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
+58
View File
@@ -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!(
+1
View File
@@ -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;
+179
View File
@@ -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
View File
@@ -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
);
}
}
}