Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/core/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,9 @@ impl Database {
.unwrap_or(std::cmp::Ordering::Equal)
});

results.truncate(limit * 3); // Get more for reranking
// Use saturating multiplication to prevent overflow
let effective_limit = limit.saturating_mul(3);
results.truncate(effective_limit); // Get more for reranking
Ok(results)
}

Expand Down Expand Up @@ -303,3 +305,30 @@ fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {

(dot / (norm_a.sqrt() * norm_b.sqrt())) as f32
}

#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
use std::panic::AssertUnwindSafe;

#[test]
fn test_search_similar_overflow() {
let dir = tempdir().unwrap();
let db_path = dir.path().join("test.db");
let db = Database::new(&db_path).unwrap();

// Ensure checked_mul/saturating_mul is needed
let huge_limit = (usize::MAX / 3) + 1;
let query_embedding = vec![0.0; 10];
let path = Path::new("/");

// This should NO LONGER panic
let db_ref = AssertUnwindSafe(&db);
let result = std::panic::catch_unwind(move || {
db_ref.search_similar(&query_embedding, path, huge_limit).unwrap();
});

assert!(result.is_ok());
}
}
5 changes: 3 additions & 2 deletions src/core/search.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,11 @@ impl SearchEngine {
// Generate query embedding
let query_embedding = self.embedding_engine.embed(query)?;

// Search for similar chunks
// Search for similar chunks with overflow protection
let limit = max_results.saturating_mul(3);
let candidates = self
.db
.search_similar(&query_embedding, &abs_path, max_results * 3)?;
.search_similar(&query_embedding, &abs_path, limit)?;

if candidates.is_empty() {
return Ok(Vec::new());
Expand Down
Loading