fix: group delete semantics - unassign instead of destroy, self-heal tkg_nodes

Studio's "delete group" was calling hard_delete which physically removed
_faces points, tkg_nodes and trace_profiles (and silently failed to back
up to a non-existent _faces_trash collection, making undo impossible).
This permanently lost face groups and broke face-groups/cluster-results
(which are based on tkg_nodes) for any trace without a node row.

Changes:
- delete_trace hard-delete now means "restore to unassigned": keep
  _faces/tkg_nodes/trace_profiles, only reset name to "Face Trace {id}".
  Data is never destroyed so groups can be rebuilt and undo works.
- schema::ensure_face_track_node: create the face_track tkg_nodes row on
  write so a trace that lost its node (old hard-delete) reappears in
  face-groups/cluster-results (self-healing). Called from
  update_trace_profile_handler, update_trace_profile_group_handler and
  merge_groups_handler; the group handler also syncs tkg_nodes.label.
- restore_trace / undo_hard_delete_trace: when _faces_trash is empty
  (new semantics), rebuild the named group from the operation snapshot
  (tkg_nodes ON CONFLICT UPDATE + trace_profiles UPSERT) instead of 404.

Verified live on port 3002 (file bfba056f...): delete -> unassigned with
_faces preserved (4 points), rebuild group -> self-healing creates node
and group shows up, restore -> name restored to original. Also fixed the
pre-existing missing tkg_nodes row for trace 4621 via the same path.
This commit is contained in:
Accusys
2026-07-31 13:14:23 +08:00
parent d36132d93a
commit 40fc8c6a53
3 changed files with 439 additions and 187 deletions
+239 -113
View File
@@ -119,25 +119,26 @@ 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, serde_json::Value, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT COALESCE(tp.name, tn.label) as name, tn.external_id, \
let row: Option<(String, String, serde_json::Value, 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)?;
@@ -153,7 +154,10 @@ pub async fn get_trace_profile_handler(
}
}
let key_frame = properties.get("key_frame").and_then(|v| v.as_str()).map(|s| s.to_string());
let key_frame = properties
.get("key_frame")
.and_then(|v| v.as_str())
.map(|s| s.to_string());
let key_face = properties
.get("key_face")
.and_then(|v| v.as_str())
@@ -247,6 +251,13 @@ pub async fn update_trace_profile_handler(
let before_name = current_name.clone().unwrap_or_default();
let final_name = new_name_val.unwrap_or(before_name.as_str());
// Self-healing: ensure a tkg_nodes face_track row exists so the trace
// can appear in face-groups / cluster-results even if it was previously
// lost (e.g. by an old hard-delete).
let _ =
schema::ensure_face_track_node(state.db.pool(), &req.file_uuid, req.trace_id, final_name)
.await;
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
@@ -269,7 +280,8 @@ pub async fn update_trace_profile_handler(
"traces": { req.trace_id.to_string(): after_name }
})),
None,
).await;
)
.await;
Ok(Json(serde_json::json!({
"success": true,
"message": "Trace profile updated",
@@ -313,7 +325,13 @@ pub async fn update_trace_profile_group_handler(
}
let mut updated = 0;
let nodes_table = schema::table_name("tkg_nodes");
for trace_id in &req.trace_ids {
// Self-healing: make sure the face_track node exists.
let _ =
schema::ensure_face_track_node(state.db.pool(), &req.file_uuid, *trace_id, &req.name)
.await;
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
@@ -329,6 +347,21 @@ pub async fn update_trace_profile_group_handler(
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
}
// Keep tkg_nodes.label in sync with the profile name.
if let Err(e) = sqlx::query(&format!(
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR (properties->>'trace_id')::int = $4)",
nodes_table
))
.bind(&req.name)
.bind(&req.file_uuid)
.bind(format!("trace_{}", trace_id))
.bind(*trace_id)
.execute(state.db.pool())
.await
{
tracing::error!("[TraceProfileGroup] tkg label sync error: {}", e);
}
}
let _ = save_trace_operation_snapshot(
@@ -431,6 +464,14 @@ pub async fn merge_groups_handler(
// UPSERT each matching trace profile to the target name
let mut updated: u64 = 0;
for trace_id in &matching_trace_ids {
// Self-healing: ensure the face_track node exists for this trace.
let _ = schema::ensure_face_track_node(
state.db.pool(),
&req.file_uuid,
*trace_id,
&req.target_group_name,
)
.await;
match schema::upsert_trace_profile(
state.db.pool(),
&req.file_uuid,
@@ -545,26 +586,23 @@ pub async fn undo_face_operation_handler(
}
// Handle operations with traces name mapping
let traces = before_snapshot.get("traces").and_then(|v| v.as_object()).ok_or_else(|| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": "Invalid snapshot: missing traces"})),
)
})?;
let traces = before_snapshot
.get("traces")
.and_then(|v| v.as_object())
.ok_or_else(|| {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(serde_json::json!({"error": "Invalid snapshot: missing traces"})),
)
})?;
for (trace_id_str, name_val) in traces {
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 (UPSERT to handle missing rows)
let _ = schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
trace_id,
name,
None,
)
.await;
let _ =
schema::upsert_trace_profile(state.db.pool(), &file_uuid, trace_id, name, None).await;
// For merge_groups, also restore tkg_nodes.label
if operation == "merge_groups" {
@@ -624,7 +662,10 @@ async fn undo_merge_trace(
{"key": "merged_from", "match": {"value": source_trace_id}}
]
});
let _ = state.qdrant.delete_points_by_filter("_faces", delete_filter).await;
let _ = state
.qdrant
.delete_points_by_filter("_faces", delete_filter)
.await;
// 2. Re-insert original points
if let Some(qdrant_points) = before_snapshot["qdrant_points"].as_array() {
@@ -633,7 +674,10 @@ async fn undo_merge_trace(
.filter_map(|p| {
let id = p["id"].as_u64()?;
let vec_arr = p["vector"].as_array()?;
let vector: Vec<f32> = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
let vector: Vec<f32> = vec_arr
.iter()
.filter_map(|v| v.as_f64().map(|f| f as f32))
.collect();
let payload = p["payload"].clone();
Some((id, vector, Some(payload)))
})
@@ -645,7 +689,11 @@ async fn undo_merge_trace(
.collect();
if !ref_batch.is_empty() {
if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await {
if let Err(e) = state
.qdrant
.upsert_vectors_batch("_faces", &ref_batch)
.await
{
tracing::error!("[UndoMergeTrace] Failed to restore Qdrant points: {}", e);
}
}
@@ -656,7 +704,10 @@ async fn undo_merge_trace(
for node in tkg_nodes {
let ext_id = node["external_id"].as_str().unwrap_or("");
let label = node["label"].as_str().unwrap_or("Person_0");
let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": source_trace_id}));
let props = node
.get("properties")
.cloned()
.unwrap_or(serde_json::json!({"trace_id": source_trace_id}));
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING",
@@ -674,7 +725,10 @@ 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(|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(
@@ -721,7 +775,8 @@ async fn undo_hard_delete_trace(
{"key": "trace_id", "match": {"value": trace_id}}
]
});
let trash_points = state.qdrant
let trash_points = state
.qdrant
.scroll_all_points_with_vectors("_faces_trash", trash_filter.clone(), 1000)
.await
.map_err(|e| {
@@ -732,72 +787,134 @@ async fn undo_hard_delete_trace(
})?;
if trash_points.is_empty() {
return Err((
StatusCode::NOT_FOUND,
Json(serde_json::json!({"error": "No trashed points found for this trace"})),
));
}
// No trash collection means the original hard-delete (new semantics)
// only reset the name to "unassigned" and kept the data. Rebuild the
// named group directly from the operation snapshot instead of looking
// for trashed Qdrant points.
tracing::warn!(
"[UndoHardDelete] No _faces_trash points for trace {}; rebuilding from snapshot",
trace_id
);
// 2. Copy back to _faces
let restore_batch: Vec<(u64, Vec<f32>, serde_json::Value)> = trash_points
.iter()
.filter_map(|p| {
let id = p["id"].as_u64()?;
let vec_arr = p["vector"].as_array()?;
let vector: Vec<f32> = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect();
let mut payload = p["payload"].clone();
if let Some(obj) = payload.as_object_mut() {
obj.remove("trashed_at");
// Re-insert TKG nodes from snapshot (ON CONFLICT updates label/props).
if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() {
for node in tkg_nodes {
let ext_id = node["external_id"].as_str().unwrap_or("");
let label = node["label"].as_str().unwrap_or("Person_0");
let props = node
.get("properties")
.cloned()
.unwrap_or(serde_json::json!({"trace_id": trace_id}));
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) \
ON CONFLICT (file_uuid, node_type, external_id) DO UPDATE SET label = EXCLUDED.label, properties = EXCLUDED.properties",
tkg_table
))
.bind(&file_uuid)
.bind(ext_id)
.bind(label)
.bind(&props)
.execute(state.db.pool())
.await;
}
Some((id, vector, payload))
})
.collect();
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = restore_batch
.iter()
.map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone())))
.collect();
if let Err(e) = state.qdrant.upsert_vectors_batch("_faces", &ref_batch).await {
tracing::error!("[UndoHardDelete] Failed to restore points: {}", e);
}
// 3. Delete from _faces_trash
let _ = state.qdrant.delete_points_by_filter("_faces_trash", trash_filter).await;
// 4. Re-insert TKG nodes
if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() {
for node in tkg_nodes {
let ext_id = node["external_id"].as_str().unwrap_or("");
let label = node["label"].as_str().unwrap_or("Person_0");
let props = node.get("properties").cloned().unwrap_or(serde_json::json!({"trace_id": trace_id}));
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING",
tkg_table
))
.bind(&file_uuid)
.bind(ext_id)
.bind(label)
.bind(&props)
.execute(state.db.pool())
.await;
}
}
// 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;
// Restore trace profile name from snapshot.
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;
} else {
// Legacy path: restore actual Qdrant points from _faces_trash.
// 2. Copy back to _faces
let restore_batch: Vec<(u64, Vec<f32>, serde_json::Value)> = trash_points
.iter()
.filter_map(|p| {
let id = p["id"].as_u64()?;
let vec_arr = p["vector"].as_array()?;
let vector: Vec<f32> = vec_arr
.iter()
.filter_map(|v| v.as_f64().map(|f| f as f32))
.collect();
let mut payload = p["payload"].clone();
if let Some(obj) = payload.as_object_mut() {
obj.remove("trashed_at");
}
Some((id, vector, payload))
})
.collect();
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = restore_batch
.iter()
.map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone())))
.collect();
if let Err(e) = state
.qdrant
.upsert_vectors_batch("_faces", &ref_batch)
.await
{
tracing::error!("[UndoHardDelete] Failed to restore points: {}", e);
}
// 3. Delete from _faces_trash
let _ = state
.qdrant
.delete_points_by_filter("_faces_trash", trash_filter)
.await;
// 4. Re-insert TKG nodes
if let Some(tkg_nodes) = before_snapshot["tkg_nodes"].as_array() {
for node in tkg_nodes {
let ext_id = node["external_id"].as_str().unwrap_or("");
let label = node["label"].as_str().unwrap_or("Person_0");
let props = node
.get("properties")
.cloned()
.unwrap_or(serde_json::json!({"trace_id": trace_id}));
let _ = sqlx::query(&format!(
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4) ON CONFLICT DO NOTHING",
tkg_table
))
.bind(&file_uuid)
.bind(ext_id)
.bind(label)
.bind(&props)
.execute(state.db.pool())
.await;
}
}
// 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!(
@@ -1260,11 +1377,14 @@ pub async fn get_cluster_results_handler(
continue;
}
frames_map.entry(frame).or_default().push(ClusterResultsFace {
face_id: format!("{:x}", point_id),
confidence,
cluster_id,
});
frames_map
.entry(frame)
.or_default()
.push(ClusterResultsFace {
face_id: format!("{:x}", point_id),
confidence,
cluster_id,
});
}
let mut frames: Vec<ClusterResultsFrame> = frames_map
@@ -1420,7 +1540,10 @@ pub async fn get_similar_group_handler(
continue;
}
trace_group.insert(*trace_id, name.clone());
group_traces.entry(name.clone()).or_default().push(*trace_id);
group_traces
.entry(name.clone())
.or_default()
.push(*trace_id);
}
let source_group_names: Vec<String> = db_rows
@@ -1462,13 +1585,19 @@ pub async fn get_similar_group_handler(
// 7. Sort by score descending, take top_k
let mut suggestions: Vec<SimilarGroupSuggestion> = group_scores
.into_iter()
.map(|(group_name, (score, matched_trace_id))| SimilarGroupSuggestion {
group_name,
score,
matched_trace_id: matched_trace_id as i32,
})
.map(
|(group_name, (score, matched_trace_id))| SimilarGroupSuggestion {
group_name,
score,
matched_trace_id: matched_trace_id as i32,
},
)
.collect();
suggestions.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
suggestions.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
});
suggestions.truncate(top_k);
Ok(Json(SimilarGroupResponse {
@@ -1499,10 +1628,7 @@ pub fn profile_routes() -> axum::Router<AppState> {
"/api/v1/file/:file_uuid/face-groups/similar",
get(get_similar_group_handler),
)
.route(
"/api/v1/cluster-results",
get(get_cluster_results_handler),
)
.route("/api/v1/cluster-results", get(get_cluster_results_handler))
.route(
"/api/v1/file/:file_uuid/groups/merge",
post(merge_groups_handler),