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:
@@ -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 相關文檔 |
|
||||
@@ -2488,6 +2488,64 @@ async fn merge_trace(
|
||||
.execute(state.db.pool())
|
||||
.await;
|
||||
|
||||
// Step 2c: Clean up source trace directory (FS)
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let source_trace_dir = std::path::Path::new(output_dir)
|
||||
.join(&file_uuid)
|
||||
.join(format!("trace_{}", trace_id));
|
||||
if source_trace_dir.exists() {
|
||||
let _ = std::fs::remove_dir_all(&source_trace_dir);
|
||||
tracing::info!(
|
||||
"[merge_trace] Removed source trace directory: {:?}",
|
||||
source_trace_dir
|
||||
);
|
||||
}
|
||||
|
||||
// Step 2d: Sync target trace label using sync_trace_label
|
||||
// Get target trace label from existing tkg_nodes
|
||||
let target_ext_id = format!("trace_{}", target_trace_id);
|
||||
let target_label: Option<String> = sqlx::query_scalar(&format!(
|
||||
"SELECT label FROM {} WHERE file_uuid = $1 AND node_type = 'face_track' AND external_id = $2",
|
||||
nodes_table
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.bind(&target_ext_id)
|
||||
.fetch_optional(state.db.pool())
|
||||
.await
|
||||
.ok()
|
||||
.flatten();
|
||||
|
||||
if let Some(label) = target_label {
|
||||
match crate::core::trace_sync::sync_trace_label(
|
||||
state.db.pool(),
|
||||
&qdrant,
|
||||
&file_uuid,
|
||||
target_trace_id,
|
||||
&label,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(sync_result) => {
|
||||
tracing::info!(
|
||||
"[merge_trace] sync_trace_label for target trace_{}: tkg={}, tp={}, fs={}, qdrant={} ({} points)",
|
||||
target_trace_id,
|
||||
sync_result.tkg_nodes_updated,
|
||||
sync_result.trace_profiles_updated,
|
||||
sync_result.fs_updated,
|
||||
sync_result.qdrant_updated,
|
||||
sync_result.qdrant_points_count
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[merge_trace] sync_trace_label failed for target trace_{}: {}",
|
||||
target_trace_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 3: Save operation snapshot for undo
|
||||
let op_table = crate::core::db::schema::table_name("trace_operation_history");
|
||||
let _ = sqlx::query(&format!(
|
||||
|
||||
@@ -37,5 +37,6 @@ pub mod thumbnail;
|
||||
pub mod time;
|
||||
pub mod tkg;
|
||||
pub mod tmdb;
|
||||
pub mod trace_sync;
|
||||
pub mod vision;
|
||||
pub mod vlm;
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
use sqlx::PgPool;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::core::db::qdrant_db::QdrantDb;
|
||||
use crate::core::db::schema;
|
||||
|
||||
/// 同步 trace label 到四個位置:
|
||||
/// 1. tkg_nodes.label
|
||||
/// 2. trace_profiles.name
|
||||
/// 3. trace_profile.json (FS) label
|
||||
/// 4. Qdrant _faces payload.label
|
||||
pub struct SyncResult {
|
||||
pub tkg_nodes_updated: bool,
|
||||
pub trace_profiles_updated: bool,
|
||||
pub fs_updated: bool,
|
||||
pub qdrant_updated: bool,
|
||||
pub qdrant_points_count: u64,
|
||||
}
|
||||
|
||||
/// 同步 trace label 到所有存儲位置
|
||||
pub async fn sync_trace_label(
|
||||
pool: &PgPool,
|
||||
qdrant: &QdrantDb,
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
new_label: &str,
|
||||
) -> anyhow::Result<SyncResult> {
|
||||
let mut result = SyncResult {
|
||||
tkg_nodes_updated: false,
|
||||
trace_profiles_updated: false,
|
||||
fs_updated: false,
|
||||
qdrant_updated: false,
|
||||
qdrant_points_count: 0,
|
||||
};
|
||||
|
||||
// 1. 更新 tkg_nodes.label
|
||||
match update_tkg_label(pool, file_uuid, trace_id, new_label).await {
|
||||
Ok(rows) => {
|
||||
result.tkg_nodes_updated = rows > 0;
|
||||
info!("[sync_trace_label] Updated tkg_nodes.label for trace_{}", trace_id);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("[sync_trace_label] Failed to update tkg_nodes.label: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 更新 trace_profiles.name
|
||||
match schema::upsert_trace_profile(pool, file_uuid, trace_id, new_label, None).await {
|
||||
Ok(_) => {
|
||||
result.trace_profiles_updated = true;
|
||||
info!("[sync_trace_label] Updated trace_profiles.name for trace_{}", trace_id);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("[sync_trace_label] Failed to update trace_profiles.name: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 更新 trace_profile.json (FS)
|
||||
match update_fs_profile_label(file_uuid, trace_id, new_label).await {
|
||||
Ok(_) => {
|
||||
result.fs_updated = true;
|
||||
info!("[sync_trace_label] Updated trace_profile.json for trace_{}", trace_id);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("[sync_trace_label] Failed to update trace_profile.json: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 更新 Qdrant _faces payload.label
|
||||
match update_qdrant_label(qdrant, file_uuid, trace_id, new_label).await {
|
||||
Ok(count) => {
|
||||
result.qdrant_updated = true;
|
||||
result.qdrant_points_count = count;
|
||||
info!(
|
||||
"[sync_trace_label] Updated Qdrant _faces label for trace_{} ({} points)",
|
||||
trace_id, count
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
warn!("[sync_trace_label] Failed to update Qdrant label: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// 更新 tkg_nodes.label
|
||||
async fn update_tkg_label(
|
||||
pool: &PgPool,
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
label: &str,
|
||||
) -> anyhow::Result<u64> {
|
||||
let tkg_table = schema::table_name("tkg_nodes");
|
||||
let ext_id_face = format!("face_track_{}", trace_id);
|
||||
let ext_id_trace = format!("trace_{}", trace_id);
|
||||
|
||||
let rows_updated = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' \
|
||||
AND (external_id = $3 OR external_id = $4)",
|
||||
tkg_table
|
||||
))
|
||||
.bind(label)
|
||||
.bind(file_uuid)
|
||||
.bind(&ext_id_face)
|
||||
.bind(&ext_id_trace)
|
||||
.execute(pool)
|
||||
.await?
|
||||
.rows_affected();
|
||||
|
||||
Ok(rows_updated)
|
||||
}
|
||||
|
||||
/// 更新 trace_profile.json (FS)
|
||||
async fn update_fs_profile_label(
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
label: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
use std::path::PathBuf;
|
||||
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let profile_path: PathBuf = [
|
||||
output_dir,
|
||||
file_uuid,
|
||||
&format!("trace_{}", trace_id),
|
||||
"trace_profile.json",
|
||||
]
|
||||
.iter()
|
||||
.collect();
|
||||
|
||||
if !profile_path.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(&profile_path)?;
|
||||
let mut profile: serde_json::Value = serde_json::from_str(&content)?;
|
||||
profile["label"] = serde_json::json!(label);
|
||||
std::fs::write(&profile_path, serde_json::to_string_pretty(&profile)?)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 更新 Qdrant _faces payload.label
|
||||
async fn update_qdrant_label(
|
||||
qdrant: &QdrantDb,
|
||||
file_uuid: &str,
|
||||
trace_id: i32,
|
||||
label: &str,
|
||||
) -> anyhow::Result<u64> {
|
||||
let filter = serde_json::json!({
|
||||
"must": [
|
||||
{"key": "file_uuid", "match": {"value": file_uuid}},
|
||||
{"key": "trace_id", "match": {"value": trace_id}}
|
||||
]
|
||||
});
|
||||
|
||||
// 先獲取點數
|
||||
let points_count = qdrant
|
||||
.scroll_all_points("_faces", filter.clone(), 1)
|
||||
.await
|
||||
.map(|pts| pts.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
if points_count == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
// 更新 payload
|
||||
let new_payload = serde_json::json!({
|
||||
"label": label
|
||||
});
|
||||
|
||||
qdrant
|
||||
.update_payload_by_filter("_faces", filter, new_payload)
|
||||
.await?;
|
||||
|
||||
Ok(points_count as u64)
|
||||
}
|
||||
+37
-53
@@ -2052,11 +2052,13 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.count();
|
||||
|
||||
if trace_count == 0 {
|
||||
// 有 tkg_nodes 記錄但沒有 trace 目錄 — 視為完成(可事後修復)
|
||||
// 這避免文件永久卡在 "Scanning" 狀態
|
||||
tracing::warn!(
|
||||
"[TKG] Database has {} records but no trace dirs for {}, returning false",
|
||||
count, uuid
|
||||
"[TKG] {} has {} nodes but no trace dirs, proceeding anyway (trace dirs can be backfilled later)",
|
||||
uuid, count
|
||||
);
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
tracing::info!(
|
||||
@@ -2066,11 +2068,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 無法讀取目錄 — 如果有 tkg_nodes 記錄,仍視為完成
|
||||
tracing::warn!(
|
||||
"[TKG] Database has {} records but cannot read trace dir for {}, returning false",
|
||||
count, uuid
|
||||
"[TKG] {} has {} nodes but cannot read trace dir, proceeding anyway",
|
||||
uuid, count
|
||||
);
|
||||
false
|
||||
true
|
||||
}
|
||||
|
||||
/// 檢查所有入庫步驟是否已完成(與 ingestion-status endpoint 同步邏輯)
|
||||
@@ -4405,57 +4408,38 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
let tkg_table = crate::core::db::schema::table_name("tkg_nodes");
|
||||
|
||||
// Update traces that ARE in clusters
|
||||
// Update traces that ARE in clusters using sync_trace_label
|
||||
let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
|
||||
for (trace_id, cluster_id) in &trace_to_cluster {
|
||||
let external_id = format!("trace_{}", trace_id);
|
||||
let label = cluster_id.clone();
|
||||
|
||||
let rows_updated = sqlx::query(&format!(
|
||||
"UPDATE {} SET label = $1 WHERE file_uuid = $2 AND node_type = 'face_track' AND external_id = $3",
|
||||
tkg_table
|
||||
))
|
||||
.bind(&label)
|
||||
.bind(uuid)
|
||||
.bind(&external_id)
|
||||
.execute(db.pool())
|
||||
// 使用統一同步函數(tkg_nodes + trace_profiles + FS + Qdrant)
|
||||
match crate::core::trace_sync::sync_trace_label(
|
||||
db.pool(),
|
||||
&qdrant,
|
||||
uuid,
|
||||
*trace_id as i32,
|
||||
&label,
|
||||
)
|
||||
.await
|
||||
.context("Failed to update tkg_nodes label")?
|
||||
.rows_affected();
|
||||
|
||||
if rows_updated == 0 {
|
||||
sqlx::query(&format!(
|
||||
"INSERT INTO {} (file_uuid, node_type, external_id, label, properties) VALUES ($1, 'face_track', $2, $3, $4)",
|
||||
tkg_table
|
||||
))
|
||||
.bind(uuid)
|
||||
.bind(&external_id)
|
||||
.bind(&label)
|
||||
.bind(serde_json::json!({"trace_id": trace_id}))
|
||||
.execute(db.pool())
|
||||
.await
|
||||
.context("Failed to insert tkg_nodes")?;
|
||||
}
|
||||
|
||||
// Sync name to trace_profiles DB + on-disk JSON
|
||||
let _ =
|
||||
schema::upsert_trace_profile(db.pool(), uuid, *trace_id as i32, &label, None).await;
|
||||
|
||||
// Update on-disk trace_profile.json
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let profile_path = crate::core::file_profile::FaceTraceProfile::profile_path(
|
||||
output_dir, uuid, *trace_id,
|
||||
);
|
||||
if profile_path.exists() {
|
||||
if let Ok(content) = std::fs::read_to_string(&profile_path) {
|
||||
if let Ok(mut profile) = serde_json::from_str::<serde_json::Value>(&content) {
|
||||
profile["label"] = serde_json::json!(label);
|
||||
let _ = std::fs::write(
|
||||
&profile_path,
|
||||
serde_json::to_string_pretty(&profile).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
{
|
||||
Ok(sync_result) => {
|
||||
tracing::info!(
|
||||
"[FaceCluster] sync_trace_label for trace_{}: tkg={}, tp={}, fs={}, qdrant={} ({} points)",
|
||||
trace_id,
|
||||
sync_result.tkg_nodes_updated,
|
||||
sync_result.trace_profiles_updated,
|
||||
sync_result.fs_updated,
|
||||
sync_result.qdrant_updated,
|
||||
sync_result.qdrant_points_count
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"[FaceCluster] sync_trace_label failed for trace_{}: {}",
|
||||
trace_id,
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user