diff --git a/src/api/profile.rs b/src/api/profile.rs index 68123287..7e435abc 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -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(¶ms.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(¶ms.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 = vec_arr.iter().filter_map(|v| v.as_f64().map(|f| f as f32)).collect(); + let vector: Vec = 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, 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 = 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)> = 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, 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 = 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)> = 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 = 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 = 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 = 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 { "/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), diff --git a/src/api/trace_agent_api.rs b/src/api/trace_agent_api.rs index be12b795..25401559 100644 --- a/src/api/trace_agent_api.rs +++ b/src/api/trace_agent_api.rs @@ -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, 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 = 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)> = 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, 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, 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 { 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) +} diff --git a/src/core/db/schema.rs b/src/core/db/schema.rs index 2ae1bf27..1cbc4e69 100644 --- a/src/core/db/schema.rs +++ b/src/core/db/schema.rs @@ -62,10 +62,7 @@ pub async fn upsert_trace_profile( props_sub = tkg_sub("tn.properties"), ); - let mut query = sqlx::query(&sql) - .bind(file_uuid) - .bind(trace_id) - .bind(name); + let mut query = sqlx::query(&sql).bind(file_uuid).bind(trace_id).bind(name); match properties { Some(p) => { let json = serde_json::to_string(p).unwrap_or_else(|_| "{}".to_string()); @@ -79,3 +76,46 @@ pub async fn upsert_trace_profile( let res = query.execute(pool).await?; Ok(res.rows_affected()) } + +/// Ensure a face_track TKG node exists for the given trace. Self-healing: +/// when a group is (re)named but its tkg_nodes row was previously removed, +/// re-insert a default node so face-groups/cluster-results queries (which +/// read FROM tkg_nodes) keep working. Keeps an existing node untouched. +pub async fn ensure_face_track_node( + pool: &PgPool, + file_uuid: &str, + trace_id: i32, + name: &str, +) -> anyhow::Result { + let tkg_table = table_name("tkg_nodes"); + let ext_id_face = format!("face_track_{}", trace_id); + let ext_id_trace = format!("trace_{}", trace_id); + let props = serde_json::json!({ "trace_id": trace_id }); + + let existing: Option<(i64,)> = sqlx::query_as(&format!( + "SELECT id FROM {tkg_table} WHERE file_uuid = $1 AND node_type = 'face_track' \ + AND (external_id = $2 OR external_id = $3) LIMIT 1" + )) + .bind(file_uuid) + .bind(&ext_id_face) + .bind(&ext_id_trace) + .fetch_optional(pool) + .await?; + + if existing.is_some() { + return Ok(0); + } + + let sql = format!( + "INSERT INTO {tkg_table} (file_uuid, node_type, external_id, label, properties) \ + VALUES ($1, 'face_track', $2, $3, $4)" + ); + let res = sqlx::query(&sql) + .bind(file_uuid) + .bind(&ext_id_trace) + .bind(name) + .bind(&props) + .execute(pool) + .await?; + Ok(res.rows_affected()) +}