From 4a480f46fd7b434ab7108a0411690bd897ec2b15 Mon Sep 17 00:00:00 2001 From: Accusys Date: Fri, 31 Jul 2026 14:04:16 +0800 Subject: [PATCH] fix: face-groups trace_id mapping + robust group merge Two bugs broke Studio "Merge groups" on files where trace_profiles.properties is empty {}: 1. get_face_groups_handler derived each group's trace_ids from COALESCE(tp.properties, tn.properties)->>'trace_id'. Since trace_profiles.properties is {} the value was NULL -> fell back to 0 for every row, so all groups reported trace_ids:[0] and group_uuid:None. This corrupted Studio's group selection and caused the merge to fail with "Target group cannot be in source_groups list" (the target name collided with a corrupted source entry). Now reads the real tp.trace_id (falling back to tn.properties->>'trace_id'). 2. merge_groups_handler matched/updated tkg_nodes.label by the source group NAME, which silently no-ops when tkg_nodes.label has drifted out of sync with trace_profiles.name (e.g. after re-cluster), yielding traces_merged:0. Rewrote it to resolve source trace_ids from trace_profiles.name, then update both trace_profiles.name and tkg_nodes.label by external_id=trace_{tid}, keeping both tables in sync. Also defensively drops the target name from source_groups so a client echoing the target no longer hard-fails. Verified on file 9cbeb112 (FilmRiot): 17 groups now map to distinct trace_ids 0-16; merge Person_4+Person_5 -> Person_0 yields traces_merged:2 and updates both tp.name and tn.label. Test mutations were reverted so the file is back to its original 17-group state. --- src/api/profile.rs | 91 ++++++++++++++++++++++++---------------------- 1 file changed, 47 insertions(+), 44 deletions(-) diff --git a/src/api/profile.rs b/src/api/profile.rs index 7e435abc..20b5962c 100644 --- a/src/api/profile.rs +++ b/src/api/profile.rs @@ -390,17 +390,16 @@ pub async fn merge_groups_handler( ) -> Result, (StatusCode, Json)> { 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" - })), - )); - } + // Defensively drop the target name from the source list so a merge does + // not fail just because the client echoed the target among sources. + let source_groups: Vec = req + .source_groups + .iter() + .filter(|g| *g != &req.target_group_name) + .cloned() + .collect(); - if req.source_groups.is_empty() { + if source_groups.is_empty() { return Err(( StatusCode::BAD_REQUEST, Json(serde_json::json!({ @@ -417,7 +416,7 @@ pub async fn merge_groups_handler( tp_table )) .bind(&req.file_uuid) - .bind(&req.source_groups) + .bind(&source_groups) .fetch_all(state.db.pool()) .await .map_err(|e| { @@ -428,29 +427,15 @@ pub async fn merge_groups_handler( ) })?; - // Update trace_profiles.name AND tkg_nodes.label for all matching traces - let nodes_table = schema::table_name("tkg_nodes"); - - // First update tkg_nodes.label - let nodes_result = sqlx::query(&format!( - "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND label = ANY($3)", - nodes_table - )) - .bind(&req.target_group_name) - .bind(&req.file_uuid) - .bind(&req.source_groups) - .execute(state.db.pool()) - .await; - - // Then collect matching trace_ids from tkg_nodes (FS source of truth) + // Resolve source trace_ids from trace_profiles.name (the grouping source + // of truth). We match by name rather than by tkg_nodes.label to stay + // correct even when tkg_nodes.label has drifted out of sync. let matching_trace_ids: Vec = 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 + "SELECT trace_id FROM {} WHERE file_uuid = $1 AND name = ANY($2) ORDER BY trace_id", + tp_table )) .bind(&req.file_uuid) - .bind(&req.source_groups) + .bind(&source_groups) .fetch_all(state.db.pool()) .await .map_err(|e| { @@ -461,6 +446,30 @@ pub async fn merge_groups_handler( ) })?; + // Update tkg_nodes.label for the resolved trace_ids (by external_id, not + // by the possibly-stale label) so both tables stay consistent. + let nodes_table = schema::table_name("tkg_nodes"); + // Build an IN list of external_id values ('trace_{tid}'). When there are + // no matches we use IN (NULL) which safely affects zero rows. + let in_list = if matching_trace_ids.is_empty() { + "NULL".to_string() + } else { + matching_trace_ids + .iter() + .map(|tid| format!("'trace_{}'", tid)) + .collect::>() + .join(", ") + }; + let nodes_result = sqlx::query(&format!( + "UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' \ + AND external_id IN ({})", + nodes_table, in_list + )) + .bind(&req.target_group_name) + .bind(&req.file_uuid) + .execute(state.db.pool()) + .await; + // UPSERT each matching trace profile to the target name let mut updated: u64 = 0; for trace_id in &matching_trace_ids { @@ -495,7 +504,7 @@ pub async fn merge_groups_handler( match nodes_result { Ok(nodes_res) => { let nodes_updated = nodes_res.rows_affected(); - let group_count = req.source_groups.len(); + let group_count = source_groups.len(); let target_name = req.target_group_name.clone(); let before_map: serde_json::Map = before_names @@ -506,7 +515,7 @@ pub async fn merge_groups_handler( state.db.pool(), &req.file_uuid, "merge_groups", - serde_json::json!({ "traces": before_map, "target": &target_name, "sources": &req.source_groups }), + serde_json::json!({ "traces": before_map, "target": &target_name, "sources": &source_groups }), Some(serde_json::json!({ "traces": before_names.iter().map(|(tid, _)| (tid.to_string(), serde_json::json!(&target_name))).collect::>(), "target": &target_name, @@ -517,7 +526,7 @@ pub async fn merge_groups_handler( Ok(Json(MergeGroupsResponse { success: true, file_uuid: req.file_uuid, - source_groups: req.source_groups, + source_groups, target_group_name: target_name.clone(), traces_merged: updated, message: format!("Merged {} group(s) into '{}'", group_count, target_name), @@ -1175,14 +1184,14 @@ pub async fn get_face_groups_handler( 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!( + let rows: Vec<(String, i32)> = sqlx::query_as(&format!( "SELECT COALESCE(tp.name, tn.label) as name, \ - COALESCE(tp.properties, tn.properties) as properties \ + COALESCE(tp.trace_id, (tn.properties->>'trace_id')::int) as trace_id \ 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 (COALESCE(tp.properties, tn.properties)->>'trace_id')::int", + ORDER BY trace_id", tkg_table, tp_table )) .bind(&file_uuid) @@ -1196,13 +1205,7 @@ pub async fn get_face_groups_handler( let mut groups: HashMap> = HashMap::new(); let mut unassigned: Vec = Vec::new(); - for (name, properties) in rows { - let trace_id = properties - .get("trace_id") - .and_then(|v| v.as_i64()) - .map(|v| v as i32) - .unwrap_or(0); - + for (name, trace_id) in rows { if name.starts_with("Face Trace ") || name.starts_with("Trace ") { unassigned.push(trace_id); } else {