feat: trace_id i64→i32 fix, OCR search filter, Rule1 OCR trigger

- Fix trace_id SQL type mismatch: i64 → i32 in profile.rs structs and queries
- Add /ocr /asr /asrx search filter suffix to keyword/semantic/smart search
- Fix fetch_ocr_texts to handle both OCR data formats (string array + object array)
- Add has_ocr trigger for Rule1 chunk ingestion in job_worker.rs
- Add search_bm25 chunk_type filter parameter
- Fix single-frame video clip duration (0-frame → 1-frame minimum)
- Re-run Rule1 for 14 files with stuck OCR in pre_chunks
This commit is contained in:
Accusys
2026-07-30 19:34:35 +08:00
parent 5d0c771a2b
commit 85d5e1fe51
20 changed files with 1783 additions and 412 deletions
+43 -25
View File
@@ -1174,6 +1174,12 @@ impl PostgresDb {
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_identity_time ON {}(identity_id, created_at DESC)", history_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_identity_history_not_undone ON {}(identity_id, created_at DESC) WHERE NOT is_undone", history_table)).execute(pool).await?;
// ── Trace Operation History (face group/trace undo) ──
let op_table = schema::table_name("trace_operation_history");
sqlx::query(&format!("CREATE TABLE IF NOT EXISTS {} (id BIGSERIAL PRIMARY KEY, file_uuid VARCHAR(32) NOT NULL, operation VARCHAR(30) NOT NULL, before_snapshot JSONB NOT NULL, after_snapshot JSONB, is_undone BOOLEAN DEFAULT FALSE, undone_at TIMESTAMPTZ, user_id VARCHAR(100), created_at TIMESTAMPTZ DEFAULT NOW())", op_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_file_time ON {}(file_uuid, created_at DESC)", op_table)).execute(pool).await?;
sqlx::query(&format!("CREATE INDEX IF NOT EXISTS idx_trace_op_history_not_undone ON {}(file_uuid, created_at DESC) WHERE NOT is_undone", op_table)).execute(pool).await?;
// ── File Identities (N:N file ↔ identity) ──
sqlx::query("CREATE TABLE IF NOT EXISTS file_identities (id SERIAL PRIMARY KEY, file_uuid VARCHAR(255) NOT NULL, identity_id INTEGER NOT NULL REFERENCES identities(id) ON DELETE CASCADE, confidence DOUBLE PRECISION DEFAULT 1.0, metadata JSONB, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, UNIQUE(file_uuid, identity_id))").execute(pool).await?;
sqlx::query(
@@ -3099,8 +3105,8 @@ impl PostgresDb {
let table = schema::table_name("processor_results");
let ptype = processor_type.as_str();
let id: i32 = sqlx::query_scalar(&format!(
"INSERT INTO {} (job_id, processor_type, processor, uuid, status) \
VALUES ($1, $2, $2, $3, $4) \
"INSERT INTO {} (job_id, processor_type, processor, file_uuid, uuid, status) \
VALUES ($1, $2, $2, $3, $3, $4) \
ON CONFLICT (job_id, processor_type) DO UPDATE SET status = EXCLUDED.status, updated_at = CURRENT_TIMESTAMP \
RETURNING id", table
))
@@ -3433,8 +3439,16 @@ impl PostgresDb {
) -> Result<u64> {
let table = schema::table_name("processor_results");
let s = format!("{:?}", status).to_lowercase();
// Only reset results that have been stuck in 'running' for a while.
// Freshly-started / actively-running results (updated_at within the window)
// are NOT flipped back to 'pending' — this prevents the worker from
// re-queuing work that is actually in flight (e.g. an untracked
// store_traced_faces.py subprocess), which previously caused an
// unbounded re-spawn / OOM spiral.
let r = sqlx::query(&format!(
"UPDATE {} SET status = 'pending', error_message = $1 WHERE status = $2",
"UPDATE {} SET status = 'pending', error_message = $1 \
WHERE status = $2 \
AND updated_at < NOW() - INTERVAL '10 minutes'",
table
))
.bind(reason)
@@ -3486,41 +3500,45 @@ impl PostgresDb {
&self,
query: &str,
file_uuid: Option<&str>,
chunk_type: Option<&str>,
limit: i64,
) -> Result<Vec<Bm25Result>> {
let table = schema::table_name("chunk");
let like = format!("%{}%", query.replace('%', "%%"));
use sqlx::Row;
// Simple LIKE-based matching (no FTS stemming)
// Build WHERE clauses dynamically to handle optional params
let mut clauses = vec!["text_content ILIKE $2".to_string(), "text_content != ''".to_string()];
let mut next_idx = 3;
if file_uuid.is_some() {
next_idx += 1;
clauses.push(format!("file_uuid = ${}", next_idx));
}
if chunk_type.is_some() {
next_idx += 1;
clauses.push(format!("chunk_type = ${}", next_idx));
}
let where_sql = clauses.join(" AND ");
let sql = format!(
"SELECT chunk_id, file_uuid, chunk_type, text_content, start_time, end_time, \
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8))::float8 as score \
FROM {} \
WHERE text_content ILIKE $2 AND text_content != '' \
{}\
WHERE {} \
ORDER BY score DESC \
LIMIT $3",
table,
if file_uuid.is_some() { "AND file_uuid = $4 " } else { "" }
table, where_sql
);
let rows = if let Some(u) = file_uuid {
sqlx::query(&sql)
.bind(query)
.bind(&like)
.bind(limit)
.bind(u)
.fetch_all(&self.pool)
.await?
} else {
sqlx::query(&sql)
.bind(query)
.bind(&like)
.bind(limit)
.fetch_all(&self.pool)
.await?
};
let mut q = sqlx::query(&sql).bind(query).bind(&like).bind(limit);
if let Some(u) = file_uuid {
q = q.bind(u);
}
if let Some(ct) = chunk_type {
q = q.bind(ct);
}
let rows = q.fetch_all(&self.pool).await?;
Ok(rows
.into_iter()
@@ -3548,7 +3566,7 @@ impl PostgresDb {
_vector_weight: f32,
_bm25_weight: f32,
) -> Result<Vec<Bm25Result>> {
self.search_bm25(query, uuid, limit as i64).await
self.search_bm25(query, uuid, None, limit as i64).await
}
pub async fn list_identities(
+50
View File
@@ -913,6 +913,56 @@ impl QdrantDb {
Ok(all_points)
}
/// Scroll ALL points with vectors, for reading face embeddings
pub async fn scroll_all_points_with_vectors(
&self,
collection: &str,
filter: serde_json::Value,
page_size: usize,
) -> Result<Vec<serde_json::Value>> {
let mut all_points = Vec::new();
let mut offset: Option<serde_json::Value> = None;
loop {
let url = format!("{}/collections/{}/points/scroll", self.base_url, collection);
let mut body = serde_json::json!({
"filter": filter,
"limit": page_size,
"with_payload": true,
"with_vector": true,
});
if let Some(ref off) = offset {
body["offset"] = off.clone();
}
let resp = self
.client
.post(&url)
.header("api-key", &self.api_key)
.header("Content-Type", "application/json")
.json(&body)
.send()
.await?;
if !resp.status().is_success() {
anyhow::bail!("Qdrant scroll failed: {}", resp.status());
}
let result: serde_json::Value = resp.json().await?;
let points = result["result"]["points"]
.as_array()
.cloned()
.unwrap_or_default();
let batch_len = points.len();
all_points.extend(points);
if batch_len < page_size {
break;
}
let next_offset = result["result"]["next_page_offset"].clone();
if next_offset.is_null() {
break;
}
offset = Some(next_offset);
}
Ok(all_points)
}
pub async fn count_points(&self, collection: &str, filter: serde_json::Value) -> Result<i64> {
let url = format!("{}/collections/{}/points/count", self.base_url, collection);