feat: sync_trace_label unified function + fix is_tkg_done

- Created trace_sync module with sync_trace_label() to sync labels across:
  1. tkg_nodes.label (PostgreSQL)
  2. trace_profiles.name (PostgreSQL)
  3. trace_profile.json label (FS)
  4. Qdrant _faces payload.label (NEW - was missing)

- Fixed is_tkg_done: allow 0 trace dirs if tkg_nodes exist
  (prevents permanent stuck in 'Scanning' status)

- Updated Face Cluster to use sync_trace_label
- Updated merge_trace to use sync_trace_label + cleanup source dir

- Created Face_Operations_Complete.md reference document
  (consolidates all face-related docs into single source of truth)
This commit is contained in:
Accusys
2026-10-18 14:15:12 +08:00
parent f3013c8509
commit 58431d1d8d
5 changed files with 622 additions and 53 deletions
@@ -0,0 +1,347 @@
# Face Operations Complete Reference
**Date**: 2026-10-18
**Version**: 1.0
**Author**: Core Team
**Status**: Active
---
## 1. 完整處理流程
### 1.1 Pipeline 概覽
```
Video Frames
│
▼
┌─────────────────────────────────────────┐
│ 0. Face Detection (Swift/Apple Vision) │
│ - swift_face binary (ANE 加速) │
│ - 輸出: face.json (bbox + confidence) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ 1. Face Embedding (FaceNet CoreML) │
│ - facenet512.mlpackage │
│ - 512D 向量寫入 Qdrant _faces │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ 2. Face Trace (Rust) │
│ - rust_store_traced_faces │
│ - IoU + Embedding 相似度匹配 │
│ - 輸出: face_traced.json + trace_id │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ 3. Face Cluster (Rust) │
│ - rust_face_cluster │
│ - 同人判斷 → label 分配 │
│ - 同步到三個位置 (見 §3) │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ 4. TKG Build │
│ - tkg_nodes (face_track nodes) │
│ - trace_profile.json (FS) │
│ - key_frame.jpg + key_face.jpg │
└─────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ 5. Identity Binding │
│ - identity_uuid 綁定 │
│ - known person / stranger │
└─────────────────────────────────────────┘
```
### 1.2 各階段工具
| 階段 | 工具 | 語言 | 加速 |
|------|------|------|------|
| Face Detection | `swift_face` | Swift | Apple Vision ANE |
| Face Embedding | `facenet512.mlpackage` | CoreML | ANE |
| Face Trace | `rust_store_traced_faces` | Rust | CPU |
| Face Cluster | `rust_face_cluster` | Rust | CPU |
| TKG Build | `build_tkg()` | Rust | CPU |
---
## 2. 數據存儲架構
### 2.1 三層存儲
```
┌─────────────────────────────────────────────────────────┐
│ Qdrant _faces collection │
│ - 512D 向量 (FaceNet embedding) │
│ - payload: { │
│ trace_id, identity_id, label, frame, file_uuid, │
│ bbox, confidence, ... │
│ } │
└─────────────────────────────────────────────────────────┘
│
│ 同步 (應為雙向,目前有漏洞)
▼
┌─────────────────────────────────────────────────────────┐
│ PostgreSQL │
│ ├── tkg_nodes (face_track nodes) │
│ │ - label 字段 │
│ │ - properties: {trace_id, start_frame, ...} │
│ └── trace_profiles │
│ - name 字段 │
│ - vlm_description, vlm_tags, ... │
└─────────────────────────────────────────────────────────┘
│
│ 同步
▼
┌─────────────────────────────────────────────────────────┐
│ Filesystem (FS) │
│ └── output/{file_uuid}/trace_{id}/ │
│ ├── trace_profile.json (label 字段) │
│ ├── key_frame.jpg │
│ └── key_face.jpg │
└─────────────────────────────────────────────────────────┘
```
### 2.2 字段對應表
| Qdrant _faces payload | PostgreSQL tkg_nodes | PostgreSQL trace_profiles | FS trace_profile.json |
|----------------------|---------------------|--------------------------|----------------------|
| `trace_id` | `properties->trace_id` | `trace_id` | `trace_id` |
| `identity_id` | `properties->identity_id` | `identity_id` | `identity_id` |
| **`label`** | **`label`** | **`name`** | **`label`** |
| `frame` | `properties->start_frame` | `start_frame` | `start_frame` |
| `bbox` | `properties->avg_bbox` | `avg_bbox` | `avg_bbox` |
| `confidence` | `properties->avg_confidence` | `avg_confidence` | `avg_confidence` |
---
## 3. 同步機制
### 3.1 Face Cluster 同步流程
```rust
// job_worker.rs:4410-4461
for (trace_id, cluster_id) in &trace_to_cluster {
let label = cluster_id.clone();
// 1. 更新 tkg_nodes.label ✅
UPDATE tkg_nodes SET label = $1 WHERE ...
// 2. 更新 trace_profiles.name ✅
upsert_trace_profile(pool, uuid, trace_id, &label, None)
// 3. 更新 trace_profile.json (FS) ✅
profile["label"] = serde_json::json!(label);
// 4. ❌ Qdrant _faces payload.label 沒有更新 → **漏洞**
}
```
### 3.2 當前同步狀態
| 操作 | tkg_nodes.label | trace_profiles.name | trace_profile.json | Qdrant _faces label |
|------|-----------------|---------------------|-------------------|---------------------|
| Face Cluster | ✅ | ✅ | ✅ | ❌ |
| merge_trace | 刪除源 | - | ❌ | ✅ trace_id |
---
## 4. API Endpoints 完整列表
### 4.1 Trace API
| Method | Endpoint | 說明 |
|--------|----------|------|
| `POST` | `/api/v1/file/:uuid/traces` | Trace 列表(排序) |
| `GET` | `/api/v1/file/:uuid/trace/:trace_id/faces` | Trace 內 faces |
| `GET` | `/api/v1/file/:uuid/trace/:trace_id/representative-face` | 代表人臉 |
| `GET` | `/api/v1/file/:uuid/trace/:trace_id/thumbnail` | Trace 縮圖 |
| `POST` | `/api/v1/file/:uuid/trace/:trace_id/merge/:target_id` | 合併 trace |
| `DELETE` | `/api/v1/file/:uuid/trace/:trace_id` | 刪除 trace |
| `POST` | `/api/v1/file/:uuid/trace/:trace_id/restore` | 恢復 trace |
| `POST` | `/api/v1/file/:uuid/trace/:trace_id/regenerate-thumbnail` | 重新生成縮圖 |
### 4.2 Cluster/Identity API
| Method | Endpoint | 說明 |
|--------|----------|------|
| `POST` | `/api/v1/identity/:uuid/bind` | 綁定身份 |
| `POST` | `/api/v1/identity/:uuid/bind/undo` | 撤銷綁定 |
| `POST` | `/api/v1/identity/:uuid/bind/redo` | 重做綁定 |
| `GET` | `/api/v1/identity/:uuid/bind/history` | 綁定歷史 |
| `GET` | `/api/v1/search/people` | 搜尋人物 |
### 4.3 TKG API
| Method | Endpoint | 說明 |
|--------|----------|------|
| `GET` | `/api/v1/file/:uuid/tkg` | TKG 操作列表 |
| `POST` | `/api/v1/file/:uuid/tkg` | 重建 TKG |
| `DELETE` | `/api/v1/file/:uuid/tkg` | 刪除 TKG |
| `POST` | `/api/v1/file/:uuid/tkg/nodes` | 查詢 nodes |
| `POST` | `/api/v1/file/:uuid/tkg/edges` | 查詢 edges |
| `GET` | `/api/v1/file/:uuid/tkg/node/:node_id` | Node 詳情 |
---
## 5. 已知漏洞
### 5.1 Qdrant Label 不同步 🔴
**問題**: Face Cluster 和 merge_trace 操作沒有更新 Qdrant `_faces` collection 的 `payload.label`
**影響**:
- 前端搜索 Qdrant 時可能拿到舊 label
- 數據不一致
**修復**: 創建 `sync_trace_label` 統一函數(見 §6.2)
### 5.2 merge_trace 後 trace_profile.json 未更新 🟡
**問題**: merge 操作後,源 trace 的 `trace_profile.json` 沒有刪除或更新
**影響**: FS 數據與數據庫不一致
**修復**: 添加 `post_merge_cleanup` 函數(見 §6.3)
### 5.3 is_tkg_done 太嚴格 🟡
**問題**: 如果 trace 目錄 = 0,`is_tkg_done` 返回 false → 永久卡住
**影響**: 文件無法完成處理(如 `5a0aca42` 有 1881 traces 但 0 dirs)
**修復**: 放寬檢查邏輯(見 §6.1)
---
## 6. 改善方案
### 6.1 修復 is_tkg_done
**文件**: `src/worker/job_worker.rs` ~line 2031
```rust
// 當前:trace 目錄 = 0 → 返回 false → 永久卡住
if trace_count == 0 { return false; }
// 修復後:如果有 tkg_nodes 記錄,視為完成
if count > 0 {
if trace_count == 0 {
tracing::warn!("[TKG] {} has nodes but no trace dirs, proceeding anyway", uuid);
}
return true;
}
```
### 6.2 創建 sync_trace_label 統一函數
**新文件**: `src/core/trace_sync.rs`
```rust
pub async fn sync_trace_label(
pool: &PgPool,
qdrant: &QdrantDb,
file_uuid: &str,
trace_id: i32,
new_label: &str,
) -> Result<SyncResult> {
// 1. 更新 tkg_nodes.label
update_tkg_label(pool, file_uuid, trace_id, new_label).await?;
// 2. 更新 trace_profiles.name
upsert_trace_profile(pool, file_uuid, trace_id, new_label, None).await?;
// 3. 更新 trace_profile.json (FS)
update_fs_profile_label(file_uuid, trace_id, new_label).await?;
// 4. 更新 Qdrant _faces payload.label ← **新增**
update_qdrant_label(qdrant, file_uuid, trace_id, new_label).await?;
Ok(SyncResult { updated: 4 })
}
```
### 6.3 添加 post_merge_cleanup
**文件**: `src/api/trace_agent_api.rs`
```rust
async fn post_merge_cleanup(
pool: &PgPool,
qdrant: &QdrantDb,
file_uuid: &str,
source_trace_id: i32,
target_trace_id: i32,
) -> Result<()> {
// 1. 合併 frame_count
merge_trace_profiles(file_uuid, source_trace_id, target_trace_id).await?;
// 2. 刪除源 trace 目錄
remove_trace_dir(file_uuid, source_trace_id)?;
// 3. 刪除源 tkg_nodes
sqlx::query("DELETE FROM tkg_nodes WHERE ...")
.bind(file_uuid)
.bind(&format!("trace_{}", source_trace_id))
.execute(pool).await?;
Ok(())
}
```
### 6.4 數據一致性檢查 API
**新路由**: `GET /api/v1/file/:uuid/data-consistency`
```json
{
"tkg_nodes": 15,
"trace_profiles": 15,
"trace_dirs": 15,
"qdrant_points": 443,
"mismatches": []
}
```
---
## 7. 相關文件
### 7.1 代碼文件
| 文件 | 說明 |
|------|------|
| `src/core/processor/face.rs` | Face Detection + Embedding |
| `src/core/processor/tkg.rs` | TKG Build + trace_profile.json |
| `src/worker/job_worker.rs` | Face Cluster + is_tkg_done |
| `src/api/trace_agent_api.rs` | Trace API + merge_trace |
| `src/api/profile.rs` | Trace Profile API |
| `src/core/db/schema.rs` | upsert_trace_profile |
| `tools/cli/rust/src/bin/rust_store_traced_faces.rs` | Rust Face Trace |
| `tools/cli/rust/src/bin/rust_face_cluster.rs` | Rust Face Cluster |
### 7.2 歷史文件(已 Deprecated)
| 文件 | 狀態 |
|------|------|
| `docs_v1.0/REFERENCE/Face_Pipeline.md` | ⚠️ Deprecated |
| `docs_v1.0/DESIGN/Face_Pipeline.md` | ⚠️ Deprecated |
| `docs_v1.0/DESIGN/Rust_Store_Traced_Faces_Design.md` | ⚠️ Deprecated |
| `docs_v1.0/DESIGN/Swift_Face_Trace_Design.md` | ⚠️ Deprecated |
| `docs_v1.0/DESIGN/Trace_Inheritance_Rules.md` | ⚠️ Deprecated |
| `docs_v1.0/DESIGN/FACE_FILTER_FILE_STORAGE.md` | ⚠️ Deprecated |
---
**版本歷史**:
| 版本 | 日期 | 說明 |
|------|------|------|
| 1.0 | 2026-10-18 | 初始版本,整合所有 face 相關文檔 |