feat: add cluster-agent endpoint, fix OCR labeling, fix ingestion blocking

- Add POST /api/v1/file/:file_uuid/cluster-agent endpoint for on-demand face clustering
- Fix OCR chunks being labeled as ASRX: use ChunkType.as_str() instead of {:?}
- Rule 1 now deletes old chunks before re-inserting to avoid stale data
- Add fallback face_traced.json when store_traced_faces.py fails
- ingestion_complete now handles status='error' to unblock jobs
- VLM describe tool now uses trace_id with pre-extracted face crops
This commit is contained in:
Accusys
2026-07-20 21:48:27 +08:00
parent 244af51edf
commit 7dc910e2de
8 changed files with 654 additions and 57 deletions
+252 -8
View File
@@ -1,4 +1,4 @@
use anyhow::Result;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
@@ -70,6 +70,14 @@ impl JobWorker {
self.config.max_concurrent, self.config.poll_interval_secs
);
// Layer 3: Health check on startup - repair incomplete jobs
if let Err(e) = self.health_check_incomplete_jobs().await {
warn!("[HEALTH-CHECK] Initial health check failed: {}", e);
}
let mut last_health_check = std::time::Instant::now();
let health_check_interval = std::time::Duration::from_secs(300); // 5 minutes
loop {
if !self.config.enabled {
warn!("Worker is disabled, sleeping for 60s...");
@@ -77,6 +85,14 @@ impl JobWorker {
continue;
}
// Layer 3: Periodic health check every 5 minutes
if last_health_check.elapsed() > health_check_interval {
if let Err(e) = self.health_check_incomplete_jobs().await {
warn!("[HEALTH-CHECK] Periodic health check failed: {}", e);
}
last_health_check = std::time::Instant::now();
}
if let Err(e) = self.poll_and_process().await {
error!("Error during poll and process: {}", e);
}
@@ -280,6 +296,80 @@ impl JobWorker {
Ok(())
}
/// Layer 2: Auto-repair missing processor_results based on existing output files
async fn check_and_repair_processor_results(&self, job: &crate::core::db::MonitorJob) -> Result<()> {
use std::path::Path;
// Get output directory from environment
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
// Get current processor_results
let existing_results = match self.db.get_latest_processor_results_by_file_uuid(&job.uuid).await {
Ok(r) => r,
Err(e) => {
warn!("[AUTO-REPAIR] Failed to get existing results for {}: {}", job.uuid, e);
return Err(e);
}
};
// Check all processors
let processors = crate::core::db::ProcessorType::all();
let mut repaired_count = 0;
for processor_type in processors {
let output_path = format!("{}/{}.{}.json", output_dir, job.uuid, processor_type.as_str());
// If file exists but no DB record
if Path::new(&output_path).exists() {
let has_db_record = existing_results.iter().any(|r|
r.processor_type == processor_type && r.status == crate::core::db::ProcessorJobStatus::Completed
);
if !has_db_record {
warn!("[AUTO-REPAIR] Creating missing processor_result for {} (file: {})",
processor_type.as_str(), job.uuid);
if let Err(e) = self.db.upsert_processor_result(job.id, processor_type, &job.uuid, "completed").await {
error!("[AUTO-REPAIR] Failed to create processor_result for {}: {}", processor_type.as_str(), e);
} else {
repaired_count += 1;
}
}
}
}
if repaired_count > 0 {
info!("[AUTO-REPAIR] Repaired {} processor_results for {}", repaired_count, job.uuid);
}
Ok(())
}
/// Layer 3: Periodic health check for incomplete jobs
async fn health_check_incomplete_jobs(&self) -> Result<()> {
info!("[HEALTH-CHECK] Starting periodic health check");
// Get all incomplete jobs
let jobs = self.db.get_pending_jobs(100).await?;
let mut total_repaired = 0;
for job in jobs {
if let Err(e) = self.check_and_repair_processor_results(&job).await {
warn!("[HEALTH-CHECK] Failed to repair job {}: {}", job.uuid, e);
} else {
total_repaired += 1;
}
}
if total_repaired > 0 {
info!("[HEALTH-CHECK] Checked {} jobs", total_repaired);
}
Ok(())
}
async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Check if job still exists in database (may have been deleted by unregister)
let current_job = self.db.get_monitor_job_by_uuid(&job.uuid).await?;
@@ -345,6 +435,11 @@ impl JobWorker {
.update_worker_job_status(&job.uuid, job.id, "running", None, 0, total_processor_types)
.await?;
// Layer 2: Auto-repair missing processor_results based on existing output files
if let Err(e) = self.check_and_repair_processor_results(&job).await {
warn!("[AUTO-REPAIR] Failed to check processor_results for {}: {}", job.uuid, e);
}
// Get existing processor results for this job AND completed results from previous jobs
let existing_results = self.db.get_processor_results_by_job(job.id).await?;
let mut result_map = HashMap::new();
@@ -480,13 +575,44 @@ impl JobWorker {
0,
)
.await?;
if let Err(e) = self
.db
.upsert_processor_result(job.id, *processor_type, &job.uuid, "completed")
.await
{
error!("Failed to create completed processor result: {}", e);
// Layer 1: Ensure write success with retry
let mut success = false;
for attempt in 1..=3 {
match self.db.upsert_processor_result(job.id, *processor_type, &job.uuid, "completed").await {
Ok(_) => {
success = true;
break;
}
Err(e) if attempt < 3 => {
warn!("[RETRY {}] upsert_processor_result failed for {}: {}", attempt, processor_type.as_str(), e);
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
Err(e) => {
error!("[FATAL] Failed to record {} completion after 3 retries: {}", processor_type.as_str(), e);
}
}
}
if !success {
warn!("[CONTINUE] {} completed but processor_result not recorded", processor_type.as_str());
}
// Special handling for FaceCluster: always update tkg_nodes if file exists
if *processor_type == crate::core::db::ProcessorType::FaceCluster {
if let Ok(json_str) = std::fs::read_to_string(&output_path) {
if let Ok(result) = serde_json::from_str::<
crate::core::processor::FaceClusterResult,
>(&json_str)
{
info!("[FaceCluster-SKIP] Updating tkg_nodes from existing file, {} clusters", result.clusters.len());
if let Err(e) =
Self::update_face_track_labels(&self.db, &job.uuid, &result).await
{
error!("Failed to update face track labels: {}", e);
}
}
}
}
// Load output file and store to pre_chunks
// Also dual-write to workspace if available
let workspace = WorkspaceDb::open(&job.uuid).await.ok();
@@ -746,6 +872,20 @@ impl JobWorker {
}
}
crate::core::db::ProcessorType::FaceCluster => {
if let Ok(result) = serde_json::from_str::<
crate::core::processor::FaceClusterResult,
>(&json_str)
{
info!("[FaceCluster] Parsing succeeded, {} clusters, {} frames", result.clusters.len(), result.frames.len());
if let Err(e) =
Self::update_face_track_labels(&self.db, &job.uuid, &result)
.await
{
error!("Failed to update face track labels: {}", e);
}
} else {
warn!("[FaceCluster] Failed to parse FaceClusterResult from json_str (len={})", json_str.len());
}
info!("Face clustering processor completed for {}", job.uuid);
Ok(())
}
@@ -1235,6 +1375,13 @@ impl JobWorker {
);
return true;
}
if status == "error" {
tracing::error!(
"[Ingestion] Face trace failed for {} - marking as done (with error)",
uuid
);
return true;
}
}
if let Some(traces) = traced_data.get("traces") {
@@ -1786,7 +1933,19 @@ impl JobWorker {
.await;
}
Err(e) => {
error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e)
error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e);
// Write fallback face_traced.json to unblock ingestion check
let output_dir = std::env::var("MOMENTRY_OUTPUT_DIR")
.unwrap_or_else(|_| "/Users/accusys/momentry/output".to_string());
let fallback_path = format!("{}/{}.face_traced.json", output_dir, uuid_clone);
let fallback_content = serde_json::json!({
"status": "error",
"error": e.to_string(),
"traces": {}
});
if let Err(write_err) = std::fs::write(&fallback_path, fallback_content.to_string()) {
error!("Failed to write fallback face_traced.json for {}: {}", uuid_clone, write_err);
}
}
}
});
@@ -2318,6 +2477,91 @@ impl JobWorker {
);
Ok(())
}
async fn update_face_track_labels(
db: &crate::core::db::PostgresDb,
uuid: &str,
result: &crate::core::processor::FaceClusterResult,
) -> Result<()> {
use std::collections::HashMap;
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
let scroll_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": uuid}}
]
});
let all_faces = qdrant
.scroll_all_points("_faces", scroll_filter, 1000)
.await
.context("Failed to scroll _faces from Qdrant")?;
let mut frame_to_traces: HashMap<u64, Vec<i64>> = HashMap::new();
for point in &all_faces {
let payload = &point["payload"];
if let (Some(frame), Some(trace_id)) = (
payload["frame"].as_u64(),
payload["trace_id"].as_i64(),
) {
if trace_id > 0 {
frame_to_traces.entry(frame).or_default().push(trace_id);
}
}
}
let mut trace_to_cluster: HashMap<i64, String> = HashMap::new();
for frame_data in &result.frames {
let frame = frame_data.frame;
if let Some(trace_ids) = frame_to_traces.get(&frame) {
for (idx, face) in frame_data.faces.iter().enumerate() {
if idx < trace_ids.len() {
trace_to_cluster.insert(trace_ids[idx], face.cluster_id.clone());
}
}
}
}
let tkg_table = crate::core::db::schema::table_name("tkg_nodes");
for (trace_id, cluster_id) in &trace_to_cluster {
let external_id = format!("trace_{}", trace_id);
let label = cluster_id.clone();
let rows_updated = sqlx::query(&format!(
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3",
tkg_table
))
.bind(&label)
.bind(uuid)
.bind(&external_id)
.execute(db.pool())
.await
.context("Failed to update tkg_nodes label")?
.rows_affected();
if rows_updated == 0 {
sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4)",
tkg_table
))
.bind(uuid)
.bind(&external_id)
.bind(&label)
.bind(serde_json::json!({"trace_id": trace_id}))
.execute(db.pool())
.await
.context("Failed to insert tkg_nodes")?;
}
}
info!(
"[FaceCluster] Updated {} trace labels for {}",
trace_to_cluster.len(),
uuid
);
Ok(())
}
}
#[cfg(test)]