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
This commit is contained in:
Accusys
2026-11-19 16:30:30 +08:00
parent 9758d91e0a
commit 8f90e98215
6 changed files with 373 additions and 22 deletions
+98 -6
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",
+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())
}
+24 -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>,
@@ -615,6 +633,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 +659,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 +700,7 @@ impl ProcessorPool {
async fn run_processor(
db: &PostgresDb,
_redis: &RedisClient,
redis: &RedisClient,
job: &MonitorJob,
processor_type: ProcessorType,
_cancel_rx: mpsc::Receiver<()>,