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 = 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 { // 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> = 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::() / 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) }