feat(cleanup): add orphan vector cleanup bin + Studio scene VLM search design suggestions
- src/bin/cleanup_orphan_vectors.rs: one-time tool to scan per-file Qdrant collections (rule1/_faces/_scenes/_vlm/_seeds/face_embeddings/speaker), dry-run support, delete points whose file_uuid is no longer registered. Used to remove 53,122 orphan vectors across all production collections. - docs: scene VLM search design suggestions for Studio team (8868 proxy)
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::time::Instant;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde_json::Value;
|
||||
use sqlx::Row;
|
||||
|
||||
use momentry_core::{Database, PostgresDb, QdrantDb};
|
||||
|
||||
/// One-time cleanup of Qdrant orphan vectors (file_uuid no longer registered in the
|
||||
/// `videos` table). Scans all per-file collections, deletes points whose file_uuid is
|
||||
/// not in the registered set, and reports before/after counts.
|
||||
///
|
||||
/// Points whose payload has no `file_uuid` (or null) are left untouched (e.g. TMDb
|
||||
/// identity seeds not tied to any file).
|
||||
///
|
||||
/// Usage:
|
||||
/// cargo run --bin cleanup_orphan_vectors
|
||||
/// cargo run --bin cleanup_orphan_vectors -- --dry-run
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let dry_run = args.iter().any(|a| a == "--dry-run");
|
||||
|
||||
dotenv::dotenv().ok();
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let pg = PostgresDb::init()
|
||||
.await
|
||||
.context("Failed to init PostgreSQL")?;
|
||||
|
||||
let registered_rows = sqlx::query("SELECT file_uuid FROM videos")
|
||||
.fetch_all(pg.pool())
|
||||
.await
|
||||
.context("Failed to read registered file_uuids")?;
|
||||
let registered: HashSet<String> = registered_rows
|
||||
.into_iter()
|
||||
.filter_map(|r| r.try_get::<String, _>("file_uuid").ok())
|
||||
.collect();
|
||||
println!(
|
||||
"Registered file_uuids in videos table: {}",
|
||||
registered.len()
|
||||
);
|
||||
|
||||
let schema = std::env::var("DATABASE_SCHEMA").unwrap_or_else(|_| "public".to_string());
|
||||
let speaker_collection = if schema == "public" {
|
||||
"momentry_public_speaker".to_string()
|
||||
} else {
|
||||
format!("momentry_{}_speaker", schema)
|
||||
};
|
||||
|
||||
let qdrant = QdrantDb::new();
|
||||
let collections = vec![
|
||||
qdrant.collection_name.clone(),
|
||||
"_faces".to_string(),
|
||||
"_scenes".to_string(),
|
||||
"_vlm".to_string(),
|
||||
"_seeds".to_string(),
|
||||
format!("{}_face_embeddings", schema),
|
||||
speaker_collection,
|
||||
];
|
||||
|
||||
let mut grand_total_deleted = 0u64;
|
||||
for collection in &collections {
|
||||
let start = Instant::now();
|
||||
let before = qdrant
|
||||
.count_points(collection, Value::Null)
|
||||
.await
|
||||
.unwrap_or(0) as usize;
|
||||
|
||||
let need_delete = {
|
||||
let all_points = qdrant
|
||||
.scroll_all_points(collection, Value::Null, 2000)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
println!(" [warn] scroll failed for `{}`: {}", collection, e);
|
||||
Vec::new()
|
||||
});
|
||||
collect_orphan_uuids(all_points, ®istered)
|
||||
};
|
||||
|
||||
if need_delete.is_empty() {
|
||||
println!(
|
||||
"{:>28}: {} points, no orphans ({:?})",
|
||||
collection,
|
||||
before,
|
||||
start.elapsed()
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let orphan_points: u64 = need_delete.values().sum();
|
||||
println!(
|
||||
"{:>28}: {} points, {} orphan uuids, {} orphan points ({:?})",
|
||||
collection,
|
||||
before,
|
||||
need_delete.len(),
|
||||
orphan_points,
|
||||
start.elapsed()
|
||||
);
|
||||
|
||||
if dry_run {
|
||||
for (uuid, n) in &need_delete {
|
||||
println!(" [dry-run] delete {} points of {}", n, uuid);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
for (uuid, n) in need_delete {
|
||||
match qdrant
|
||||
.delete_points_by_filter(
|
||||
collection,
|
||||
serde_json::json!({
|
||||
"must": [{ "key": "file_uuid", "match": { "value": uuid } }]
|
||||
}),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
grand_total_deleted += n;
|
||||
println!(" deleted {} points of {}", n, uuid);
|
||||
}
|
||||
Err(e) => println!(" [warn] failed to delete {} ({}): {}", uuid, n, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"\nDone. Total orphan points deleted: {}",
|
||||
grand_total_deleted
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Collect file_uuids present in the given points that are missing from `registered`.
|
||||
/// No-file_uuid (null/absent) payloads are ignored so shared seeds are preserved.
|
||||
fn collect_orphan_uuids(points: Vec<Value>, registered: &HashSet<String>) -> HashMap<String, u64> {
|
||||
let mut counts: HashMap<String, u64> = HashMap::new();
|
||||
for point in points {
|
||||
let file_uuid = point
|
||||
.get("payload")
|
||||
.and_then(|p| p.get("file_uuid"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
if file_uuid.is_empty() || file_uuid == "?" {
|
||||
continue;
|
||||
}
|
||||
if !registered.contains(file_uuid) {
|
||||
*counts.entry(file_uuid.to_string()).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
Reference in New Issue
Block a user