4 Commits

Author SHA1 Message Date
Accusys d0dae475f9 fix: 確保每個 file_uuid 只有一個 monitor_job
Core Test / lint-and-test (push) Has been cancelled
Cross-Project Integration / integration (push) Has been cancelled
檢查結果:目前 DB 無重複 job,但 uuid 索引非 UNIQUE,且兩個建立路徑
(create_monitor_job 的 check-then-insert、REPAIR 的 INSERT WHERE NOT EXISTS)
都有 race,並發時可能產生重複 job。

三層防護:
- DB: CREATE UNIQUE INDEX uq_monitor_jobs_uuid ON monitor_jobs(uuid)
- create_monitor_job INSERT 改 ON CONFLICT (uuid) DO UPDATE
- REPAIR INSERT 加 ON CONFLICT (uuid) DO NOTHING

驗證:並發 5 個 process 請求 → 仍只有 1 個 job
2026-11-19 16:49:13 +08:00
Accusys 9b1618f85b fix: force re-run 可靠性 — 備份/恢復 + orphan job + stuck detector 不再毀資料
備份/恢復:
- force re-run 前備份 output 到 .backup/{uuid}/{timestamp}/,label 存 Redis
- processor 失敗時自動還原備份
- 成功後清除 backup label,避免日後誤還原舊資料

worker 穩定性:
- Worker 啟動時重置 orphan running jobs / processor_results 為 pending
  (原先只處理 error_message='Worker restarted',orphan 會永遠佔住
   backpressure 名額,讓 force re-run 的 pending job 排不到)
- detect_and_rescan_stuck_jobs 改為直接重置 job 為 pending,不再用
  force register command(unregister 會刪除 videos 記錄 + 所有 output,
  對 force re-run 是毀滅性資料遺失)
2026-11-19 16:44:39 +08:00
Accusys 8f90e98215 fix: FS VLM Summary 寫入 trace_profile.json + 新增 {uuid}.fs_vlm.json 彙總檔
- label 欄位改 Option<String>:修正 rust_store_traced_faces 寫出 null 導致
  FaceTraceProfile::load() 反序列化失敗、VLM summary 無法寫回 JSON 的問題
- VLM summary 寫入從『僅新產生時』改為『任何情況都同步 JSON』:
  DB 已有但 JSON 缺漏時重跑也會補寫
- 新增 write_vlm_summary_index():VLM 完成後產生 {uuid}.fs_vlm.json,
  含 22 筆 trace_id/vlm_summary/key_face/bbox/best_frame
- processor-json?processor=vlm_summary 優先讀 fs_vlm.json,DB 彙總為 fallback
- backfill 現有 22 筆 trace_profile.json + 產生 fs_vlm.json
2026-11-19 16:30:30 +08:00
Accusys 9758d91e0a fix: 恢復 FS VLM Summary 手動觸發 API
- 重新啟用 /api/v1/file/:file_uuid/vlm-summary 路由(之前被註解)
- 取消 trigger_vlm_summary handler 的註解
- output_dir 改用 per-library
- 規則: FS VLM Summary 只手動觸發,不在 pipeline_flows 自動執行
- 驗證: API 回傳 success, 22 traces pending
2026-11-19 15:54:36 +08:00
8 changed files with 448 additions and 56 deletions
+103 -16
View File
@@ -424,21 +424,58 @@ async fn trigger_processing(
}
tracing::info!("[TRIGGER] Cleaned processor_results for job {}", job_id);
// If force=true, delete output files to force re-processing
// If force=true, backup + delete output files to force re-processing
if req.force {
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
let per_lib_dir = crate::core::config::get_output_dir_for_file(&file_uuid, state.db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.to_string();
let output_dir = if std::path::Path::new(&per_lib_dir).is_dir() {
per_lib_dir.clone()
} else {
global_dir.clone()
};
// Build the list of files that will be deleted
let target_files: Vec<String> = if processors_to_run.is_empty() {
["asrx", "cut", "face", "face_cluster", "face_traced", "ocr", "scenes"]
.iter().map(|ext| format!("{}.{}.json", file_uuid, ext)).collect()
} else {
processors_to_run.iter().filter_map(|p| {
let ext = match p.as_str() {
"asr" => "asr", "asr_asrx" | "asrx" => "asrx",
"ocr" => "ocr", "cut" => "cut", "face" => "face",
"face_cluster" => "face_cluster", "face_trace" => "face_traced",
"scene_vlm" | "scene" => "scenes", "pose" => "pose",
"hand" => "hand", "appearance" => "appearance", "tkg" => "tkg",
_ => return None,
};
Some(format!("{}.{}.json", file_uuid, ext))
}).collect()
};
// BACKUP before deletion (per-library + global dirs)
let backup_label = crate::core::rerun_backup::backup_files(&output_dir, &file_uuid, &target_files)
.or_else(|| crate::core::rerun_backup::backup_files(&global_dir, &file_uuid, &target_files));
if let Some(label) = &backup_label {
// Store backup label in Redis so worker failure handler can restore
let key = format!("{}rerun_backup:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
let _: Result<(), _> = redis::cmd("SET").arg(&key).arg(label)
.arg("EX").arg(86400).query_async(&mut conn).await;
tracing::info!("[TRIGGER] Backup created for {} label={}", file_uuid, label);
}
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)
+ delete_output_files_for_uuid(&file_uuid, &global_dir)
} else {
// Single-processor re-run: delete only that processor's output
delete_processor_output_files(&file_uuid, &processors_to_run, &output_dir)
+ delete_processor_output_files(&file_uuid, &processors_to_run, &global_dir)
};
tracing::info!(
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?})",
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?}, backup={:?})",
deleted_count,
file_uuid,
processors_to_run
processors_to_run,
backup_label
);
// Re-running ASR/OCR/Scene VLM must also rebuild the search index:
@@ -1042,6 +1079,61 @@ async fn get_processor_json(
Json(serde_json::json!({"error": "Missing processor"})),
))?;
// FS VLM Summary: prefer the consolidated {uuid}.fs_vlm.json
// (written when VLM generation completes); fall back to DB aggregation
// for files processed before the index was introduced.
if processor == "vlm_summary" {
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, state.db.pool()).await;
let global = crate::core::config::OUTPUT_DIR.as_str();
for dir in [per_lib.trim_end_matches('/'), global.trim_end_matches('/')] {
let path = std::path::Path::new(dir).join(format!("{}.fs_vlm.json", file_uuid));
if let Ok(content) = std::fs::read_to_string(&path) {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
return Ok(Json(json));
}
}
}
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let rows: Vec<(i32, Option<String>, Option<String>)> = match sqlx::query_as(&format!(
"SELECT trace_id, vlm_description, status FROM {tp_table} \
WHERE file_uuid = $1 ORDER BY trace_id"
))
.bind(file_uuid)
.fetch_all(state.db.pool())
.await
{
Ok(r) => r,
Err(e) => {
tracing::error!("Failed to query vlm_summary for {}: {}", file_uuid, e);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": format!("DB error: {}", e)})),
));
}
};
let traces: Vec<serde_json::Value> = rows
.into_iter()
.map(|(trace_id, vlm_summary, status)| {
serde_json::json!({
"trace_id": trace_id,
"vlm_summary": vlm_summary,
"status": status,
})
})
.collect();
let total = traces.len();
let done = traces.iter().filter(|t| {
t.get("vlm_summary").and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false)
}).count();
return Ok(Json(serde_json::json!({
"file_uuid": file_uuid,
"total": total,
"done": done,
"traces": traces,
})));
}
// Map processor name to output file extension.
let ext = match processor.as_str() {
"asrx" => "asrx",
@@ -1220,9 +1312,6 @@ async fn verify_file_handler(
Json(report)
}
/// [DISABLED] FS VLM Summary removed from pipeline (2026-09-22)
/// Scene VLM (moment chunk VLM) remains active
/*
/// Manually trigger VLM summary generation for an existing file.
/// Non-blocking: returns immediately, VLM runs in background.
async fn trigger_vlm_summary(
@@ -1230,7 +1319,7 @@ async fn trigger_vlm_summary(
Path(file_uuid): Path<String>,
) -> Json<serde_json::Value> {
let db = state.db.clone();
let output_dir = crate::core::config::OUTPUT_DIR.clone();
let output_dir = crate::core::config::get_output_dir_for_file(&file_uuid, db.pool()).await;
// Check if file has face traces
let tp_table = crate::core::db::schema::table_name("trace_profiles");
@@ -1291,7 +1380,6 @@ async fn trigger_vlm_summary(
"pending": pending,
}))
}
*/
pub fn processing_routes() -> Router<AppState> {
Router::new()
@@ -1323,9 +1411,8 @@ pub fn processing_routes() -> Router<AppState> {
get(get_processor_json),
)
.route("/api/v1/file/:file_uuid/verify", get(verify_file_handler))
// [DISABLED] FS VLM Summary API removed (2026-09-22)
// .route(
// "/api/v1/file/:file_uuid/vlm-summary",
// post(trigger_vlm_summary),
// )
.route(
"/api/v1/file/:file_uuid/vlm-summary",
post(trigger_vlm_summary),
)
}
+4
View File
@@ -2395,6 +2395,10 @@ impl PostgresDb {
r#"
INSERT INTO {} (uuid, video_path, status, video_id, processors, face_settings)
VALUES ($1, $2, 'pending', $3, {}::text[], $4::jsonb)
ON CONFLICT (uuid) DO UPDATE SET
status = 'pending', video_path = EXCLUDED.video_path,
video_id = EXCLUDED.video_id, processors = EXCLUDED.processors,
face_settings = EXCLUDED.face_settings, updated_at = NOW()
RETURNING id, uuid, video_path, status, current_processor, progress_total, progress_current, error_count, last_error, started_at::TEXT, updated_at::TEXT, created_at::TEXT, processors, completed_processors, failed_processors, video_id, face_settings::text
"#,
jobs_table, processors_array
+3 -2
View File
@@ -529,7 +529,8 @@ pub struct FaceTraceProfile {
pub version: String,
pub file_uuid: String,
pub trace_id: i64,
pub label: String,
#[serde(default)]
pub label: Option<String>,
pub frame_count: i64,
pub start_frame: i64,
pub end_frame: i64,
@@ -615,7 +616,7 @@ impl FaceTraceProfile {
version: PROFILE_VERSION.to_string(),
file_uuid: file_uuid.to_string(),
trace_id,
label: label.to_string(),
label: Some(label.to_string()),
frame_count,
start_frame,
end_frame,
+1
View File
@@ -45,3 +45,4 @@ pub mod vlm;
pub mod json_debug;
pub mod json_standardize;
pub mod rerun_backup;
+98 -13
View File
@@ -151,9 +151,77 @@ pub async fn generate_vlm_summaries(
file_uuid, result.summarized, result.total, result.embedded, result.errors
);
// Write a single consolidated {uuid}.fs_vlm.json next to the other
// processor outputs, so the UI can open it just like face.json / ocr.json.
write_vlm_summary_index(db, file_uuid, output_dir).await;
result
}
/// Build `{output_dir}/{file_uuid}.fs_vlm.json` from DB + per-trace
/// trace_profile.json (for key_face / bbox / best_frame context).
pub async fn write_vlm_summary_index(db: &PostgresDb, file_uuid: &str, output_dir: &str) {
let tp_table = table_name("trace_profiles");
let rows: Vec<(i32, Option<String>, Option<String>)> = match sqlx::query_as(&format!(
"SELECT trace_id, vlm_description, status FROM {tp_table} \
WHERE file_uuid = $1 ORDER BY trace_id"
))
.bind(file_uuid)
.fetch_all(db.pool())
.await
{
Ok(r) => r,
Err(e) => {
warn!("[VLM] Failed to build summary index for {}: {}", file_uuid, e);
return;
}
};
let mut traces = Vec::new();
for (tid, desc, status) in rows {
let mut item = serde_json::json!({
"trace_id": tid,
"vlm_summary": desc,
"status": status,
});
if let Some(p) = crate::core::file_profile::FaceTraceProfile::load(
output_dir,
file_uuid,
tid as i64,
) {
let prefix = format!("trace_{}", tid);
item["key_frame"] = serde_json::json!(p.key_frame.as_ref().map(|f| format!("{}/{}", prefix, f)));
item["key_face"] = serde_json::json!(p.key_face.as_ref().map(|f| format!("{}/{}", prefix, f)));
item["best_frame"] = serde_json::json!(p.best_frame);
item["frame_count"] = serde_json::json!(p.frame_count);
item["avg_bbox"] = serde_json::json!(p.avg_bbox);
item["best_bbox"] = serde_json::json!(p.best_bbox);
item["avg_confidence"] = serde_json::json!(p.avg_confidence);
}
traces.push(item);
}
let done = traces
.iter()
.filter(|t| t.get("vlm_summary").and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false))
.count();
let index = serde_json::json!({
"file_uuid": file_uuid,
"generated_at": chrono::Utc::now().to_rfc3339(),
"total": traces.len(),
"done": done,
"traces": traces,
});
let path = std::path::Path::new(output_dir).join(format!("{}.fs_vlm.json", file_uuid));
match serde_json::to_string_pretty(&index) {
Ok(content) => match std::fs::write(&path, content) {
Ok(_) => info!("[VLM] Wrote summary index {} ({} traces)", path.display(), traces.len()),
Err(e) => warn!("[VLM] Failed to write summary index {}: {}", path.display(), e),
},
Err(e) => warn!("[VLM] Failed to serialize summary index: {}", e),
}
}
async fn process_single_trace(
db: &PostgresDb,
file_uuid: &str,
@@ -293,32 +361,49 @@ async fn process_single_trace(
);
}
// Update on-disk trace_profile.json
summary
} else {
existing_desc.unwrap_or_default()
};
// Ensure on-disk trace_profile.json contains the summary. This runs even when
// the summary already existed in DB but was missing from JSON (e.g. an earlier
// save silently failed), so re-running the manual VLM summary always repairs it.
{
let profile_path = crate::core::file_profile::FaceTraceProfile::profile_path(
output_dir,
file_uuid,
trace_id_i64,
);
if profile_path.exists() {
if let Some(mut profile) = crate::core::file_profile::FaceTraceProfile::load(
match crate::core::file_profile::FaceTraceProfile::load(
output_dir,
file_uuid,
trace_id_i64,
) {
profile.vlm_summary = Some(summary.clone());
if let Err(e) = profile.save(output_dir, None, None) {
warn!(
"[VLM] trace {}/{} (tid={}): JSON save failed: {}",
current, total, trace_id, e
);
Some(mut profile) => {
if profile.vlm_summary.as_deref() != Some(summary.as_str()) {
profile.vlm_summary = Some(summary.clone());
if let Err(e) = profile.save(output_dir, None, None) {
warn!(
"[VLM] trace {}/{} (tid={}): JSON save failed: {}",
current, total, trace_id, e
);
} else {
info!(
"[VLM] trace {}/{} (tid={}): JSON vlm_summary written",
current, total, trace_id
);
}
}
}
None => warn!(
"[VLM] trace {}/{} (tid={}): trace_profile.json exists but load() failed — summary NOT written to JSON (DB still OK)",
current, total, trace_id
),
}
}
summary
} else {
existing_desc.unwrap_or_default()
};
}
// Generate embedding and store in Qdrant if needed
if !need_embed {
+149
View File
@@ -0,0 +1,149 @@
//! Rerun backup/rollback — 在 force re-run 前備份既有 output,
//! 若 processor 失敗則自動還原,避免資料遺失。
//!
//! 备份目录: {output_root}/.backup/{uuid}/{timestamp}/
//! 每个 processor 的备份记录: manifest.json { "filename": "path" }
use std::path::{Path, PathBuf};
use tracing::{info, warn};
/// Backup dir root: parent of per-library output dir (i.e. output/.backup/)
fn backup_root(output_dir: &str) -> PathBuf {
let p = Path::new(output_dir);
// output/test -> output ; output/demo -> output
let root = p
.parent()
.filter(|par| par.file_name().and_then(|n| n.to_str()) == Some("output"))
.unwrap_or(p);
root.join(".backup")
}
/// Timestamp label for this rerun session (unix millis)
fn timestamp_label() -> String {
chrono::Utc::now().timestamp_millis().to_string()
}
/// Backup specific files before they are deleted for a force re-run.
/// `output_dir`: per-library output dir (e.g. output/test)
/// `filenames`: list of json filenames to back up (e.g. ["uuid.face.json"])
/// Returns the backup dir path (relative label) for later restore.
pub fn backup_files(
output_dir: &str,
file_uuid: &str,
filenames: &[String],
) -> Option<String> {
let existing: Vec<&String> = filenames
.iter()
.filter(|name| Path::new(output_dir).join(name).exists())
.collect();
if existing.is_empty() {
return None;
}
let label = timestamp_label();
let backup_dir = backup_root(output_dir).join(file_uuid).join(&label);
if let Err(e) = std::fs::create_dir_all(&backup_dir) {
warn!("[RERUN-BACKUP] Failed to create backup dir {:?}: {}", backup_dir, e);
return None;
}
let mut manifest = serde_json::Map::new();
for name in existing {
let src = Path::new(output_dir).join(name);
let dst = backup_dir.join(name);
match std::fs::copy(&src, &dst) {
Ok(_) => {
manifest.insert(name.clone(), serde_json::Value::String(name.to_string()));
info!("[RERUN-BACKUP] Backed up {} -> {:?}", name, dst);
}
Err(e) => warn!("[RERUN-BACKUP] Failed to back up {}: {}", name, e),
}
}
// Write manifest
let manifest_path = backup_dir.join("manifest.json");
if let Ok(content) = serde_json::to_string_pretty(&serde_json::Value::Object(manifest)) {
let _ = std::fs::write(&manifest_path, content);
}
Some(label)
}
/// Restore files from a backup session.
/// `output_dir`: per-library output dir
/// `label`: backup session label returned by backup_files()
/// Returns number of files restored.
pub fn restore_files(output_dir: &str, file_uuid: &str, label: &str) -> usize {
let backup_dir = backup_root(output_dir).join(file_uuid).join(label);
let manifest_path = backup_dir.join("manifest.json");
let manifest: serde_json::Value = match std::fs::read_to_string(&manifest_path)
.ok()
.and_then(|s| serde_json::from_str(&s).ok())
{
Some(m) => m,
None => {
warn!("[RERUN-RESTORE] No manifest at {:?}", manifest_path);
return 0;
}
};
let mut restored = 0;
if let Some(obj) = manifest.as_object() {
for name in obj.keys() {
let src = backup_dir.join(name);
let dst = Path::new(output_dir).join(name);
if src.exists() {
if let Some(parent) = dst.parent() {
let _ = std::fs::create_dir_all(parent);
}
match std::fs::copy(&src, &dst) {
Ok(_) => {
info!("[RERUN-RESTORE] Restored {} from {:?}", name, backup_dir);
restored += 1;
}
Err(e) => warn!("[RERUN-RESTORE] Failed to restore {}: {}", name, e),
}
}
}
}
restored
}
/// Mark a backup session as successful (cleanup) or keep for rollback.
/// On success we keep the backup for a while (user can manually restore),
/// so this only removes backups older than `keep_days`.
pub fn cleanup_old_backups(output_dir: &str, file_uuid: &str, keep_days: i64) -> usize {
let uuid_dir = backup_root(output_dir).join(file_uuid);
let cutoff = chrono::Utc::now().timestamp_millis() - keep_days * 24 * 60 * 60 * 1000;
let mut removed = 0;
if let Ok(entries) = std::fs::read_dir(&uuid_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if let Ok(ts) = name.parse::<i64>() {
if ts < cutoff {
let _ = std::fs::remove_dir_all(entry.path());
removed += 1;
}
}
}
}
}
removed
}
/// Get the latest backup session label for a file (for manual restore UI)
pub fn latest_backup_label(output_dir: &str, file_uuid: &str) -> Option<String> {
let uuid_dir = backup_root(output_dir).join(file_uuid);
let mut labels: Vec<(i64, String)> = Vec::new();
if let Ok(entries) = std::fs::read_dir(&uuid_dir) {
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
if let Ok(ts) = name.parse::<i64>() {
labels.push((ts, name.to_string()));
}
}
}
}
labels.sort_by_key(|x| x.0);
labels.last().map(|x| x.1.clone())
}
+53 -24
View File
@@ -346,7 +346,8 @@ impl JobWorker {
FROM {v_t} v
WHERE v.status = 'pending'
AND v.file_type IN ('video', 'mp4', 'mov', 'avi', 'mkv')
AND NOT EXISTS (SELECT 1 FROM {mj_t} mj WHERE mj.uuid = v.file_uuid)",
AND NOT EXISTS (SELECT 1 FROM {mj_t} mj WHERE mj.uuid = v.file_uuid)
ON CONFLICT (uuid) DO NOTHING",
mj_t = monitor_jobs_table,
v_t = videos_table
))
@@ -729,6 +730,37 @@ impl JobWorker {
let processor_results_table = schema::table_name("processor_results");
let monitor_jobs_table = schema::table_name("monitor_jobs");
// 0. Worker 剛啟動,不可能有任何 live process。把上次 session 遺留的
// running job 全部退回 pending,連同未完成的 processor_results。
// 否則這些 orphan job 會一直佔住 backpressure 名額,讓新的(例如
// force re-run)pending job 永遠排不到。
let orphan_processors = sqlx::query(&format!(
"UPDATE {processor_results_table} pr
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
FROM {monitor_jobs_table} mj
WHERE pr.job_id = mj.id
AND mj.status = 'running'
AND pr.status IN ('running', 'pending')"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
let orphan_jobs = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
WHERE status = 'running'"
))
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if orphan_jobs > 0 || orphan_processors > 0 {
info!(
"[RECOVER] Worker 啟動:重置 {} 個 orphan jobs / {} 個 orphan processors 為 pending",
orphan_jobs, orphan_processors
);
}
// 1. 重置所有被 worker 重啟中斷的處理器
let recovered = sqlx::query(&format!(
"UPDATE {processor_results_table}
@@ -1044,35 +1076,36 @@ impl JobWorker {
continue;
}
// 與 GUI re-scan 相同:register command(force=true → unregister →
// register → deep scan)。先將 job 標記 paused,避免 command 尚未
// 執行的這一輪又被偵測重複排入。
// 直接重置卡住的 job,不 unregister、不刪 output。
// 原本用 force register command 會觸發 unregister → 清除所有 output,
// 對 force re-run 是資料毀損(備份還在但 job 被刪、output 消失)。
// 這裡只把 job 與未完成的 processor 退回 pending,讓 worker 重新認領,
// 保留所有既有產出。
let reset_pr = sqlx::query(&format!(
"UPDATE {processor_results_table}
SET status = 'pending', retry_count = 0, error_message = NULL, updated_at = NOW()
WHERE job_id = $1 AND status IN ('running', 'pending')"
))
.bind(job_id)
.execute(self.db.pool())
.await
.map(|r| r.rows_affected())
.unwrap_or(0);
if let Err(e) = sqlx::query(&format!(
"UPDATE {monitor_jobs_table} SET status = 'paused', updated_at = NOW()
"UPDATE {monitor_jobs_table} SET status = 'pending', updated_at = NOW()
WHERE uuid = $1 AND status = 'running'"
))
.bind(&uuid)
.execute(self.db.pool())
.await
{
error!("[STUCK-RESCAN] 無法暫停卡住 job {}: {}", uuid, e);
error!("[STUCK-RESCAN] 無法重置卡住 job {}: {}", uuid, e);
continue;
}
let payload = serde_json::json!({
"force": true,
"deep_scan": true,
"trigger_source": "worker_stuck_auto",
});
match self
.db
.create_command("register", Some(&file_path), None, None, &payload, 1)
.await
{
Ok(cmd) => {
info!(
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已自動 re-scan(command={},第 {} 次)",
uuid, timeout_min, cmd.command_id, rescan_count + 1
"[STUCK-RESCAN] job {} 卡住超過 {} 分鐘(fingerprint 無變化),已重置為 pending({} 個 processor,第 {} 次)",
uuid, timeout_min, reset_pr, rescan_count + 1
);
let _: Result<i64, _> = redis::cmd("INCR")
.arg(&counter_key)
@@ -1083,13 +1116,9 @@ impl JobWorker {
.arg(86_400i64)
.query_async(&mut conn)
.await;
// 清除觀察 key(job 將被 unregister 刪除重建)
// 清除觀察 key
let _: Result<(), _> = redis::cmd("DEL").arg(&fp_key).query_async(&mut conn).await;
let _: Result<(), _> = redis::cmd("DEL").arg(&since_key).query_async(&mut conn).await;
}
Err(e) => {
error!("[STUCK-RESCAN] 為 {} 建立 re-scan command 失敗: {}", uuid, e);
}
}
}
+37 -1
View File
@@ -142,6 +142,24 @@ const FRAME_SLOT_MAX: usize = 4;
/// Increased from 1 to 2 to improve throughput.
const TIME_SLOT_MAX: usize = 2;
/// Restore backed-up outputs when a forced re-run processor fails.
async fn restore_backup_on_failure(db: &crate::core::db::PostgresDb, redis: &crate::core::db::RedisClient, file_uuid: &str) {
let key = format!("{}rerun_backup:{}", crate::core::config::REDIS_KEY_PREFIX.as_str(), file_uuid);
let label: Option<String> = match redis.get_conn().await {
Ok(mut conn) => redis::cmd("GET").arg(&key).query_async(&mut conn).await.ok().flatten(),
Err(_) => None,
};
if let Some(label) = label {
let per_lib = crate::core::config::get_output_dir_for_file(file_uuid, db.pool()).await;
let global_dir = crate::core::config::OUTPUT_DIR.to_string();
let restored = crate::core::rerun_backup::restore_files(&per_lib, file_uuid, &label)
+ crate::core::rerun_backup::restore_files(&global_dir, file_uuid, &label);
if restored > 0 {
tracing::warn!("[RERUN-RESTORE] Restored {} files for {} after processor failure", restored, file_uuid);
}
}
}
pub struct ProcessorPool {
db: Arc<PostgresDb>,
redis: Arc<RedisClient>,
@@ -583,6 +601,19 @@ impl ProcessorPool {
error!("Failed to update Redis processor status: {}", e);
}
// Re-run succeeded — drop the rollback label so a later
// failure on this file never restores this stale backup.
{
let key = format!(
"{}rerun_backup:{}",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
job.uuid
);
if let Ok(mut c) = redis.get_conn().await {
let _: Result<(), _> = redis::cmd("DEL").arg(&key).query_async(&mut c).await;
}
}
// Also update PostgreSQL processing_status JSON
if let Err(e) = db
.update_processor_progress(
@@ -615,6 +646,9 @@ impl ProcessorPool {
error!("Failed to update processor result to failed: {}", db_err);
}
// Restore backed-up output if this was a forced re-run
restore_backup_on_failure(db.as_ref(), redis.as_ref(), &job.uuid).await;
if let Err(redis_err) = redis
.update_worker_processor_status(
&job.uuid,
@@ -638,6 +672,8 @@ impl ProcessorPool {
"Processor {} failed for job {}: {}",
processor_name, job.uuid, e
);
// Restore backed-up output if this was a forced re-run
restore_backup_on_failure(db.as_ref(), redis.as_ref(), &job.uuid).await;
if let Err(db_err) = db
.update_processor_result_with_stats(
processor_result_id,
@@ -677,7 +713,7 @@ impl ProcessorPool {
async fn run_processor(
db: &PostgresDb,
_redis: &RedisClient,
redis: &RedisClient,
job: &MonitorJob,
processor_type: ProcessorType,
_cancel_rx: mpsc::Receiver<()>,