docs: trace_profile UPSERT fixes + Studio face group API gap analysis

- profile.rs: single/group/merge_groups/undo all use upsert_trace_profile
- trace_agent_api.rs: hard delete/merge snapshot + delete trace_profiles
- cluster_agent.rs, job_worker.rs: background name writes use UPSERT
- schema.rs: upsert_trace_profile helper (backfill from tkg_nodes)
- Studio 3 API gaps documented (cluster-results/identity-matches/similar)
This commit is contained in:
Accusys
2026-07-31 11:16:18 +08:00
parent 7272077b65
commit aab727b297
6 changed files with 464 additions and 101 deletions
+21 -26
View File
@@ -106,7 +106,6 @@ pub async fn trigger_cluster_agent(
PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_cluster.json", file_uuid));
// Reset all trace_profiles names to default (Person_N) before re-clustering
let tp_table = schema::table_name("trace_profiles");
let traced_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.face_traced.json", file_uuid));
if let Ok(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
@@ -122,14 +121,13 @@ pub async fn trigger_cluster_agent(
if let Some(all_trace_ids) = trace_list {
for tid in &all_trace_ids {
let name = format!("Person_{}", tid);
let _ = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&name)
.bind(&file_uuid)
.bind(tid)
.execute(state.db.pool())
let _ = schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
*tid as i32,
&name,
None,
)
.await;
}
tracing::info!(
@@ -235,7 +233,6 @@ async fn update_trace_labels_from_cluster(
}
let tkg_table = schema::table_name("tkg_nodes");
let tp_table = schema::table_name("trace_profiles");
for (trace_id, cluster_id) in &trace_to_cluster {
let external_id = format!("trace_{}", trace_id);
@@ -265,14 +262,13 @@ async fn update_trace_labels_from_cluster(
.await?;
}
let _ = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&label)
.bind(file_uuid)
.bind(trace_id)
.execute(state.db.pool())
let _ = schema::upsert_trace_profile(
state.db.pool(),
file_uuid,
*trace_id as i32,
&label,
None,
)
.await;
}
@@ -282,14 +278,13 @@ 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 _ = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&name)
.bind(file_uuid)
.bind(tid)
.execute(state.db.pool())
let _ = schema::upsert_trace_profile(
state.db.pool(),
file_uuid,
*tid as i32,
&name,
None,
)
.await;
updated_count += 1;
}
+108 -58
View File
@@ -179,7 +179,6 @@ pub async fn update_trace_profile_handler(
Json(req): Json<UpdateTraceProfileRequest>,
) -> Result<Json<serde_json::Value>, StatusCode> {
let tp_table = schema::table_name("trace_profiles");
let nodes_table = schema::table_name("tkg_nodes");
// Get current profile
let current: Option<(Option<String>, serde_json::Value)> = sqlx::query_as(&format!(
@@ -195,7 +194,10 @@ pub async fn update_trace_profile_handler(
StatusCode::INTERNAL_SERVER_ERROR
})?;
let (current_name, mut current_props) = current.ok_or(StatusCode::NOT_FOUND)?;
let (current_name, mut current_props) = match current {
Some((name, props)) => (name, props),
None => (None, serde_json::json!({})),
};
// Build updates for trace_profiles
let mut tp_updates: Vec<String> = Vec::new();
@@ -243,30 +245,18 @@ pub async fn update_trace_profile_handler(
let new_name_val = req.name.as_deref();
let before_name = current_name.clone().unwrap_or_default();
let final_name = new_name_val.unwrap_or(before_name.as_str());
let props_json = serde_json::to_string(&current_props).unwrap();
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");
let mut sql_query = sqlx::query(&query)
.bind(&req.file_uuid)
.bind(&props_json)
.bind(req.trace_id as i32);
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 => {
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
req.trace_id,
final_name,
Some(&current_props),
)
.await
{
Ok(affected) if affected > 0 => {
let after_name = new_name_val.unwrap_or(&before_name);
let _ = save_trace_operation_snapshot(
state.db.pool(),
@@ -324,18 +314,20 @@ pub async fn update_trace_profile_group_handler(
let mut updated = 0;
for trace_id in &req.trace_ids {
let result = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(&req.name)
.bind(&req.file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
if let Ok(res) = result {
updated += res.rows_affected();
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
*trace_id,
&req.name,
None,
)
.await
{
Ok(affected) => updated += affected,
Err(e) => {
tracing::error!("[TraceProfileGroup] UPSERT error: {}", e);
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
}
@@ -417,20 +409,50 @@ pub async fn merge_groups_handler(
.execute(state.db.pool())
.await;
// Then update trace_profiles.name
let tp_result = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND name = ANY($3)",
tp_table
// Then collect matching trace_ids from tkg_nodes (FS source of truth)
let matching_trace_ids: Vec<i32> = sqlx::query_scalar(&format!(
"SELECT (properties->>'trace_id')::int FROM {} \
WHERE file_uuid = $1 AND node_type = 'face_track' AND label = ANY($2) \
ORDER BY (properties->>'trace_id')::int",
nodes_table
))
.bind(&req.target_group_name)
.bind(&req.file_uuid)
.bind(&req.source_groups)
.execute(state.db.pool())
.await;
.fetch_all(state.db.pool())
.await
.map_err(|e| {
tracing::error!("[MergeGroups] Failed to collect trace_ids: {}", e);
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": e.to_string()})),
)
})?;
match (nodes_result, tp_result) {
(Ok(nodes_res), Ok(tp_res)) => {
let updated = tp_res.rows_affected();
// UPSERT each matching trace profile to the target name
let mut updated: u64 = 0;
for trace_id in &matching_trace_ids {
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
*trace_id,
&req.target_group_name,
None,
)
.await
{
Ok(affected) => updated += affected,
Err(e) => {
tracing::error!("[MergeGroups] UPSERT error: {}", e);
return Err((
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": e.to_string()})),
));
}
}
}
match nodes_result {
Ok(nodes_res) => {
let nodes_updated = nodes_res.rows_affected();
let group_count = req.source_groups.len();
let target_name = req.target_group_name.clone();
@@ -460,7 +482,7 @@ pub async fn merge_groups_handler(
message: format!("Merged {} group(s) into '{}'", group_count, target_name),
}))
}
(Err(e), _) | (_, Err(e)) => {
Err(e) => {
tracing::error!("[MergeGroups] DB error: {}", e);
Err((
StatusCode::INTERNAL_SERVER_ERROR,
@@ -487,7 +509,6 @@ pub async fn undo_face_operation_handler(
Path(file_uuid): Path<String>,
) -> Result<Json<UndoFaceOperationResponse>, (StatusCode, Json<serde_json::Value>)> {
let table = schema::table_name("trace_operation_history");
let tp_table = schema::table_name("trace_profiles");
let tkg_table = schema::table_name("tkg_nodes");
// Find latest undoable operation for this file
@@ -535,15 +556,14 @@ pub async fn undo_face_operation_handler(
let name = name_val.as_str().unwrap_or("Person_0");
let trace_id: i32 = trace_id_str.parse().unwrap_or(0);
// Restore trace_profiles.name
let _ = sqlx::query(&format!(
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
tp_table
))
.bind(name)
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
// Restore trace_profiles.name (UPSERT to handle missing rows)
let _ = schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
trace_id,
name,
None,
)
.await;
// For merge_groups, also restore tkg_nodes.label
@@ -651,6 +671,21 @@ async fn undo_merge_trace(
}
}
// 3b. Restore source trace profile (UPSERT to handle missing row)
let source_name = before_snapshot["trace_profiles"]
.as_array()
.and_then(|arr| arr.iter().find(|p| p["trace_id"].as_i64() == Some(source_trace_id)))
.and_then(|p| p["name"].as_str().map(String::from))
.unwrap_or_else(|| "Person_0".to_string());
let _ = schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
source_trace_id as i32,
&source_name,
None,
)
.await;
// Mark as undone
let _ = sqlx::query(&format!(
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
@@ -749,6 +784,21 @@ async fn undo_hard_delete_trace(
}
}
// 4b. Restore trace profile (UPSERT to handle missing row)
let profile_name = before_snapshot["trace_profiles"]
.as_array()
.and_then(|arr| arr.iter().find(|p| p["trace_id"].as_i64() == Some(trace_id)))
.and_then(|p| p["name"].as_str().map(String::from))
.unwrap_or_else(|| "Person_0".to_string());
let _ = schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
trace_id as i32,
&profile_name,
None,
)
.await;
// 5. Mark as undone
let _ = sqlx::query(&format!(
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
+58
View File
@@ -1770,6 +1770,18 @@ async fn delete_trace(
.await
.unwrap_or_default();
// 2b. Save trace profile before deleting
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let profile_snapshot: Vec<(i32, Option<String>, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT trace_id, name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2",
tp_table
))
.bind(&file_uuid)
.bind(trace_id)
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
// 3. Delete from _faces
let _ = qdrant.delete_points_by_filter("_faces", filter.clone()).await;
@@ -1784,6 +1796,16 @@ async fn delete_trace(
.execute(state.db.pool())
.await;
// 4b. Delete trace profile
let _ = sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1 AND trace_id = $2",
tp_table
))
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
// 5. Save operation snapshot
let op_table = crate::core::db::schema::table_name("trace_operation_history");
let before_snapshot = serde_json::json!({
@@ -1795,6 +1817,13 @@ async fn delete_trace(
"properties": props,
})
}).collect::<Vec<_>>(),
"trace_profiles": profile_snapshot.iter().map(|(tid, name, props)| {
serde_json::json!({
"trace_id": tid,
"name": name,
"properties": props,
})
}).collect::<Vec<_>>(),
});
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, operation, before_snapshot) VALUES ($1, 'hard_delete', $2)",
@@ -1924,6 +1953,18 @@ async fn merge_trace(
.await
.unwrap_or_default();
// Snapshot source trace profile before merge
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let profile_snapshot: Vec<(i32, Option<String>, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT trace_id, name, properties FROM {} WHERE file_uuid = $1 AND trace_id = $2",
tp_table
))
.bind(&file_uuid)
.bind(trace_id)
.fetch_all(state.db.pool())
.await
.unwrap_or_default();
let before_snapshot = serde_json::json!({
"source_trace_id": trace_id,
"target_trace_id": target_trace_id,
@@ -1935,6 +1976,13 @@ async fn merge_trace(
"properties": props,
})
}).collect::<Vec<_>>(),
"trace_profiles": profile_snapshot.iter().map(|(tid, name, props)| {
serde_json::json!({
"trace_id": tid,
"name": name,
"properties": props,
})
}).collect::<Vec<_>>(),
});
// Step 1: Update all face points from source trace to target trace
@@ -1990,6 +2038,16 @@ async fn merge_trace(
}
};
// Step 2b: Delete source trace profile
let _ = sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1 AND trace_id = $2",
tp_table
))
.bind(&file_uuid)
.bind(trace_id)
.execute(state.db.pool())
.await;
// Step 3: Save operation snapshot for undo
let op_table = crate::core::db::schema::table_name("trace_operation_history");
let _ = sqlx::query(&format!(