fix: ASRX duplication, TKG edges, trace ingest, and add pipeline progress publishing

- ASRX handler no longer stores duplicate 'asr' pre_chunks
- Pre_chunks storage made idempotent (delete-before-insert)
- Rule 1 + trace_ingest changed to query 'asrx' not 'asr'
- Trace chunks removed (dynamic from TKG/Qdrant)
- TKG scroll_face_points fixed: trace_id >= 1 (not == 1)
- TKG AsrxSegmentEntry: start/end -> start_time/end_time (match ASRX JSON)
- Unregister error handling: log instead of silent discard
- Add publish_pipeline_progress calls at each pipeline stage
  (processors, rule1, face_trace, identity_agent, TKG, rule2, completion)
This commit is contained in:
Accusys
2026-07-02 10:43:46 +08:00
parent d791d138f2
commit 3eabd45882
65 changed files with 9477 additions and 3852 deletions
+165 -114
View File
@@ -3,7 +3,7 @@ use serde::Deserialize;
use std::collections::HashMap;
use tracing::{error, info, warn};
use crate::core::db::{schema, PostgresDb};
use crate::core::db::{schema, PostgresDb, QdrantDb};
#[derive(Debug, Deserialize)]
struct TmdbIdentity {
@@ -30,41 +30,87 @@ fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
/// Round 1: seed match against TMDb face_embeddings (threshold 0.50)
/// Round 2+: propagate to remaining traces using matched faces as reference
pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Result<usize> {
let pool = db.pool();
let qdrant = QdrantDb::new();
// Step 1: Load TMDb identities with face embeddings
let tmdb_rows = sqlx::query_as::<_, (i32, String, Vec<f32>)>(
&format!("SELECT id, name, face_embedding::real[] FROM {} WHERE source='tmdb' AND face_embedding IS NOT NULL", schema::table_name("identities"))
)
.fetch_all(pool).await?;
// Step 1: Load TMDb identity seeds from Qdrant _seeds collection
let tmdb_filter = serde_json::json!({
"must": [
{"key": "source", "match": {"value": "tmdb"}}
]
});
let seed_points = match qdrant.scroll_all_points("_seeds", tmdb_filter, 500).await {
Ok(pts) => pts,
Err(e) => {
warn!("[TKG-MATCH] Failed to scroll _seeds: {}", e);
return Ok(0);
}
};
let tmdb_rows: Vec<(i32, String, Vec<f32>)> = seed_points
.iter()
.filter_map(|p| {
let payload = &p["payload"];
let id = payload["identity_id"].as_i64()? as i32;
let name = payload["name"].as_str()?.to_string();
let vector = p["vector"]
.as_array()?
.iter()
.filter_map(|v| v.as_f64().map(|f| f as f32))
.collect::<Vec<f32>>();
if vector.len() == 512 {
Some((id, name, vector))
} else {
None
}
})
.collect();
if tmdb_rows.is_empty() {
info!("[TKG-MATCH] No TMDb identities with face embeddings");
info!("[TKG-MATCH] No TMDb identity seeds in _seeds collection");
return Ok(0);
}
info!("[TKG-MATCH] {} TMDb seeds loaded", tmdb_rows.len());
info!("[TKG-MATCH] {} TMDb seeds loaded from _seeds", tmdb_rows.len());
// Step 2: Load face_detections grouped by trace_id
let fd_table = schema::table_name("face_detections");
let fd_rows = sqlx::query_as::<_, (i32, Vec<f32>)>(&format!(
"SELECT trace_id, embedding FROM {} \
WHERE file_uuid=$1 AND trace_id IS NOT NULL AND embedding IS NOT NULL \
ORDER BY trace_id",
fd_table
))
.bind(file_uuid)
.fetch_all(pool)
.await?;
// Step 2: Load face embeddings from Qdrant _faces, grouped by trace_id
let face_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": 1}} // trace_id > 0 means traced
]
});
let face_points = match qdrant.scroll_all_points("_faces", face_filter, 1000).await {
Ok(pts) => pts,
Err(e) => {
warn!("[TKG-MATCH] Failed to scroll _faces for {}: {}", file_uuid, e);
return Ok(0);
}
};
if fd_rows.is_empty() {
info!("[TKG-MATCH] No face detections for {}", file_uuid);
if face_points.is_empty() {
info!("[TKG-MATCH] No traced faces in _faces for {}", file_uuid);
return Ok(0);
}
// Group by trace_id, collect embeddings
let mut trace_faces: HashMap<i32, Vec<Vec<f32>>> = HashMap::new();
for (tid, emb) in &fd_rows {
trace_faces.entry(*tid).or_default().push(emb.clone());
for point in &face_points {
let payload = &point["payload"];
let trace_id = match payload["trace_id"].as_i64() {
Some(tid) if tid > 0 => tid as i32,
_ => continue,
};
let vector = match point["vector"].as_array() {
Some(arr) => arr
.iter()
.filter_map(|v| v.as_f64().map(|f| f as f32))
.collect::<Vec<f32>>(),
None => continue,
};
if vector.len() == 512 {
trace_faces.entry(trace_id).or_default().push(vector);
}
}
// Dedup near-identical embeddings within trace
for faces in trace_faces.values_mut() {
faces.sort_by(|a, b| a[0].partial_cmp(&b[0]).unwrap_or(std::cmp::Ordering::Equal));
@@ -72,7 +118,7 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
}
let total = trace_faces.len();
info!("[TKG-MATCH] {} traces with {} faces", total, fd_rows.len());
info!("[TKG-MATCH] {} traces with {} faces", total, face_points.len());
// Step 3: Iterative matching
const TH: f32 = 0.50;
@@ -100,12 +146,12 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
info!(
"[TKG-MATCH] Round 1: {} ({}/{})",
matched.len(),
matched.len() * 100 / total,
matched.len() * 100 / total.max(1),
total
);
// Round 2+: propagate
for round_n in 2..=10 {
for _round_n in 2..=10 {
let prev = matched.len();
let mut seed_pool: HashMap<i32, Vec<&Vec<f32>>> = HashMap::new();
for (&tid, (id, _)) in &matched {
@@ -133,7 +179,6 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
}
}
if best_sim >= TH {
// Look up name for this id
for (id, name, _) in &tmdb_rows {
if *id == best_id {
best_name = name.clone();
@@ -153,19 +198,16 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
}
// Step 4: Quality control
// 4a: Remove low-confidence traces (fewer than 4 face detections)
let fd_table = schema::table_name("face_detections");
// 4a: Remove low-confidence traces (fewer than 4 face points)
let mut after_qc = HashMap::new();
for (&tid, &(id, ref name)) in &matched {
let cnt: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid=$1 AND trace_id=$2",
fd_table
))
.bind(file_uuid)
.bind(tid)
.fetch_one(pool)
.await
.unwrap_or(0);
let cnt: i64 = face_points
.iter()
.filter(|p| {
p["payload"]["trace_id"].as_i64() == Some(tid as i64)
&& p["payload"]["file_uuid"].as_str() == Some(file_uuid)
})
.count() as i64;
if cnt >= 4 {
after_qc.insert(tid, (id, name.clone()));
} else {
@@ -184,8 +226,8 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
);
}
// 4b: Temporal collision check
let removed_collisions = quality_check_temporal_collisions(pool, file_uuid).await?;
// 4b: Temporal collision check via Qdrant
let removed_collisions = quality_check_temporal_collisions_qdrant(&qdrant, file_uuid).await?;
if removed_collisions > 0 {
info!(
"[TKG-QC] Resolved {} temporal collisions",
@@ -193,19 +235,21 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
);
}
// Step 5: Update DB
// Step 5: Update Qdrant _faces with identity_id
let mut updated = 0usize;
for (&tid, &(id, _)) in &matched {
let r = sqlx::query(&format!(
"UPDATE {} SET identity_id=$1 WHERE file_uuid=$2 AND trace_id=$3",
fd_table
))
.bind(id)
.bind(file_uuid)
.bind(tid)
.execute(pool)
.await?;
if r.rows_affected() > 0 {
let filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": tid}}
]
});
let payload = serde_json::json!({"identity_id": id});
if qdrant
.update_payload_by_filter("_faces", filter, payload)
.await
.is_ok()
{
updated += 1;
}
}
@@ -214,87 +258,94 @@ pub async fn match_faces_against_tmdb(db: &PostgresDb, file_uuid: &str) -> Resul
"[TKG-MATCH] Done: {}/{} traces matched ({}%)",
matched.len(),
total,
matched.len() * 100 / total
matched.len() * 100 / total.max(1)
);
Ok(updated)
}
/// Quality check: detect temporal collisions where two different traces of the same
/// identity appear in the same frame (impossible for one person).
/// Unbind the lower-confidence trace from the conflicting pair.
/// RCA reference: docs_v1.0/API_V1.0.0/INTERNAL/RCA_TRACE39_TRACE45_COLLISION_V1.0.0.md
async fn quality_check_temporal_collisions(pool: &sqlx::PgPool, file_uuid: &str) -> Result<usize> {
let fd_table = schema::table_name("face_detections");
// Find all collision pairs: same identity, same frame, different trace
let collisions = sqlx::query_as::<_, (i32, i32, i32, i64)>(&format!(
"SELECT a.identity_id, a.trace_id, b.trace_id, a.frame_number \
FROM {} a \
JOIN {} b \
ON a.file_uuid = b.file_uuid \
AND a.frame_number = b.frame_number \
AND a.trace_id < b.trace_id \
WHERE a.file_uuid = $1 \
AND a.identity_id IS NOT NULL \
AND a.identity_id = b.identity_id \
ORDER BY a.identity_id, a.frame_number",
fd_table, fd_table
))
.bind(file_uuid)
.fetch_all(pool)
.await?;
/// Unbind the lower-confidence trace from the conflicting pair via Qdrant.
async fn quality_check_temporal_collisions_qdrant(
qdrant: &QdrantDb,
file_uuid: &str,
) -> Result<usize> {
use std::collections::HashSet;
if collisions.is_empty() {
return Ok(0);
// Load all traced faces for this file
let face_filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": 1}}
]
});
let face_points = match qdrant.scroll_all_points("_faces", face_filter, 1000).await {
Ok(pts) => pts,
Err(_) => return Ok(0),
};
// Group by (frame, identity_id) to find collisions
let mut frame_identity_traces: HashMap<(i64, i32), HashSet<i32>> = HashMap::new();
let mut trace_point_counts: HashMap<i32, i64> = HashMap::new();
for point in &face_points {
let payload = &point["payload"];
let frame = payload["frame"].as_i64().unwrap_or(0);
let trace_id = match payload["trace_id"].as_i64() {
Some(tid) if tid > 0 => tid as i32,
_ => continue,
};
let identity_id = match payload["identity_id"].as_i64() {
Some(id) if id > 0 => id as i32,
_ => continue,
};
frame_identity_traces
.entry((frame, identity_id))
.or_default()
.insert(trace_id);
*trace_point_counts.entry(trace_id).or_default() += 1;
}
// Group collisions by (identity_id, trace_a, trace_b) and count frames
use std::collections::HashMap;
// Find collision pairs: (identity_id, trace_a, trace_b)
let mut collision_groups: HashMap<(i32, i32, i32), usize> = HashMap::new();
for (id, ta, tb, _) in &collisions {
*collision_groups.entry((*id, *ta, *tb)).or_default() += 1;
for ((_frame, identity_id), traces) in &frame_identity_traces {
let traces: Vec<i32> = traces.iter().copied().collect();
for i in 0..traces.len() {
for j in (i + 1)..traces.len() {
let (ta, tb) = if traces[i] < traces[j] {
(traces[i], traces[j])
} else {
(traces[j], traces[i])
};
*collision_groups.entry((*identity_id, ta, tb)).or_default() += 1;
}
}
}
if collision_groups.is_empty() {
return Ok(0);
}
let mut unbound = 0usize;
for ((id, ta, tb), overlap_frames) in &collision_groups {
// Get face detection count for each trace
let cnt_a: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid=$1 AND trace_id=$2 AND identity_id=$3",
fd_table
))
.bind(file_uuid)
.bind(ta)
.bind(id)
.fetch_one(pool)
.await
.unwrap_or(0);
let cnt_a = trace_point_counts.get(ta).copied().unwrap_or(0);
let cnt_b = trace_point_counts.get(tb).copied().unwrap_or(0);
let cnt_b: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {} WHERE file_uuid=$1 AND trace_id=$2 AND identity_id=$3",
fd_table
))
.bind(file_uuid)
.bind(tb)
.bind(id)
.fetch_one(pool)
.await
.unwrap_or(0);
// Unbind the trace with fewer detections (likely the false positive)
let victim = if cnt_a <= cnt_b { *ta } else { *tb };
let victim_cnt = if cnt_a <= cnt_b { cnt_a } else { cnt_b };
sqlx::query(&format!(
"UPDATE {} SET identity_id=NULL WHERE file_uuid=$1 AND trace_id=$2",
fd_table
))
.bind(file_uuid)
.bind(victim)
.execute(pool)
.await?;
let filter = serde_json::json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}},
{"key": "trace_id", "match": {"value": victim}}
]
});
let payload = serde_json::json!({"identity_id": serde_json::Value::Null});
let _ = qdrant.update_payload_by_filter("_faces", filter, payload).await;
unbound += 1;
warn!("[TKG-QC] Collision identity={}: trace {} vs trace {} ({} overlap frames). Unbound trace {} ({} detections)",
id, ta, tb, overlap_frames, victim, victim_cnt);
warn!("[TKG-QC] Collision identity={}: trace {} vs trace {} ({} overlap frames). Unbound trace {} ({} points)",
id, ta, tb, overlap_frames, victim, if cnt_a <= cnt_b { cnt_a } else { cnt_b });
}
Ok(unbound)
+2 -3
View File
@@ -45,9 +45,8 @@ fn extract_movie_name(filename: &str) -> Option<String> {
.file_stem()
.and_then(|s| s.to_str())?;
let noise_words = [
"youtube", "yt", "fps", "hd", "full", "movie", "official",
"trailer", "teaser", "4k",
let noise_words = [
"youtube", "yt", "fps", "hd", "full", "movie", "official", "trailer", "teaser", "4k",
];
let cleaned = name