fix: face group name read consistency, sync_file_status fix, cleanup ghost records, identity_agent replaced with face_dedup

- get_face_groups_handler: COALESCE(tp.name, tn.label) for name consistency
- sync_file_status: compare JSON vs pre_chunks (not chunk table)
- face consistency: compare frames.len() not total_faces
- cleanup 2 ghost records with NULL file_name/file_path
- replace identity_agent with face_dedup in pipeline stages
- remove identity_agent_api.rs and all references
- update required_processors to match actual processors
- update AGENTS.md with team responsibilities
- add Studio pipeline changes documentation
This commit is contained in:
Accusys
2026-07-27 02:15:51 +08:00
parent fcdeab82e6
commit 39a2cbc65b
118 changed files with 19386 additions and 2964 deletions
+228 -74
View File
@@ -1,15 +1,15 @@
use axum::{
Extension, Json,
extract::{Path, Query, State},
http::StatusCode,
Extension, Json,
};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use std::collections::HashMap;
use crate::core::db::schema;
use crate::api::middleware::UserAuth;
use crate::api::types::AppState;
use crate::core::db::schema;
// ─── Trace Profile ───
@@ -49,6 +49,23 @@ pub struct UpdateTraceProfileGroupRequest {
pub name: String,
}
#[derive(Debug, Deserialize)]
pub struct MergeGroupsRequest {
pub file_uuid: String,
pub source_groups: Vec<String>,
pub target_group_name: String,
}
#[derive(Debug, Serialize)]
pub struct MergeGroupsResponse {
pub success: bool,
pub file_uuid: String,
pub source_groups: Vec<String>,
pub target_group_name: String,
pub traces_merged: u64,
pub message: String,
}
pub async fn get_trace_profile_handler(
State(state): State<AppState>,
Extension(_auth): Extension<UserAuth>,
@@ -100,19 +117,16 @@ pub async fn update_trace_profile_handler(
Extension(_auth): Extension<UserAuth>,
Json(req): Json<UpdateTraceProfileRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let tkg_table = schema::table_name("tkg_nodes");
let external_id_face = format!("face_track_{}", req.trace_id);
let external_id_trace = format!("trace_{}", req.trace_id);
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
// Get current node (match both external_id formats)
let current: Option<(String, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT label, properties FROM {} \
WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
tkg_table
// Get current profile
let current: Option<(Option<String>, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2",
tp_table
))
.bind(&req.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.bind(req.trace_id)
.fetch_optional(state.db.pool())
.await
.map_err(|e| {
@@ -120,14 +134,16 @@ pub async fn update_trace_profile_handler(
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (current_label, mut current_props) = current.ok_or(StatusCode::NOT_FOUND)?;
let (current_name, mut current_props) = current.ok_or(StatusCode::NOT_FOUND)?;
// Build updates
let mut updates: Vec<String> = Vec::new();
// Build updates for trace_profiles
let mut tp_updates: Vec<String> = Vec::new();
let mut param_idx = 3;
if let Some(ref new_name) = req.name {
if new_name != &current_label {
updates.push(format!("label = $5"));
if Some(new_name) != current_name.as_ref() {
param_idx += 1;
tp_updates.push(format!("name = ${}", param_idx));
}
}
@@ -152,8 +168,11 @@ pub async fn update_trace_profile_handler(
current_props["aliases"] = aliases.clone();
}
if updates.is_empty() && req.properties.is_none() && req.key_frame.is_none()
&& req.key_face.is_none() && req.aliases.is_none()
if tp_updates.is_empty()
&& req.properties.is_none()
&& req.key_frame.is_none()
&& req.key_face.is_none()
&& req.aliases.is_none()
{
return Ok(Json(serde_json::json!({
"success": true,
@@ -161,40 +180,28 @@ pub async fn update_trace_profile_handler(
})));
}
let mut query = format!(
"UPDATE {} SET properties = properties || $4::jsonb",
tkg_table
);
if !updates.is_empty() {
query.push_str(", ");
query.push_str(&updates.join(", "));
}
query.push_str(" WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)");
query.push_str(" RETURNING id");
let props_json = serde_json::to_string(&current_props).unwrap();
let result = if !updates.is_empty() {
sqlx::query(&query)
.bind(&req.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.bind(&props_json)
.bind(req.name.as_ref().unwrap_or(&current_label))
.execute(state.db.pool())
.await
} else {
sqlx::query(&query)
.bind(&req.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.bind(&props_json)
.execute(state.db.pool())
.await
};
let mut query = format!(
"UPDATE {} SET properties = $2::jsonb",
tp_table
);
if !tp_updates.is_empty() {
query.push_str(", ");
query.push_str(&tp_updates.join(", "));
}
query.push_str(" WHERE file_uuid = $1 AND trace_id = $3");
match result {
let mut sql_query = sqlx::query(&query)
.bind(&req.file_uuid)
.bind(&props_json)
.bind(req.trace_id);
if let Some(ref new_name) = req.name {
sql_query = sql_query.bind(new_name);
}
match sql_query.execute(state.db.pool()).await {
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
"success": true,
"message": "Trace profile updated",
@@ -214,21 +221,17 @@ pub async fn update_trace_profile_group_handler(
Extension(_auth): Extension<UserAuth>,
Json(req): Json<UpdateTraceProfileGroupRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
let mut updated = 0;
for trace_id in &req.trace_ids {
let external_id_face = format!("face_track_{}", trace_id);
let external_id_trace = format!("trace_{}", trace_id);
let result = sqlx::query(&format!(
"UPDATE {} SET label = $1 \
WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR external_id = $4)",
tkg_table
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&req.name)
.bind(&req.file_uuid)
.bind(&external_id_face)
.bind(&external_id_trace)
.bind(trace_id)
.execute(state.db.pool())
.await;
@@ -245,6 +248,78 @@ pub async fn update_trace_profile_group_handler(
})))
}
pub async fn merge_groups_handler(
State(state): State<AppState>,
Extension(_auth): Extension<UserAuth>,
Json(req): Json<MergeGroupsRequest>,
) -> Result<Json<MergeGroupsResponse>, (StatusCode, Json<serde_json::Value>)> {
let tkg_table = schema::table_name("tkg_nodes");
if req.source_groups.contains(&req.target_group_name) {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"success": false,
"error": "Target group cannot be in source_groups list"
})),
));
}
if req.source_groups.is_empty() {
return Err((
StatusCode::BAD_REQUEST,
Json(serde_json::json!({
"success": false,
"error": "source_groups cannot be empty"
})),
));
}
// Update trace_profiles.name for all matching traces
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
let result = sqlx::query(&format!(
"UPDATE {} tp SET name = $1 \
WHERE tp.file_uuid = $2 AND tp.trace_id IN (\
SELECT REPLACE(n.external_id, 'trace_', '')::int \
FROM {} n WHERE n.file_uuid = $2 AND n.node_type = 'face_track' AND n.label = ANY($3)\
)",
tp_table, nodes_table
))
.bind(&req.target_group_name)
.bind(&req.file_uuid)
.bind(&req.source_groups)
.execute(state.db.pool())
.await;
match result {
Ok(res) => {
let updated = res.rows_affected();
let group_count = req.source_groups.len();
let target_name = req.target_group_name.clone();
Ok(Json(MergeGroupsResponse {
success: true,
file_uuid: req.file_uuid,
source_groups: req.source_groups,
target_group_name: req.target_group_name,
traces_merged: updated,
message: format!("Merged {} group(s) into '{}'", group_count, target_name),
}))
}
Err(e) => {
tracing::error!("[MergeGroups] DB error: {}", e);
Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({
"success": false,
"error": e.to_string()
})),
))
}
}
}
// ─── File Profile ───
#[derive(Deserialize)]
@@ -263,6 +338,16 @@ pub struct FileProfile {
pub height: i32,
pub fps: f64,
pub total_frames: i64,
#[serde(skip_serializing_if = "Option::is_none")]
pub birth: Option<serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub history: Option<Vec<serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub key_frame: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub proxy_path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub audio_track: Option<String>,
}
#[derive(Deserialize)]
@@ -296,16 +381,51 @@ pub async fn get_file_profile_handler(
let (file_uuid, file_name, file_path, status, duration, width, height, fps, total_frames) =
row.ok_or(StatusCode::NOT_FOUND)?;
// Enrich with on-disk profile data (birth, history, key_frame)
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let disk_profile =
crate::core::file_profile::FileProfile::load_from_disk(output_dir, &file_uuid);
// Fallback for zombie files: if DB fields are empty, try to recover from profile
let effective_name = if file_name.is_empty() {
disk_profile
.as_ref()
.map(|p| p.file_name.clone())
.unwrap_or_default()
} else {
file_name
};
let effective_path = if file_path.is_empty() {
disk_profile
.as_ref()
.map(|p| p.current.path.clone())
.unwrap_or_default()
} else {
file_path
};
Ok(Json(FileProfile {
file_uuid,
file_name,
file_path,
file_name: effective_name,
file_path: effective_path,
status,
duration,
width,
height,
fps,
total_frames,
birth: disk_profile
.as_ref()
.and_then(|p| serde_json::to_value(&p.birth).ok()),
history: disk_profile.as_ref().map(|p| {
p.history
.iter()
.map(|h| serde_json::to_value(h).unwrap_or_default())
.collect()
}),
key_frame: disk_profile.as_ref().and_then(|p| p.key_frame.clone()),
proxy_path: disk_profile.as_ref().and_then(|p| p.proxy_path.clone()),
audio_track: disk_profile.as_ref().and_then(|p| p.audio_track.clone()),
}))
}
@@ -372,11 +492,34 @@ pub async fn update_file_profile_handler(
};
match result {
Ok(res) if res.rows_affected() > 0 => Ok(Json(serde_json::json!({
"success": true,
"message": "File profile updated",
"file_uuid": req.file_uuid
}))),
Ok(res) if res.rows_affected() > 0 => {
// Update on-disk profile if path or name changed
if req.file_path.is_some() || req.file_name.is_some() {
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
if let Some(mut profile) = crate::core::file_profile::FileProfile::load_from_disk(
output_dir,
&req.file_uuid,
) {
let new_path = req
.file_path
.clone()
.unwrap_or_else(|| profile.current.path.clone());
let new_name = req
.file_name
.clone()
.unwrap_or_else(|| profile.current.file_name.clone());
profile.update_current_path(&new_path, &new_name);
if let Err(e) = profile.save_to_disk(output_dir) {
tracing::warn!("[FileProfile] Failed to update on-disk profile: {}", e);
}
}
}
Ok(Json(serde_json::json!({
"success": true,
"message": "File profile updated",
"file_uuid": req.file_uuid
})))
}
Ok(_) => Err(StatusCode::NOT_FOUND),
Err(e) => {
tracing::error!("[FileProfile] Update failed: {}", e);
@@ -412,12 +555,16 @@ pub async fn get_face_groups_handler(
Path(file_uuid): Path<String>,
) -> Result<Json<FaceGroupsResponse>, StatusCode> {
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
let rows: Vec<(String, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT label, properties FROM {} \
WHERE file_uuid = $1 AND node_type = 'face_track' \
ORDER BY (properties->>'trace_id')::int",
tkg_table
"SELECT COALESCE(tp.name, tn.label) as name, 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' \
ORDER BY (tn.properties->>'trace_id')::int",
tkg_table, tp_table
))
.bind(&file_uuid)
.fetch_all(state.db.pool())
@@ -430,16 +577,16 @@ pub async fn get_face_groups_handler(
let mut groups: HashMap<String, Vec<i64>> = HashMap::new();
let mut unassigned: Vec<i64> = Vec::new();
for (label, properties) in rows {
for (name, properties) in rows {
let trace_id = properties
.get("trace_id")
.and_then(|v| v.as_i64())
.unwrap_or(0);
if label.starts_with("Face Trace ") || label.starts_with("Trace ") {
if name.starts_with("Face Trace ") || name.starts_with("Trace ") {
unassigned.push(trace_id);
} else {
groups.entry(label).or_default().push(trace_id);
groups.entry(name).or_default().push(trace_id);
}
}
@@ -468,7 +615,7 @@ pub async fn get_face_groups_handler(
// ─── Routes ───
pub fn profile_routes() -> axum::Router<AppState> {
use axum::routing::{get, put};
use axum::routing::{get, post, put};
axum::Router::new()
.route("/api/v1/trace-profile", get(get_trace_profile_handler))
.route("/api/v1/trace-profile", put(update_trace_profile_handler))
@@ -478,5 +625,12 @@ pub fn profile_routes() -> axum::Router<AppState> {
)
.route("/api/v1/file-profile", get(get_file_profile_handler))
.route("/api/v1/file-profile", put(update_file_profile_handler))
.route("/api/v1/file/:file_uuid/face-groups", get(get_face_groups_handler))
.route(
"/api/v1/file/:file_uuid/face-groups",
get(get_face_groups_handler),
)
.route(
"/api/v1/file/:file_uuid/groups/merge",
post(merge_groups_handler),
)
}