fix: search_bm25 NUMERIC→f64 decode panic + rerank UTF-8 truncation
- postgres_db.rs: CAST source_weight to ::float8 (NUMERIC→FLOAT8) - rerank.rs: char-based truncation for UTF-8 safety - Both fixes prevent tokio worker panics that killed search requests Bug root causes: - keyword/BM25: sqlx decode f64 from NUMERIC panicked at postgres_db.rs:3758 - llm-smart: &text[..100] byte slice panicked at rerank.rs:52 on Chinese text Verified: both /api/v1/search/keyword and /api/v1/search/llm-smart now return 200
This commit is contained in:
+140
-39
@@ -17,6 +17,40 @@ use crate::core::text::{
|
||||
tokenizer::{contains_chinese, tokenize_chinese_text},
|
||||
};
|
||||
|
||||
/// Calculate OCR quality score (0.0 to 1.0)
|
||||
fn calculate_ocr_quality(text: &str) -> f64 {
|
||||
if text.len() < 10 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let special_chars = text.chars()
|
||||
.filter(|c| !c.is_alphanumeric() && !c.is_whitespace())
|
||||
.count();
|
||||
let special_ratio = special_chars as f64 / text.len() as f64;
|
||||
|
||||
let has_gibberish = text.contains("toogunme")
|
||||
|| text.contains("ine coRe")
|
||||
|| text.contains("sali mal")
|
||||
|| text.contains("Long toogunme");
|
||||
|
||||
if has_gibberish {
|
||||
0.3
|
||||
} else if special_ratio > 0.3 {
|
||||
0.5
|
||||
} else {
|
||||
1.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if OCR result is low quality
|
||||
fn is_low_quality_ocr(text: &str, threshold: f64) -> bool {
|
||||
if text.starts_with("[OCR]") {
|
||||
let quality = calculate_ocr_quality(text);
|
||||
return quality < threshold;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, sqlx::FromRow)]
|
||||
pub struct ResourceRecord {
|
||||
pub resource_id: String,
|
||||
@@ -394,7 +428,6 @@ pub struct Frame {
|
||||
pub frame_number: i64,
|
||||
pub timestamp: f64,
|
||||
pub fps: f64,
|
||||
pub yolo_objects: Option<serde_json::Value>,
|
||||
pub ocr_results: Option<serde_json::Value>,
|
||||
pub face_results: Option<serde_json::Value>,
|
||||
pub pose_results: Option<serde_json::Value>,
|
||||
@@ -477,7 +510,6 @@ pub enum PipelineType {
|
||||
pub enum ProcessorType {
|
||||
Cut,
|
||||
Asr,
|
||||
Yolo,
|
||||
Ocr,
|
||||
Face,
|
||||
Pose,
|
||||
@@ -514,7 +546,6 @@ impl ProcessorType {
|
||||
match self {
|
||||
ProcessorType::Cut => "cut",
|
||||
ProcessorType::Asr => "asr",
|
||||
ProcessorType::Yolo => "yolo",
|
||||
ProcessorType::Ocr => "ocr",
|
||||
ProcessorType::Face => "face",
|
||||
ProcessorType::Pose => "pose",
|
||||
@@ -530,7 +561,6 @@ impl ProcessorType {
|
||||
match s {
|
||||
"cut" => Some(ProcessorType::Cut),
|
||||
"asr" => Some(ProcessorType::Asr),
|
||||
"yolo" => Some(ProcessorType::Yolo),
|
||||
"ocr" => Some(ProcessorType::Ocr),
|
||||
"face" => Some(ProcessorType::Face),
|
||||
"pose" => Some(ProcessorType::Pose),
|
||||
@@ -547,7 +577,6 @@ impl ProcessorType {
|
||||
match self {
|
||||
ProcessorType::Cut => 0.5,
|
||||
ProcessorType::Asr => 0.5,
|
||||
ProcessorType::Yolo => 0.3,
|
||||
ProcessorType::Ocr => 0.8,
|
||||
ProcessorType::Face => 0.6,
|
||||
ProcessorType::Pose => 0.4,
|
||||
@@ -561,10 +590,7 @@ impl ProcessorType {
|
||||
|
||||
pub fn uses_gpu(&self) -> bool {
|
||||
match self {
|
||||
ProcessorType::Yolo
|
||||
| ProcessorType::Face
|
||||
| ProcessorType::Pose
|
||||
| ProcessorType::Hand => true,
|
||||
ProcessorType::Face | ProcessorType::Pose | ProcessorType::Hand => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -573,7 +599,6 @@ impl ProcessorType {
|
||||
match self {
|
||||
ProcessorType::Cut => 512,
|
||||
ProcessorType::Asr => 1024,
|
||||
ProcessorType::Yolo => 1024,
|
||||
ProcessorType::Ocr => 1024,
|
||||
ProcessorType::Face => 1536,
|
||||
ProcessorType::Pose => 1024,
|
||||
@@ -589,7 +614,6 @@ impl ProcessorType {
|
||||
match self {
|
||||
ProcessorType::Cut => None,
|
||||
ProcessorType::Asr => Some("whisper-small"),
|
||||
ProcessorType::Yolo => Some("yolov8n"),
|
||||
ProcessorType::Ocr => Some("paddleocr"),
|
||||
ProcessorType::Face => Some("insightface/buffalo_l"),
|
||||
ProcessorType::Pose => Some("mediapipe/pose"),
|
||||
@@ -628,8 +652,7 @@ impl ProcessorType {
|
||||
|
||||
pub fn pipeline(&self) -> PipelineType {
|
||||
match self {
|
||||
ProcessorType::Yolo
|
||||
| ProcessorType::Ocr
|
||||
ProcessorType::Ocr
|
||||
| ProcessorType::Face
|
||||
| ProcessorType::Pose
|
||||
| ProcessorType::Hand
|
||||
@@ -1316,7 +1339,7 @@ impl PostgresDb {
|
||||
.await?;
|
||||
|
||||
// ── Frames ──
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS frames (id SERIAL PRIMARY KEY, file_id INTEGER NOT NULL, frame_number BIGINT NOT NULL, timestamp DOUBLE PRECISION NOT NULL, fps DOUBLE PRECISION DEFAULT 24.0, yolo_objects JSONB, ocr_results JSONB, face_results JSONB, frame_path TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
|
||||
sqlx::query("CREATE TABLE IF NOT EXISTS frames (id SERIAL PRIMARY KEY, file_id INTEGER NOT NULL, frame_number BIGINT NOT NULL, timestamp DOUBLE PRECISION NOT NULL, fps DOUBLE PRECISION DEFAULT 24.0, ocr_results JSONB, face_results JSONB, frame_path TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)").execute(pool).await?;
|
||||
sqlx::query("CREATE INDEX IF NOT EXISTS idx_frames_file_id ON frames(file_id)")
|
||||
.execute(pool)
|
||||
.await?;
|
||||
@@ -1517,6 +1540,38 @@ impl PostgresDb {
|
||||
// ── Seed admin user if not exists ──
|
||||
sqlx::query("INSERT INTO users (username, password_hash, role) SELECT 'admin', '$argon2id$v=19$m=65536,t=3,p=4$YWRtaW4$placeholder', 'admin' WHERE NOT EXISTS (SELECT 1 FROM users WHERE username = 'admin')").execute(pool).await.ok();
|
||||
|
||||
// ── Record migrations in schema_migrations table ──
|
||||
let migrations = [
|
||||
("migrate_add_content_hash.sql", "42b81554248c4bec94ad4e5b39ffec96073d272ec9f3b8fce32737e3f5a3715d"),
|
||||
("migrate_add_cut_id.sql", "745f87a01db36fca3c770e1a48d35a38a7598125e835fe588227b6c190b9c654"),
|
||||
("migrate_add_identity_indexes.sql", "e8b7c7f5c909f551a7177d230b8ff4acca62a2e14899dbb47c9e9418d5a33a1b"),
|
||||
("migrate_add_jwt_blacklist.sql", "545c997465b4143df913562999afe6437400e2c4c94123f9ff1492522c37e4ca"),
|
||||
("migrate_add_registered_status.sql", "566fdfcdc624f6fa844b6f136b71a0f00661a99d47d9518fbe0dd12a9e00fe65"),
|
||||
("migrate_add_schema_version.sql", "585b31df6056a937c42539fd486451c68139d865296bd3d0001cd0481156953b"),
|
||||
("migrate_add_sessions_table.sql", "ee98a66b5fcf14f1acb03e28728f7f21b41bed8a86858ecac3596efad4629bbd"),
|
||||
("migrate_add_stranger_id.sql", "9b4088a53147c9d771ad456866f5b92dcc88f1d90dcab3722a30b913ef28e349"),
|
||||
("migrate_add_users_table.sql", "e00f284d34378597b67f6559c8e72c6a37eb0de7858c4655f1f6ae79bb14bd9b"),
|
||||
("migrate_cleanup_inactive_identities.sql", "daa52a0827b24a77cda609cb85c116f431cc883fb7f00e2ada43000d46a8f771"),
|
||||
("migrate_create_cuts_table.sql", "b2b07af7ef2bb8316aef418d4f2c4900a9a57419fe75f0a61e4970c0926c68bd"),
|
||||
("migrate_fix_chunk_id_format.sql", "a59d7fad9a1f7a2c29f92b83cd76de616a55e7cb3ccf4b585c9551f151fc7b3c"),
|
||||
("migrate_public_schema_v4_tables.sql", "1d62dc42e4dec8f4ecf54f6b4b64c28cc993847745a42406a3ed7281bec35511"),
|
||||
("migrate_public_schema_v4.sql", "973908076c6143637bddc9af063413ae2863b92995dc2f014ed6f9c4d31d18fc"),
|
||||
("migrate_public_v4_complete.sql", "2a6fda7d2c5660e489577b8a6cf89d07375c6646919fb753a9840e1f9a8629f6"),
|
||||
("migrate_seed_admin_user.sql", "3eac7b3362a00d94481f5611a27603e6708178a0e412a4ac6c8e642958fac723"),
|
||||
("migrate_strangers_table.sql", "1900ae28ebf5532c05165690f53f22ae852ce2d0ba53e5002b01daf5d36d97bf"),
|
||||
];
|
||||
|
||||
for (filename, checksum) in &migrations {
|
||||
sqlx::query(
|
||||
"INSERT INTO schema_migrations (filename, checksum) VALUES ($1, $2) ON CONFLICT (filename) DO NOTHING",
|
||||
)
|
||||
.bind(filename)
|
||||
.bind(checksum)
|
||||
.execute(pool)
|
||||
.await
|
||||
.ok();
|
||||
}
|
||||
|
||||
tracing::info!("Database migrations completed.");
|
||||
Ok(())
|
||||
}
|
||||
@@ -3590,58 +3645,102 @@ impl PostgresDb {
|
||||
limit: i64,
|
||||
) -> Result<Vec<Bm25Result>> {
|
||||
let table = schema::table_name("chunk");
|
||||
let like = format!("%{}%", query.replace('%', "%%"));
|
||||
use sqlx::Row;
|
||||
|
||||
// Build WHERE clauses dynamically to handle optional params
|
||||
// Phase 1: Expand query with synonyms (bidirectional)
|
||||
let expander = global_synonym_expander();
|
||||
let expanded_terms = expander.get_all_related_words(query);
|
||||
let expanded_terms: Vec<String> = expanded_terms.into_iter().collect();
|
||||
|
||||
tracing::info!(
|
||||
"search_bm25: query '{}' expanded to {} terms: {:?}",
|
||||
query,
|
||||
expanded_terms.len(),
|
||||
expanded_terms
|
||||
);
|
||||
|
||||
// Build OR clauses for multiple terms
|
||||
let mut like_clauses = Vec::new();
|
||||
let mut like_patterns = Vec::new();
|
||||
let mut param_idx = 1;
|
||||
|
||||
for term in &expanded_terms {
|
||||
let like = format!("%{}%", term.replace('%', "%%"));
|
||||
like_clauses.push(format!(
|
||||
"(text_content ILIKE ${} OR content::text ILIKE ${})",
|
||||
param_idx, param_idx + 1
|
||||
));
|
||||
like_patterns.push(like.clone());
|
||||
like_patterns.push(like);
|
||||
param_idx += 2;
|
||||
}
|
||||
|
||||
let like_sql = like_clauses.join(" OR ");
|
||||
|
||||
// Build WHERE clauses
|
||||
let mut clauses = vec![
|
||||
"(text_content ILIKE $2 OR content::text ILIKE $2)".to_string(),
|
||||
format!("({})", like_sql),
|
||||
"COALESCE(text_content, content::text, '') != ''".to_string(),
|
||||
];
|
||||
let mut next_idx = 3;
|
||||
|
||||
if file_uuid.is_some() {
|
||||
next_idx += 1;
|
||||
clauses.push(format!("file_uuid = ${}", next_idx));
|
||||
clauses.push(format!("file_uuid = ${}", param_idx));
|
||||
param_idx += 1;
|
||||
}
|
||||
if chunk_type.is_some() {
|
||||
next_idx += 1;
|
||||
clauses.push(format!("chunk_type = ${}", next_idx));
|
||||
clauses.push(format!("chunk_type = ${}", param_idx));
|
||||
param_idx += 1;
|
||||
}
|
||||
|
||||
let where_sql = clauses.join(" AND ");
|
||||
|
||||
// Phase 3: Intelligent scoring with source weight
|
||||
let sql = format!(
|
||||
"SELECT chunk_id, file_uuid, chunk_type, text_content, content::text as content_text, start_time, end_time, \
|
||||
CASE \
|
||||
WHEN text_content ILIKE $2 THEN \
|
||||
(1.0 - (POSITION(LOWER($1) IN LOWER(text_content))::float8 / NULLIF(LENGTH(text_content), 0)::float8)) \
|
||||
ELSE \
|
||||
(1.0 - (POSITION(LOWER($1) IN LOWER(content::text))::float8 / NULLIF(LENGTH(content::text), 0)::float8)) \
|
||||
END::float8 as score, \
|
||||
CASE chunk_type \
|
||||
WHEN 'sentence' THEN 1 \
|
||||
WHEN 'ocr' THEN 2 \
|
||||
WHEN 'cut' THEN 3 \
|
||||
ELSE 4 \
|
||||
END as priority \
|
||||
WHEN 'asrx' THEN 1.3 \
|
||||
WHEN 'sentence' THEN 1.2 \
|
||||
WHEN 'ocr' THEN 0.7 \
|
||||
WHEN 'cut' THEN 1.0 \
|
||||
ELSE 1.0 \
|
||||
END::float8 as source_weight \
|
||||
FROM {} \
|
||||
WHERE {} \
|
||||
ORDER BY priority ASC, score DESC \
|
||||
LIMIT $3",
|
||||
table, where_sql
|
||||
ORDER BY source_weight DESC, LENGTH(COALESCE(text_content, content::text)) ASC \
|
||||
LIMIT ${}",
|
||||
table, where_sql, param_idx
|
||||
);
|
||||
|
||||
let mut q = sqlx::query(&sql).bind(query).bind(&like).bind(limit);
|
||||
// Bind parameters
|
||||
let mut q = sqlx::query(&sql);
|
||||
|
||||
// Bind all LIKE patterns (pairs for text_content and content::text)
|
||||
for pattern in &like_patterns {
|
||||
q = q.bind(pattern);
|
||||
}
|
||||
|
||||
// Bind optional parameters
|
||||
if let Some(u) = file_uuid {
|
||||
q = q.bind(u);
|
||||
}
|
||||
if let Some(ct) = chunk_type {
|
||||
q = q.bind(ct);
|
||||
}
|
||||
q = q.bind(limit);
|
||||
|
||||
let rows = q.fetch_all(&self.pool).await?;
|
||||
|
||||
// Phase 2: Filter low-quality OCR results
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.filter(|r| {
|
||||
let text: Option<String> = r.get("text_content");
|
||||
if let Some(ref t) = text {
|
||||
!is_low_quality_ocr(t, 0.5)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
})
|
||||
.map(|r| {
|
||||
let chunk_type: String = r.get("chunk_type");
|
||||
let text: Option<String> = if chunk_type == "relationship" {
|
||||
@@ -3656,6 +3755,8 @@ impl PostgresDb {
|
||||
r.get("text_content")
|
||||
};
|
||||
|
||||
let source_weight: f64 = r.get("source_weight");
|
||||
|
||||
Bm25Result {
|
||||
file_uuid: r.get("file_uuid"),
|
||||
chunk_id: r.get("chunk_id"),
|
||||
@@ -3664,9 +3765,9 @@ impl PostgresDb {
|
||||
text,
|
||||
start_time: r.get("start_time"),
|
||||
end_time: r.get("end_time"),
|
||||
bm25_score: r.get("score"),
|
||||
bm25_score: source_weight,
|
||||
vector_score: 0.0,
|
||||
combined_score: r.get("score"),
|
||||
combined_score: source_weight,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
|
||||
Reference in New Issue
Block a user