feat: add TraceArtifacts phase + VLM waits for all key_frame.jpg

- Add TraceArtifacts phase to TkgPhase enum (phase 18)
- Report progress as key_frame.jpg/key_face.jpg are created
- VLM trigger now polls until ALL key_frame.jpg files exist
  (was: started after TKG build, before artifacts were ready)
- Add iron rule to AGENTS.md: ask before removing data

Tested: Gamma 8 (27 traces) → 27/27 VLM summaries completed
This commit is contained in:
Accusys
2026-08-24 19:13:11 +08:00
parent d29b4804af
commit 9f12e835b8
43 changed files with 3993 additions and 491 deletions
+39 -37
View File
@@ -148,9 +148,7 @@ pub async fn trigger_cluster_agent(
// Check for existing running job for this file
let registry = CLUSTER_JOB_REGISTRY.read().await;
for (job_id, handle) in registry.iter() {
if handle.file_uuid == file_uuid
&& matches!(handle.status, ClusterJobStatus::Running)
{
if handle.file_uuid == file_uuid && matches!(handle.status, ClusterJobStatus::Running) {
return Ok(Json(ClusterAgentResponse {
success: false,
job_id: job_id.clone(),
@@ -215,7 +213,14 @@ pub async fn trigger_cluster_agent(
let total_traces = count_total_traces(&state, &file_uuid).await.unwrap_or(0);
let job_id = format!("cluster_{}_{}", file_uuid, std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs());
let job_id = format!(
"cluster_{}_{}",
file_uuid,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
);
let output_path =
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
let cancel_token = tokio_util::sync::CancellationToken::new();
@@ -307,9 +312,10 @@ pub async fn trigger_cluster_agent(
// Build frames list
let frames = if total_frames > 0 {
let fps_val = if fps > 0.0 { fps } else { 30.0 };
Some(
crate::core::processor::PythonExecutor::compute_8hz_frames(total_frames, fps_val),
)
Some(crate::core::processor::PythonExecutor::compute_8hz_frames(
total_frames,
fps_val,
))
} else {
None
};
@@ -340,12 +346,9 @@ pub async fn trigger_cluster_agent(
}
// Update trace labels
let _ = update_trace_labels_from_cluster(
&db_clone,
&file_uuid_clone,
&cluster_result,
)
.await;
let _ =
update_trace_labels_from_cluster(&db_clone, &file_uuid_clone, &cluster_result)
.await;
handle.status = ClusterJobStatus::Completed;
handle.progress = 1.0;
@@ -371,7 +374,10 @@ pub async fn trigger_cluster_agent(
let job_id_for_cleanup = job_id_clone.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(300)).await;
CLUSTER_JOB_REGISTRY.write().await.remove(&job_id_for_cleanup);
CLUSTER_JOB_REGISTRY
.write()
.await
.remove(&job_id_for_cleanup);
});
});
@@ -401,10 +407,16 @@ pub async fn get_cluster_job_status(
})?;
let (status_str, message) = match &handle.status {
ClusterJobStatus::Running => ("running".to_string(), Some("Clustering in progress".to_string())),
ClusterJobStatus::Running => (
"running".to_string(),
Some("Clustering in progress".to_string()),
),
ClusterJobStatus::Completed => ("completed".to_string(), None),
ClusterJobStatus::Failed(msg) => ("failed".to_string(), Some(msg.clone())),
ClusterJobStatus::Cancelled => ("cancelled".to_string(), Some("Job was cancelled".to_string())),
ClusterJobStatus::Cancelled => (
"cancelled".to_string(),
Some("Job was cancelled".to_string()),
),
};
Ok(Json(ClusterJobStatusResponse {
@@ -414,7 +426,11 @@ pub async fn get_cluster_job_status(
progress: if matches!(handle.status, ClusterJobStatus::Running) {
Some(handle.progress)
} else {
Some(if matches!(handle.status, ClusterJobStatus::Completed) { 1.0 } else { handle.progress })
Some(if matches!(handle.status, ClusterJobStatus::Completed) {
1.0
} else {
handle.progress
})
},
message,
clusters: handle.clusters,
@@ -524,14 +540,8 @@ async fn update_trace_labels_from_cluster(
.await?;
}
let _ = schema::upsert_trace_profile(
db.pool(),
file_uuid,
*trace_id as i32,
&label,
None,
)
.await;
let _ = schema::upsert_trace_profile(db.pool(), file_uuid, *trace_id as i32, &label, None)
.await;
}
if let Some(all_trace_ids) = get_all_trace_ids(file_uuid) {
@@ -539,14 +549,9 @@ async fn update_trace_labels_from_cluster(
for tid in &all_trace_ids {
if !trace_to_cluster.contains_key(tid) {
let name = format!("Person_{}", tid);
let _ = schema::upsert_trace_profile(
db.pool(),
file_uuid,
*tid as i32,
&name,
None,
)
.await;
let _ =
schema::upsert_trace_profile(db.pool(), file_uuid, *tid as i32, &name, None)
.await;
updated_count += 1;
}
}
@@ -587,10 +592,7 @@ fn get_all_trace_ids(file_uuid: &str) -> Option<Vec<i64>> {
}
}
async fn count_total_traces(
state: &AppState,
file_uuid: &str,
) -> anyhow::Result<usize> {
async fn count_total_traces(state: &AppState, file_uuid: &str) -> anyhow::Result<usize> {
let tkg_table = schema::table_name("tkg_nodes");
let count: (i64,) = sqlx::query_as(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1 AND node_type = 'face_track'",
+73 -54
View File
@@ -12,8 +12,8 @@ use std::collections::HashMap;
use super::types::AppState;
use crate::core::db::schema;
use crate::core::face_filter_engine::{
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine, FilterRecommendation,
FilterRuleConfig, RuleResult,
default_filter_config, FaceFilterFeatures, FaceFilterResult, FilterEngine,
FilterRecommendation, FilterRuleConfig, RuleResult,
};
/// Request to filter faces
@@ -43,7 +43,7 @@ pub struct FilteredFaceInfo {
/// Request to get faces with filtering
#[derive(Debug, Deserialize)]
pub struct GetFacesRequest {
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
pub source: Option<String>, // "all" | "apple_vision" | "mediapipe"
pub page: Option<usize>,
pub page_size: Option<usize>,
}
@@ -134,24 +134,21 @@ pub async fn get_faces(
page: Some(1),
page_size: Some(50),
});
let page = req.page.unwrap_or(1);
let page_size = req.page_size.unwrap_or(50);
let offset = (page - 1) * page_size;
// Get total count
let filter_table = schema::table_name("face_filter_features");
let count_query = format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid = $1",
filter_table
);
let count_query = format!("SELECT COUNT(*) FROM {} WHERE file_uuid = $1", filter_table);
let total: i64 = sqlx::query_scalar(&count_query)
.bind(&file_uuid)
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Get faces with filter features
let faces_query = format!(
"SELECT face_id, frame, primary_source, apple_vision_confidence, mediapipe_confidence,
@@ -163,7 +160,7 @@ pub async fn get_faces(
LIMIT $2 OFFSET $3",
filter_table
);
let rows = sqlx::query(&faces_query)
.bind(&file_uuid)
.bind(page_size as i64)
@@ -171,7 +168,7 @@ pub async fn get_faces(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
// Build response
let faces: Vec<FaceInfo> = rows
.into_iter()
@@ -182,7 +179,7 @@ pub async fn get_faces(
let av_conf: Option<f64> = row.get(3);
let mp_conf: Option<f64> = row.get(4);
let bbox_size: Option<i32> = row.get(5);
FaceInfo {
face_id: face_id.clone(),
frame,
@@ -218,7 +215,7 @@ pub async fn get_faces(
}
})
.collect();
// Get source summary
let summary_query = format!(
"SELECT
@@ -229,19 +226,19 @@ pub async fn get_faces(
WHERE file_uuid = $1",
filter_table
);
let summary_row = sqlx::query(&summary_query)
.bind(&file_uuid)
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let apple_vision: i64 = summary_row.get(0);
let mediapipe: i64 = summary_row.get(1);
let merged_unique: i64 = summary_row.get(2);
let total_pages = ((total as f64) / (page_size as f64)).ceil() as usize;
Ok(Json(GetFacesResponse {
faces,
pagination: PaginationInfo {
@@ -264,7 +261,7 @@ pub async fn get_face_filter_report(
Path((file_uuid, face_id)): Path<(String, String)>,
) -> Result<Json<FaceFilterResult>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
let row = sqlx::query(&format!(
"SELECT face_id, frame, bbox_size, eye_ratio, nose_ratio, pose_score,
mediapipe_detected, mediapipe_iou, embedding_similarity,
@@ -279,7 +276,7 @@ pub async fn get_face_filter_report(
.fetch_optional(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
match row {
Some(row) => {
let features = FaceFilterFeatures {
@@ -299,13 +296,15 @@ pub async fn get_face_filter_report(
mediapipe_confidence: row.get(12),
primary_source: row.get(13),
};
// Apply default filter rules
let config = default_filter_config();
let engine = FilterEngine::new(config);
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let result = engine
.filter_face(&features)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(result))
}
None => Err(StatusCode::NOT_FOUND),
@@ -319,7 +318,7 @@ pub async fn filter_faces(
req: Json<FilterFacesRequest>,
) -> Result<Json<FilterFacesResponse>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
// Get all faces for this file
let rows = sqlx::query(&format!(
"SELECT face_id, frame, bbox_size, eye_ratio, nose_ratio, pose_score,
@@ -334,19 +333,19 @@ pub async fn filter_faces(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let total_faces = rows.len() as i32;
// Use provided rules or default
let config = req.0.rules.clone().unwrap_or_else(default_filter_config);
let engine = FilterEngine::new(config);
// Apply filters
let mut passed = 0;
let mut filtered = 0;
let mut filtered_faces = Vec::new();
let mut filter_stats: HashMap<String, i64> = HashMap::new();
for row in rows {
let features = FaceFilterFeatures {
face_id: row.get(0),
@@ -365,17 +364,22 @@ pub async fn filter_faces(
mediapipe_confidence: row.get(12),
primary_source: row.get(13),
};
let result = engine.filter_face(&features).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let result = engine
.filter_face(&features)
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
if result.recommendation == FilterRecommendation::Accept {
passed += 1;
} else {
filtered += 1;
// Count reasons before moving
for reason in &result.reasons {
let key = if reason.contains("eye_ratio") || reason.contains("nose_ratio") || reason.contains("pose_score") {
let key = if reason.contains("eye_ratio")
|| reason.contains("nose_ratio")
|| reason.contains("pose_score")
{
"landmark".to_string()
} else if reason.contains("MediaPipe") {
"mediapipe".to_string()
@@ -386,10 +390,10 @@ pub async fn filter_faces(
} else {
"other".to_string()
};
*filter_stats.entry(key).or_insert(0) += 1;
}
filtered_faces.push(FilteredFaceInfo {
face_id: result.face_id,
frame: result.frame,
@@ -397,9 +401,9 @@ pub async fn filter_faces(
});
}
}
let filter_stats_json = serde_json::to_value(&filter_stats).unwrap_or_default();
Ok(Json(FilterFacesResponse {
total_faces,
passed,
@@ -415,7 +419,7 @@ pub async fn get_filter_stats(
Path(file_uuid): Path<String>,
) -> Result<Json<FilterStatsResponse>, StatusCode> {
let filter_table = schema::table_name("face_filter_features");
let row = sqlx::query(&format!(
"SELECT
COUNT(*) as total,
@@ -435,7 +439,7 @@ pub async fn get_filter_stats(
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let stats = serde_json::json!({
"total_faces": row.get::<i64, _>(0),
"by_source": {
@@ -451,7 +455,7 @@ pub async fn get_filter_stats(
"avg_consecutive_frames": row.get::<Option<f64>, _>(8),
}
});
Ok(Json(FilterStatsResponse {
total_faces: row.get(0),
by_category: stats,
@@ -465,9 +469,9 @@ pub async fn save_filter_rules(
req: Json<SaveFilterRulesRequest>,
) -> Result<Json<FilterRuleInfo>, StatusCode> {
let rules_table = schema::table_name("filter_rules");
let is_active = req.is_active.unwrap_or(true);
let row = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, rule_name, rules, is_active)
VALUES ($1, $2, $3, $4)
@@ -483,9 +487,9 @@ pub async fn save_filter_rules(
.fetch_one(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let rules: FilterRuleConfig = serde_json::from_value(row.get(2)).unwrap();
Ok(Json(FilterRuleInfo {
id: row.get(0),
rule_name: row.get(1),
@@ -502,7 +506,7 @@ pub async fn get_filter_rules(
Path(file_uuid): Path<String>,
) -> Result<Json<FilterRulesResponse>, StatusCode> {
let rules_table = schema::table_name("filter_rules");
let rows = sqlx::query(&format!(
"SELECT id, rule_name, rules, is_active, created_at::TEXT, updated_at::TEXT
FROM {}
@@ -514,7 +518,7 @@ pub async fn get_filter_rules(
.fetch_all(state.db.pool())
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let rules: Vec<FilterRuleInfo> = rows
.into_iter()
.map(|row| {
@@ -529,7 +533,7 @@ pub async fn get_filter_rules(
}
})
.collect();
Ok(Json(FilterRulesResponse { rules }))
}
@@ -537,9 +541,24 @@ pub async fn get_filter_rules(
pub fn face_filter_routes() -> Router<AppState> {
Router::new()
.route("/api/v1/file/:file_uuid/face-filter/faces", get(get_faces))
.route("/api/v1/file/:file_uuid/face-filter/:face_id/report", get(get_face_filter_report))
.route("/api/v1/file/:file_uuid/face-filter/apply", post(filter_faces))
.route("/api/v1/file/:file_uuid/face-filter/stats", get(get_filter_stats))
.route("/api/v1/file/:file_uuid/face-filter/rules", get(get_filter_rules))
.route("/api/v1/file/:file_uuid/face-filter/rules", post(save_filter_rules))
.route(
"/api/v1/file/:file_uuid/face-filter/:face_id/report",
get(get_face_filter_report),
)
.route(
"/api/v1/file/:file_uuid/face-filter/apply",
post(filter_faces),
)
.route(
"/api/v1/file/:file_uuid/face-filter/stats",
get(get_filter_stats),
)
.route(
"/api/v1/file/:file_uuid/face-filter/rules",
get(get_filter_rules),
)
.route(
"/api/v1/file/:file_uuid/face-filter/rules",
post(save_filter_rules),
)
}
+6 -5
View File
@@ -1062,10 +1062,7 @@ async fn search_file_faces(
let where_sql = where_clauses.join(" AND ");
// Count total
let count_sql = format!(
"SELECT COUNT(*) FROM {} tp WHERE {}",
tp_table, where_sql
);
let count_sql = format!("SELECT COUNT(*) FROM {} tp WHERE {}", tp_table, where_sql);
let mut count_query = sqlx::query_scalar::<_, i64>(&count_sql).bind(&file_uuid);
if let Some(ref q) = params.q {
@@ -1110,7 +1107,11 @@ async fn search_file_faces(
WHERE {} \
ORDER BY tp.start_frame ASC \
LIMIT ${} OFFSET ${}",
tp_table, video_table, where_sql, param_idx, param_idx + 1
tp_table,
video_table,
where_sql,
param_idx,
param_idx + 1
);
let mut data_query = sqlx::query(&data_sql).bind(&file_uuid);
+16 -4
View File
@@ -1773,7 +1773,10 @@ async fn get_face_landmarks_handler(
let face_path = std::path::Path::new(output_dir).join(format!("{}.face.json", file_uuid));
if !face_path.exists() {
tracing::error!("[get_face_landmarks] File not found: {}", face_path.display());
tracing::error!(
"[get_face_landmarks] File not found: {}",
face_path.display()
);
return Err(StatusCode::NOT_FOUND);
}
@@ -1840,7 +1843,10 @@ async fn get_face_landmarks_handler(
y: face.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: face.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: face.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: face.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
confidence: face
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0),
})
.collect();
@@ -1850,8 +1856,14 @@ async fn get_face_landmarks_handler(
y: selected.get("y").and_then(|v| v.as_i64()).unwrap_or(0),
width: selected.get("width").and_then(|v| v.as_i64()).unwrap_or(0),
height: selected.get("height").and_then(|v| v.as_i64()).unwrap_or(0),
confidence: selected.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0),
pose_angle: selected.get("pose_angle").cloned().or_else(|| selected.get("pose").cloned()),
confidence: selected
.get("confidence")
.and_then(|v| v.as_f64())
.unwrap_or(0.0),
pose_angle: selected
.get("pose_angle")
.cloned()
.or_else(|| selected.get("pose").cloned()),
landmarks: selected
.get("landmarks")
.cloned()
+23 -8
View File
@@ -267,15 +267,21 @@ pub async fn request_logger(request: Request, next: Next) -> Response {
let query = request.uri().query().unwrap_or("").to_string();
// Skip health checks and static files to reduce noise
if path == "/api/v1/health"
|| path.starts_with("/static")
|| path.starts_with("/favicon")
{
if path == "/api/v1/health" || path.starts_with("/static") || path.starts_with("/favicon") {
return next.run(request).await;
}
let start = std::time::Instant::now();
tracing::info!("[API Request] {} {}{}", method, path, if query.is_empty() { String::new() } else { format!("?{}", query) });
tracing::info!(
"[API Request] {} {}{}",
method,
path,
if query.is_empty() {
String::new()
} else {
format!("?{}", query)
}
);
let response = next.run(request).await;
let duration = start.elapsed();
@@ -286,17 +292,26 @@ pub async fn request_logger(request: Request, next: Next) -> Response {
if status.is_server_error() {
tracing::error!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
} else if status.is_client_error() {
tracing::warn!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
} else {
tracing::info!(
"[API Response] {} {} -> {} ({}ms)",
method, path, status, duration_ms
method,
path,
status,
duration_ms
);
}
+22 -24
View File
@@ -120,31 +120,36 @@ pub async fn get_trace_profile_handler(
let external_id_face = format!("face_track_{}", params.trace_id);
let external_id_trace = format!("trace_{}", params.trace_id);
let row: Option<(String, String, Option<serde_json::Value>, Option<serde_json::Value>)> =
sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
let row: Option<(
String,
String,
Option<serde_json::Value>,
Option<serde_json::Value>,
)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
tp.properties, tn.properties \
FROM {} tn \
LEFT JOIN {} tp ON tp.file_uuid = tn.file_uuid \
AND tp.trace_id = (tn.properties->>'trace_id')::int \
WHERE tn.file_uuid = $1 AND tn.node_type = 'face_track' \
AND (tn.external_id = $2 OR tn.external_id = $3)",
tkg_table, tp_table
))
.bind(&params.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TraceProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
tkg_table, tp_table
))
.bind(&params.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[TraceProfile] DB error: {}", e);
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (name, _ext_id, tp_props, tn_props) = row.ok_or(StatusCode::NOT_FOUND)?;
// Merge properties: tp_props takes precedence, tn_props as fallback
let mut properties = tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
let mut properties =
tn_props.unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));
if let Some(tp_obj) = tp_props.as_ref().and_then(|v| v.as_object()) {
if let Some(props_obj) = properties.as_object_mut() {
for (k, v) in tp_obj {
@@ -1243,17 +1248,10 @@ pub async fn get_face_groups_handler(
}
}
// Filter out single-trace "groups" — only auto-generated Person_N names.
// User-named groups (even with 1 trace) are kept.
// All Person_N groups are shown as face groups regardless of trace count.
let mut filtered_groups: HashMap<String, Vec<i32>> = HashMap::new();
for (name, trace_ids) in groups {
let is_auto_name = name.starts_with("Person_");
if trace_ids.len() > 1 || !is_auto_name {
filtered_groups.insert(name, trace_ids);
} else {
// Single-trace auto-generated group → treat as unassigned
unassigned.extend(trace_ids);
}
filtered_groups.insert(name, trace_ids);
}
let include_trace_ids = q.include_trace_ids.unwrap_or(true);