feat: add backfill_trace_profiles tool + backfill 8250 traces avg_confidence

- Created src/bin/backfill_trace_profiles.rs
- Queries Qdrant _faces once per file (optimized)
- Calculates avg confidence per trace
- Updates trace_profiles.avg_confidence and tkg_nodes.properties
- Backfilled 8250/9877 NULL traces (remaining 102 are edge cases without Qdrant data)
This commit is contained in:
Accusys
2026-08-07 14:26:39 +08:00
parent cd8df324be
commit b52777ac03
2 changed files with 120 additions and 0 deletions
+4
View File
@@ -151,3 +151,7 @@ chrono = "0.4"
[dev-dependencies]
tempfile = "3"
[[bin]]
name = "backfill_trace_profiles"
path = "src/bin/backfill_trace_profiles.rs"
+116
View File
@@ -0,0 +1,116 @@
use anyhow::Result;
use momentry_core::core::config;
use momentry_core::core::db::{qdrant_db::QdrantDb, PostgresDb};
use serde_json::json;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let db = PostgresDb::new(&config::DATABASE_URL).await?;
let qdrant = QdrantDb::new();
// Find all files with traces that have NULL avg_confidence
let files: Vec<String> = sqlx::query_scalar::<_, String>(
r#"
SELECT DISTINCT file_uuid
FROM trace_profiles
WHERE avg_confidence IS NULL
ORDER BY file_uuid
"#,
)
.fetch_all(db.pool())
.await?;
println!("Found {} files to backfill", files.len());
let mut total_updated = 0;
let mut total_errors = 0;
for file_uuid in &files {
match backfill_file(&db, &qdrant, file_uuid).await {
Ok(count) => {
total_updated += count;
println!(" ✅ {} : {} traces updated", file_uuid, count);
}
Err(e) => {
total_errors += 1;
eprintln!(" ❌ {} : {}", file_uuid, e);
}
}
}
println!("\nDone! Total updated: {}, Errors: {}", total_updated, total_errors);
Ok(())
}
async fn backfill_file(db: &PostgresDb, qdrant: &QdrantDb, file_uuid: &str) -> Result<usize> {
// Get all face points for this file from Qdrant
let filter = json!({
"must": [
{"key": "file_uuid", "match": {"value": file_uuid}}
]
});
let points = qdrant.scroll_all_points("_faces", filter, 10000).await?;
if points.is_empty() {
return Ok(0);
}
// Group by trace_id and calculate avg confidence
let mut trace_conf: HashMap<i32, Vec<f64>> = HashMap::new();
for p in &points {
if let Some(tid) = p["payload"]["trace_id"].as_i64() {
if let Some(conf) = p["payload"]["confidence"].as_f64() {
trace_conf.entry(tid as i32).or_default().push(conf);
}
}
}
if trace_conf.is_empty() {
return Ok(0);
}
// Update trace_profiles and tkg_nodes for each trace
let mut updated = 0;
for (trace_id, confs) in &trace_conf {
let avg_conf = confs.iter().sum::<f64>() / confs.len() as f64;
let avg_conf_rounded = (avg_conf * 1000.0).round() / 1000.0;
// Update trace_profiles
sqlx::query(
"UPDATE trace_profiles SET avg_confidence = $1 WHERE file_uuid = $2 AND trace_id = $3",
)
.bind(avg_conf_rounded)
.bind(file_uuid)
.bind(trace_id)
.execute(db.pool())
.await?;
// Update tkg_nodes.properties
sqlx::query(
r#"
UPDATE tkg_nodes
SET properties = jsonb_set(
COALESCE(properties, '{}'::jsonb),
'{avg_confidence}',
to_jsonb($1::double precision)
)
WHERE file_uuid = $2
AND node_type = 'face_track'
AND (properties->>'trace_id')::int = $3
"#,
)
.bind(avg_conf_rounded)
.bind(file_uuid)
.bind(trace_id)
.execute(db.pool())
.await?;
updated += 1;
}
Ok(updated)
}