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
+156 -70
View File
@@ -1714,51 +1714,18 @@ async fn delete_trace(
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
if hard_delete {
// Hard delete: move to _faces_trash, then remove from _faces and TKG
let filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": &file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}}
]
});
// 0. Scroll points with vectors for trash backup
let trashed_points = qdrant
.scroll_all_points_with_vectors("_faces", filter.clone(), 1000)
.await
.unwrap_or_default();
// 1. Copy to _faces_trash
if !trashed_points.is_empty() {
let trash_batch: Vec<(u64, Vec<f32>, serde_json::Value)> = trashed_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.insert("trashed_at".to_string(), serde_json::json!(chrono::Utc::now().to_rfc3339()));
}
Some((id, vector, payload))
})
.collect();
let ref_batch: Vec<(u64, &[f32], Option<serde_json::Value>)> = trash_batch
.iter()
.map(|(id, vec, pl)| (*id, vec.as_slice(), Some(pl.clone())))
.collect();
if let Err(e) = qdrant.upsert_vectors_batch("_faces_trash", &ref_batch).await {
tracing::error!("[delete_trace] Failed to copy to trash: {}", e);
}
}
// 2. Save TKG nodes before deleting
// "Hard delete" now means: restore trace to unassigned.
// Keep _faces points, tkg_nodes rows and trace_profiles rows;
// only reset the name/label back to the default so the trace
// shows up in the unassigned/pending list again. Data is never
// destroyed, so groups can be re-created later.
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
let tp_table = crate::core::db::schema::table_name("trace_profiles");
let ext_id_face = format!("face_track_{}", trace_id);
let ext_id_trace = format!("trace_{}", trace_id);
let default_name = format!("Face Trace {}", trace_id);
// 1. Save TKG nodes before reset (for undo)
let tkg_snapshot: Vec<(String, String, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT external_id, label, properties FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
nodes_table
@@ -1770,43 +1737,44 @@ 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();
// 1b. Save trace profile before reset (for undo)
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;
// 4. Delete TKG nodes
// 2. Reset tkg_nodes label to the unassigned default (rows preserved)
let _ = sqlx::query(&format!(
"DELETE FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND (external_id = $3 OR external_id = $4)",
nodes_table
))
.bind(&default_name)
.bind(&file_uuid)
.bind(&ext_id_face)
.bind(&ext_id_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())
// 3. Reset trace_profiles name to the unassigned default (UPSERT so the
// row is also created when it was missing)
let _ = crate::core::db::schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
trace_id,
&default_name,
None,
)
.await;
// 5. Save operation snapshot
// 4. Keep _faces points intact (do NOT delete)
// 5. Save operation snapshot for undo
let op_table = crate::core::db::schema::table_name("trace_operation_history");
let before_snapshot = serde_json::json!({
"trace_id": trace_id,
@@ -1839,7 +1807,8 @@ async fn delete_trace(
"file_uuid": file_uuid,
"trace_id": trace_id,
"hard_delete": true,
"trashed_points": trashed_points.len(),
"unassigned": true,
"message": format!("Trace {} restored to unassigned (data preserved)", trace_id),
}))
} else {
// Soft delete: mark as deleted in Qdrant and TKG
@@ -2075,7 +2044,118 @@ async fn restore_trace(
) -> Json<serde_json::Value> {
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
// Restore Qdrant points: clear deleted status
// Restore semantics depend on the recorded operation:
// - "hard_delete" now preserves data and only resets names, so undo
// restores the original name/label from the operation snapshot.
// - Legacy soft delete (status=deleted markers) is still cleared.
let op_table = crate::core::db::schema::table_name("trace_operation_history");
let snapshot: Option<(i64, serde_json::Value)> = sqlx::query_as(&format!(
"SELECT id, before_snapshot FROM {} \
WHERE file_uuid = $1 AND operation = 'hard_delete' AND is_undone = false \
AND before_snapshot->>'trace_id' = $2::text \
ORDER BY created_at DESC LIMIT 1",
op_table
))
.bind(&file_uuid)
.bind(trace_id)
.fetch_optional(state.db.pool())
.await
.unwrap_or(None);
if let Some((history_id, before_snapshot)) = snapshot {
let nodes_table = crate::core::db::schema::table_name("tkg_nodes");
let ext_id_face = format!("face_track_{}", trace_id);
let ext_id_trace = format!("trace_{}", trace_id);
// Restore tkg_nodes label
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("");
let props = node
.get("properties")
.cloned()
.unwrap_or(serde_json::json!({"trace_id": trace_id}));
if !label.is_empty() {
let _ = sqlx::query(&format!(
"UPDATE {} SET label = $1, properties = $2 \
WHERE file_uuid = $3 AND node_type = 'face_track' AND external_id = $4",
nodes_table
))
.bind(label)
.bind(&props)
.bind(&file_uuid)
.bind(ext_id)
.execute(state.db.pool())
.await;
}
}
}
// Restore trace_profiles name
let profile_name = before_snapshot["trace_profiles"]
.as_array()
.and_then(|arr| {
arr.iter()
.find(|p| p["trace_id"].as_i64() == Some(trace_id as i64))
})
.and_then(|p| p["name"].as_str().map(String::from))
.unwrap_or_else(|| format!("Face Trace {}", trace_id));
let _ = crate::core::db::schema::upsert_trace_profile(
state.db.pool(),
&file_uuid,
trace_id,
&profile_name,
None,
)
.await;
// Clear any legacy deleted status markers
let legacy_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": &file_uuid}},
{"key": "trace_id", "match": {"value": trace_id}},
{"key": "status", "match": {"value": "deleted"}}
]
});
let _ = qdrant
.update_payload_by_filter(
"_faces",
legacy_filter,
serde_json::json!({"status": serde_json::Value::Null}),
)
.await;
let _ = sqlx::query(&format!(
"UPDATE {} SET properties = properties - 'status' \
WHERE file_uuid = $1 AND node_type = 'face_track' AND (external_id = $2 OR external_id = $3)",
nodes_table
))
.bind(&file_uuid)
.bind(&ext_id_face)
.bind(&ext_id_trace)
.execute(state.db.pool())
.await;
// Mark snapshot as undone
let _ = sqlx::query(&format!(
"UPDATE {} SET is_undone = true, undone_at = NOW() WHERE id = $1",
op_table
))
.bind(history_id)
.execute(state.db.pool())
.await;
return Json(serde_json::json!({
"success": true,
"file_uuid": file_uuid,
"trace_id": trace_id,
"name_restored": true,
"restored_name": profile_name,
"tkg_nodes_restored": tkg_snapshot_count(&before_snapshot),
}));
}
// Legacy path: soft-deleted trace (status=deleted markers), clear them
let filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
@@ -2084,7 +2164,6 @@ async fn restore_trace(
]
});
// Get count of points to restore
let points_to_restore = qdrant
.scroll_all_points("_faces", filter.clone(), 1)
.await
@@ -2098,7 +2177,6 @@ async fn restore_trace(
}));
}
// Clear the deleted status
let clear_payload = serde_json::json!({
"status": serde_json::Value::Null
});
@@ -2151,7 +2229,15 @@ async fn restore_trace(
"success": true,
"file_uuid": file_uuid,
"trace_id": trace_id,
"name_restored": false,
"qdrant_restored": qdrant_restored,
"tkg_nodes_restored": tkg_restored
}))
}
fn tkg_snapshot_count(before_snapshot: &serde_json::Value) -> usize {
before_snapshot["tkg_nodes"]
.as_array()
.map(|a| a.len())
.unwrap_or(0)
}