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:
@@ -0,0 +1,197 @@
|
||||
# Studio Face Group API 斷點對照
|
||||
|
||||
**Date:** 2026-07-31
|
||||
**Status:** Analysis Report
|
||||
**Author:** OpenCode
|
||||
**Scope:** Studio (`momentry_studio`) 依賴 Core 的 face group 相關 API 斷點分析
|
||||
|
||||
---
|
||||
|
||||
## 一、背景
|
||||
|
||||
Core 完成 trace_profiles UPSERT 修復後(`2026-07-31_trace_profile_upsert_fix_plan.md`),
|
||||
確認 rename/undo/delete/restore 的 API contract 完全相容,Studio 端不需要改動。
|
||||
|
||||
但調查過程中發現 Studio 的 **face group 顯示流程** 存在三個既存斷點
|
||||
(與本次 UPSERT 修復無關,先前調查已記錄):
|
||||
|
||||
| # | Studio 呼叫 | Core 端點 | 狀態 |
|
||||
|---|-------------|-----------|------|
|
||||
| 1 | `get_cluster_results` | `GET /api/v1/cluster-results?file_hash=` | ❌ 404 (Core 無此端點) |
|
||||
| 2 | `get_identity_matches` | `GET /api/v1/identity-matches?file_hash=` | ❌ 404 (Core 無此端點) |
|
||||
| 3 | `get_similar_face_groups` | `GET /api/v1/file/:file_uuid/face-groups/similar` | ⚠️ 逾時 (183K points 全量 scroll) |
|
||||
|
||||
---
|
||||
|
||||
## 二、斷點 1:`cluster-results`(影響最大)
|
||||
|
||||
### Studio 端呼叫
|
||||
|
||||
- `momentry_studio/src/api/index.ts:471-473`
|
||||
```typescript
|
||||
case 'get_cluster_results': {
|
||||
return { url: `/api/v1/cluster-results?file_hash=${a.fileHash}`, method: 'GET' }
|
||||
}
|
||||
```
|
||||
|
||||
- `momentry_studio/src/views/PeopleView.vue:848-976` `loadClusterResults()`:
|
||||
- 入口:`faceGroups` computed(line 624-658)依賴 `clusterResults`
|
||||
- 選檔、cluster 完成後、rename 後都會重新 load
|
||||
- 回傳需含 `face_groups` 或 `clusters` 陣列 + `frames` 陣列
|
||||
|
||||
### Studio 預期回應格式(PeopleView.vue:864-893)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"face_groups": [ // 或 "clusters"
|
||||
{
|
||||
"group_id": 1, // 沒有時 fallback 用 cluster_id
|
||||
"cluster_id": "c01", // 可選,統一用 group_id
|
||||
"name": "Person_1",
|
||||
"trace_ids": [12, 34],
|
||||
"trace_count": 2,
|
||||
"representative_trace": 12
|
||||
}
|
||||
],
|
||||
"frames": [ // 每個 group 的 member_faces / face_count 來源
|
||||
{
|
||||
"frame": 100,
|
||||
"timestamp": 3.33,
|
||||
"faces": [
|
||||
{ "face_id": "face_12", "confidence": 0.9, "cluster_id": "c01" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- Studio 對每個 group 會填 `member_faces`、`face_count`(line 889-893)
|
||||
- group 沒有 `name` 時 fallback 為 `group NN`(line 641)
|
||||
|
||||
### Core 現況
|
||||
|
||||
Core 完全沒有 `cluster-results` 端點(`grep cluster-results src/` 無結果)。
|
||||
|
||||
**可替代方案**:Core 已有 `GET /api/v1/file/:file_uuid/face-groups`
|
||||
(`src/api/profile.rs:1325`),回應:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"face_groups": [
|
||||
{
|
||||
"group_id": 1,
|
||||
"name": "Person_1",
|
||||
"trace_ids": [12, 34],
|
||||
"trace_count": 2,
|
||||
"representative_trace": 12,
|
||||
"editable": true
|
||||
}
|
||||
],
|
||||
"total_groups": 1,
|
||||
"unassigned_traces": [99]
|
||||
}
|
||||
```
|
||||
|
||||
差異:
|
||||
| 欄位 | Studio 預期 (`cluster-results`) | Core (`face-groups`) |
|
||||
|------|-------------------------------|----------------------|
|
||||
| group 列表 | `face_groups` | `face_groups` ✅ |
|
||||
| `cluster_id` | 可選(fallback 用 group_id) | 無 → Studio 會用 `group_id` ✅ |
|
||||
| `trace_ids` | 需要 | 有 ✅ |
|
||||
| `representative_trace` | 需要 | 有 ✅ |
|
||||
| `frames[]` / `member_faces` | 需要(顯示成員臉) | ❌ 無 |
|
||||
| `unassigned_traces` | 未用 | 有(額外) |
|
||||
|
||||
→ **缺 `frames[]`** 是主要差距。Studio 用它建立 `member_faces`(點擊 group 顯示成員臉)。
|
||||
|
||||
---
|
||||
|
||||
## 三、斷點 2:`identity-matches`
|
||||
|
||||
### Studio 端呼叫
|
||||
|
||||
- `momentry_studio/src/api/index.ts:465-467`
|
||||
```typescript
|
||||
case 'get_identity_matches': {
|
||||
return { url: `/api/v1/identity-matches?file_hash=${a.fileHash}`, method: 'GET' }
|
||||
}
|
||||
```
|
||||
|
||||
- `momentry_studio/src/views/PeopleView.vue:943-970`:抓 TMDB identity 建議,
|
||||
對每個 cluster 統計 trace → suggestion 的 `group_uuid` 映射,取最高頻者設為
|
||||
`c.tmdb_name` / `c.tmdb_uuid` / `c.tmdb_count`。
|
||||
|
||||
### Studio 預期回應格式(PeopleView.vue:945-946)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"suggestions": {
|
||||
"12": { "group_uuid": "tmdb-xxx", "name": "Alice" }, // key = trace_id (string)
|
||||
"34": { "group_uuid": "tmdb-xxx", "name": "Alice" }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Core 現況
|
||||
|
||||
Core 無此端點。若無法提供,**影響有限**:Studio 已用 `try/catch` 包住
|
||||
(line 970 `catch { /* no identity matches available */ }`),
|
||||
404 時只是 TMDB 名稱建議不顯示,不阻斷 face group 流程。
|
||||
|
||||
---
|
||||
|
||||
## 四、斷點 3:`face-groups/similar`(逾時)
|
||||
|
||||
### Studio 端呼叫
|
||||
|
||||
- `momentry_studio/src/api/index.ts:474-480`
|
||||
```typescript
|
||||
case 'get_similar_face_groups': {
|
||||
const params = new URLSearchParams()
|
||||
if (a.traceIds) params.set('trace_ids', String(a.traceIds))
|
||||
if (a.topK) params.set('top_k', String(a.topK))
|
||||
if (a.minScore) params.set('min_score', String(a.minScore))
|
||||
return { url: `/api/v1/file/${a.fileUuid}/face-groups/similar?${params.toString()}`, method: 'GET' }
|
||||
}
|
||||
```
|
||||
|
||||
### Core 現況
|
||||
|
||||
Core 有端點(`src/api/profile.rs:1329`,handler `get_similar_group_handler`),
|
||||
回應格式:
|
||||
```jsonc
|
||||
{
|
||||
"success": true,
|
||||
"file_uuid": "...",
|
||||
"suggestions": [
|
||||
{ "group_name": "Person_1", "score": 0.91, "matched_trace_id": 12 }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**問題**:handler 對 source trace 的 `_faces` 做全量 scroll(183K points),
|
||||
實測逾時。屬效能問題,非格式問題。
|
||||
|
||||
---
|
||||
|
||||
## 五、建議(角色分工待確認)
|
||||
|
||||
> **注意**:`momentry_studio/` 屬 Studio team 負責,Core team 不可直接改;
|
||||
> Core route 新增屬 API 設計決策,不應由實作方單方面決定(見 AGENTS.md)。
|
||||
|
||||
| 方案 | 做法 | 負責方 |
|
||||
|------|------|--------|
|
||||
| A | Core 新增 `GET /api/v1/cluster-results` alias → 轉發 `face-groups` + 附 `frames[]` | Core (需使用者/路由設計拍板) |
|
||||
| B | Studio 改用 `GET /file/:file_uuid/face-groups` + 另行組 `frames[]` | Studio team |
|
||||
| C | 暫緩,僅記錄。cluster-results 404 時 face group 列表不顯示 | 維持現狀 |
|
||||
|
||||
`identity-matches` 影響最小(已 try/catch),`similar` 為效能問題需 Core 優化 scroll。
|
||||
|
||||
---
|
||||
|
||||
## 六、Version History
|
||||
|
||||
| Version | Date | Author | Changes |
|
||||
|---------|------|--------|---------|
|
||||
| 1.0 | 2026-07-31 | OpenCode | Initial analysis report |
|
||||
+21
-26
@@ -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
@@ -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(¤t_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(¤t_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",
|
||||
|
||||
@@ -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!(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use sqlx::PgPool;
|
||||
|
||||
/// Schema-qualified table name helper
|
||||
/// Returns `name` for public schema, `schema.name` for others
|
||||
pub fn t(name: &str) -> String {
|
||||
@@ -13,3 +15,67 @@ pub fn table_name(name: &str) -> String {
|
||||
format!("{}.{}", schema, name)
|
||||
}
|
||||
}
|
||||
|
||||
/// UPSERT a trace profile row (insert on missing, update name on existing).
|
||||
/// When inserting a new row, backfills start_frame/end_frame/frame_count/
|
||||
/// key_frame/key_face/avg_confidence/properties from tkg_nodes face_track node
|
||||
/// so the created profile is complete.
|
||||
///
|
||||
/// `properties`: when provided, also overwrites the properties column on conflict;
|
||||
/// when `None`, only `name` is updated on conflict and properties are preserved.
|
||||
pub async fn upsert_trace_profile(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
name: &str,
|
||||
properties: Option<&serde_json::Value>,
|
||||
) -> anyhow::Result<u64> {
|
||||
let tp_table = table_name("trace_profiles");
|
||||
let tkg_table = table_name("tkg_nodes");
|
||||
|
||||
let tkg_sub = |col: &str| {
|
||||
format!(
|
||||
"(SELECT {col} FROM {tkg_table} tn WHERE tn.file_uuid = $1 \
|
||||
AND tn.node_type = 'face_track' AND (tn.properties->>'trace_id')::int = $2)"
|
||||
)
|
||||
};
|
||||
|
||||
let update_props = if properties.is_some() {
|
||||
", properties = EXCLUDED.properties"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
|
||||
let sql = format!(
|
||||
"INSERT INTO {tp_table} (file_uuid, trace_id, name, start_frame, end_frame, \
|
||||
frame_count, key_frame, key_face, status, avg_confidence, properties) \
|
||||
VALUES ($1, $2, $3, {sf}, {ef}, {fc}, {kf}, {kface}, 'pending', {avgc}, \
|
||||
COALESCE($4::jsonb, {props_sub}, '{{}}'::jsonb)) \
|
||||
ON CONFLICT (file_uuid, trace_id) \
|
||||
DO UPDATE SET name = EXCLUDED.name{update_props}, updated_at = NOW()",
|
||||
sf = tkg_sub("(tn.properties->>'start_frame')::bigint"),
|
||||
ef = tkg_sub("(tn.properties->>'end_frame')::bigint"),
|
||||
fc = tkg_sub("(tn.properties->>'frame_count')::int"),
|
||||
kf = tkg_sub("tn.properties->>'key_frame'"),
|
||||
kface = tkg_sub("tn.properties->>'key_face'"),
|
||||
avgc = tkg_sub("(tn.properties->>'avg_confidence')::double precision"),
|
||||
props_sub = tkg_sub("tn.properties"),
|
||||
);
|
||||
|
||||
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());
|
||||
query = query.bind(json);
|
||||
}
|
||||
None => {
|
||||
query = query.bind(Option::<String>::None);
|
||||
}
|
||||
}
|
||||
|
||||
let res = query.execute(pool).await?;
|
||||
Ok(res.rows_affected())
|
||||
}
|
||||
|
||||
+14
-17
@@ -2986,7 +2986,6 @@ impl JobWorker {
|
||||
}
|
||||
|
||||
let tkg_table = crate::core::db::schema::table_name("tkg_nodes");
|
||||
let tp_table = crate::core::db::schema::table_name("trace_profiles");
|
||||
|
||||
// Update traces that ARE in clusters
|
||||
for (trace_id, cluster_id) in &trace_to_cluster {
|
||||
@@ -3020,14 +3019,13 @@ impl JobWorker {
|
||||
}
|
||||
|
||||
// Sync name to trace_profiles
|
||||
let _ = sqlx::query(&format!(
|
||||
"UPDATE {} SET name = $1 WHERE file_uuid = $2 AND trace_id = $3",
|
||||
tp_table
|
||||
))
|
||||
.bind(&label)
|
||||
.bind(uuid)
|
||||
.bind(trace_id)
|
||||
.execute(db.pool())
|
||||
let _ = schema::upsert_trace_profile(
|
||||
db.pool(),
|
||||
uuid,
|
||||
*trace_id as i32,
|
||||
&label,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
@@ -3048,14 +3046,13 @@ impl JobWorker {
|
||||
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(uuid)
|
||||
.bind(tid)
|
||||
.execute(db.pool())
|
||||
let _ = schema::upsert_trace_profile(
|
||||
db.pool(),
|
||||
uuid,
|
||||
*tid as i32,
|
||||
&name,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
updated_count += 1;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user