YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(audio): add cross-device transcription deduplication
Louis Beaumont78b4dc66f318
diff --git a/Cargo.lock b/Cargo.lockindex da31365b7..d01cbff99 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6567,7 +6567,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"[[package]]name = "screenpipe-audio"-version = "0.2.93"+version = "0.2.95"dependencies = ["anyhow","bytemuck",@@ -6620,7 +6620,7 @@ dependencies = [[[package]]name = "screenpipe-core"-version = "0.2.93"+version = "0.2.95"dependencies = ["accessibility","accessibility-sys",@@ -6663,7 +6663,7 @@ dependencies = [[[package]]name = "screenpipe-db"-version = "0.2.93"+version = "0.2.95"dependencies = ["anyhow","chrono",@@ -6687,7 +6687,7 @@ dependencies = [[[package]]name = "screenpipe-events"-version = "0.2.93"+version = "0.2.95"dependencies = ["anyhow","chrono",@@ -6705,7 +6705,7 @@ dependencies = [[[package]]name = "screenpipe-integrations"-version = "0.2.93"+version = "0.2.95"dependencies = ["anyhow","image",@@ -6720,7 +6720,7 @@ dependencies = [[[package]]name = "screenpipe-server"-version = "0.2.93"+version = "0.2.95"dependencies = ["anyhow","axum",@@ -6783,7 +6783,7 @@ dependencies = [[[package]]name = "screenpipe-vision"-version = "0.2.93"+version = "0.2.95"dependencies = ["accessibility-sys","anyhow",diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rsindex c0daaed83..e236cbfb7 100644--- a/screenpipe-db/src/db.rs+++ b/screenpipe-db/src/db.rs@@ -20,12 +20,20 @@ use zerocopy::AsBytes;use futures::future::try_join_all;use crate::{- AudioChunksResponse, AudioDevice, AudioEntry, AudioResult, AudioResultRaw, ContentType,- DeviceType, FrameData, FrameRow, OCREntry, OCRResult, OCRResultRaw, OcrEngine, OcrTextBlock,- Order, SearchMatch, SearchResult, Speaker, TagContentType, TextBounds, TextPosition,- TimeSeriesChunk, UiContent, VideoMetadata,+ text_similarity::is_similar_transcription, AudioChunksResponse, AudioDevice, AudioEntry,+ AudioResult, AudioResultRaw, ContentType, DeviceType, FrameData, FrameRow, OCREntry, OCRResult,+ OCRResultRaw, OcrEngine, OcrTextBlock, Order, SearchMatch, SearchResult, Speaker,+ TagContentType, TextBounds, TextPosition, TimeSeriesChunk, UiContent, VideoMetadata,};+/// Time window (in seconds) to check for similar transcriptions across devices.+/// Transcriptions within this window are checked for cross-device duplicates.+const DEDUP_TIME_WINDOW_SECS: i64 = 45;++/// Similarity threshold for cross-device deduplication (0.0 to 1.0).+/// Higher = stricter matching, lower = more aggressive deduplication.+const DEDUP_SIMILARITY_THRESHOLD: f64 = 0.85;+pub struct DatabaseManager {pub pool: SqlitePool,}@@ -143,11 +151,32 @@ impl DatabaseManager {start_time: Option<f64>,end_time: Option<f64>,) -> Result<i64, sqlx::Error> {+ // Skip empty transcriptions+ let trimmed = transcription.trim();+ if trimmed.is_empty() {+ return Ok(0);+ }++ // CROSS-DEVICE DEDUPLICATION CHECK+ // Check if similar transcription exists in the last N seconds from ANY device.+ // This prevents the same audio content from being stored twice when captured+ // by both system output and microphone.+ if self+ .has_similar_recent_transcription(trimmed, DEDUP_TIME_WINDOW_SECS)+ .await?+ {+ debug!(+ "Skipping duplicate transcription (cross-device): {:?}",+ &trimmed[..trimmed.len().min(50)]+ );+ return Ok(0);+ }+let text_length = transcription.len() as i64;let mut tx = self.pool.begin().await?;// Insert the transcription, ignoring duplicates (same audio_chunk_id + transcription)- // This prevents duplicates from VAD segment overlap issues+ // This prevents duplicates from VAD segment overlap issues within the same devicelet result = sqlx::query("INSERT OR IGNORE INTO audio_transcriptions (audio_chunk_id, transcription, offset_index, timestamp, transcription_engine, device, is_input_device, speaker_id, start_time, end_time, text_length) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",)@@ -178,6 +207,34 @@ impl DatabaseManager {}}+ /// Check if a similar transcription exists in the recent time window.+ /// Used for cross-device deduplication.+ async fn has_similar_recent_transcription(+ &self,+ transcription: &str,+ time_window_secs: i64,+ ) -> Result<bool, sqlx::Error> {+ // Fetch recent transcriptions from ALL devices+ let recent: Vec<(String,)> = sqlx::query_as(+ "SELECT transcription FROM audio_transcriptions+ WHERE timestamp > datetime('now', ?1)+ ORDER BY timestamp DESC+ LIMIT 50",+ )+ .bind(format!("-{} seconds", time_window_secs))+ .fetch_all(&self.pool)+ .await?;++ // Check similarity against each recent transcription+ for (existing,) in recent {+ if is_similar_transcription(transcription, &existing, DEDUP_SIMILARITY_THRESHOLD) {+ return Ok(true);+ }+ }++ Ok(false)+ }+pub async fn update_audio_transcription(&self,audio_chunk_id: i64,diff --git a/screenpipe-db/src/lib.rs b/screenpipe-db/src/lib.rsindex b63b4c355..8fcfba830 100644--- a/screenpipe-db/src/lib.rs+++ b/screenpipe-db/src/lib.rs@@ -1,6 +1,7 @@mod db;mod migration_worker;pub mod text_normalizer;+pub mod text_similarity;mod types;mod video_db;diff --git a/screenpipe-db/src/text_similarity.rs b/screenpipe-db/src/text_similarity.rsnew file mode 100644index 000000000..4f6e063ec--- /dev/null+++ b/screenpipe-db/src/text_similarity.rs@@ -0,0 +1,319 @@+/// Text similarity utilities for cross-device audio transcription deduplication.+///+/// The core problem: The same audio content can be captured by multiple devices+/// (e.g., system output AND microphone picking up speakers). Each device transcribes+/// independently, resulting in duplicate entries with slightly different text.+///+/// This module provides similarity functions to detect these cross-device duplicates.++use std::collections::HashSet;++/// Calculate word-level Jaccard similarity between two strings.+/// Returns a value between 0.0 (no overlap) and 1.0 (identical word sets).+///+/// The algorithm:+/// 1. Normalize both strings (lowercase, remove punctuation)+/// 2. Split into word sets+/// 3. Calculate |intersection| / |union|+pub fn word_jaccard_similarity(s1: &str, s2: &str) -> f64 {+ let words1 = normalize_to_words(s1);+ let words2 = normalize_to_words(s2);++ if words1.is_empty() && words2.is_empty() {+ return 1.0; // Both empty = identical+ }+ if words1.is_empty() || words2.is_empty() {+ return 0.0; // One empty, one not = no similarity+ }++ let set1: HashSet<_> = words1.iter().collect();+ let set2: HashSet<_> = words2.iter().collect();++ let intersection = set1.intersection(&set2).count();+ let union = set1.union(&set2).count();++ if union == 0 {+ return 0.0;+ }++ intersection as f64 / union as f64+}++/// Check if s2 contains s1 as a substring (word-level).+/// This catches cases where a short transcription is fully contained in a longer one.+/// Returns the fraction of s1's words that appear in s2.+pub fn containment_similarity(shorter: &str, longer: &str) -> f64 {+ let words_short = normalize_to_words(shorter);+ let words_long = normalize_to_words(longer);++ if words_short.is_empty() {+ return 1.0; // Empty string is "contained" in anything+ }+ if words_long.is_empty() {+ return 0.0;+ }++ let set_long: HashSet<_> = words_long.iter().collect();+ let contained = words_short+ .iter()+ .filter(|w| set_long.contains(w))+ .count();++ contained as f64 / words_short.len() as f64+}++/// Combined similarity check: returns true if texts are "similar enough" to be duplicates.+///+/// Uses both Jaccard similarity AND containment check because:+/// - Jaccard catches "mostly the same text with minor variations"+/// - Containment catches "short segment fully contained in longer transcription"+pub fn is_similar_transcription(s1: &str, s2: &str, threshold: f64) -> bool {+ // Skip very short strings (likely noise like "So", "like", "um")+ let words1 = normalize_to_words(s1);+ let words2 = normalize_to_words(s2);++ // Don't deduplicate very short phrases - they're often false positives+ // (common words that appear in unrelated conversations)+ if words1.len() < 4 && words2.len() < 4 {+ // For very short strings, require exact match (after normalization)+ return words1 == words2;+ }++ let jaccard = word_jaccard_similarity(s1, s2);+ if jaccard >= threshold {+ return true;+ }++ // Check containment in both directions+ let (shorter, longer) = if words1.len() <= words2.len() {+ (s1, s2)+ } else {+ (s2, s1)+ };++ // Only use containment if the shorter string has enough words to be meaningful+ let shorter_words = normalize_to_words(shorter);+ if shorter_words.len() >= 4 {+ let containment = containment_similarity(shorter, longer);+ if containment >= threshold {+ return true;+ }+ }++ false+}++/// Normalize text and split into words for comparison.+fn normalize_to_words(s: &str) -> Vec<String> {+ s.to_lowercase()+ .chars()+ .filter(|c| c.is_alphanumeric() || c.is_whitespace())+ .collect::<String>()+ .split_whitespace()+ .map(|s| s.to_string())+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ // ==================== UNIT TESTS FOR SIMILARITY FUNCTIONS ====================++ #[test]+ fn test_jaccard_exact_match() {+ assert_eq!(+ word_jaccard_similarity("hello world", "hello world"),+ 1.0+ );+ }++ #[test]+ fn test_jaccard_case_insensitive() {+ assert_eq!(+ word_jaccard_similarity("Hello World", "hello world"),+ 1.0+ );+ }++ #[test]+ fn test_jaccard_punctuation_ignored() {+ assert_eq!(+ word_jaccard_similarity("Hello, world!", "hello world"),+ 1.0+ );+ }++ #[test]+ fn test_jaccard_partial_overlap() {+ // "hello world" vs "hello there" = intersection {hello}, union {hello, world, there}+ // = 1/3 ≈ 0.333+ let sim = word_jaccard_similarity("hello world", "hello there");+ assert!((sim - 0.333).abs() < 0.01);+ }++ #[test]+ fn test_jaccard_no_overlap() {+ assert_eq!(word_jaccard_similarity("hello world", "goodbye moon"), 0.0);+ }++ #[test]+ fn test_jaccard_empty_strings() {+ assert_eq!(word_jaccard_similarity("", ""), 1.0);+ assert_eq!(word_jaccard_similarity("hello", ""), 0.0);+ assert_eq!(word_jaccard_similarity("", "hello"), 0.0);+ }++ #[test]+ fn test_containment_full() {+ // "beautiful typography" is fully contained in longer string+ assert_eq!(+ containment_similarity(+ "beautiful typography",+ "it was the first computer with beautiful typography"+ ),+ 1.0+ );+ }++ #[test]+ fn test_containment_partial() {+ // 2 of 3 words contained+ let sim = containment_similarity("hello world friend", "hello world enemy");+ assert!((sim - 0.666).abs() < 0.01);+ }++ // ==================== PRODUCTION REGRESSION TESTS ====================+ // These test cases are taken directly from the production logs that showed duplicates++ #[test]+ fn test_production_case_beautiful_typography() {+ // From production logs:+ // Display 4 (output): "It was the first computer with beautiful typography."+ // MacBook Pro Microphone: "...And we designed it all into the Mac. It was the first computer with beautiful typography."++ let short = "It was the first computer with beautiful typography.";+ let long = "in a way that science can't capture. And I found it fascinating. None of this had even a hope of any practical application in my life. But 10 years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography.";++ assert!(+ is_similar_transcription(short, long, 0.85),+ "Should detect short transcription contained in longer one"+ );+ }++ #[test]+ fn test_production_case_bicycle_for_mind() {+ // From production logs - same content captured by both devices+ let s1 = "A bicycle for the mind. That was the original vision.";+ let s2 = "the mind. That was the original vision.";++ assert!(+ is_similar_transcription(s1, s2, 0.85),+ "Should detect overlapping transcriptions"+ );+ }++ #[test]+ fn test_production_case_dots_looking_forward() {+ // Almost identical transcriptions from different devices+ let output_device = "You can't connect the dots looking forward. You can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something, your gut, destiny, life, karma, whatever, because believing that the dots will connect down the road will give you the confidence to follow your heart even when it leads you off the well-worn path, and that will make all the difference.";+ let input_device = "You can't connect the dots looking forward. You can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something, your gut, destiny, life, karma, whatever. Because believing that the dots will connect down the road will give you the confidence to follow your heart even when it leads you off the well-worn path. And that will make all the difference.";++ let sim = word_jaccard_similarity(output_device, input_device);+ assert!(+ sim > 0.95,+ "Nearly identical transcriptions should have very high similarity: {}",+ sim+ );+ assert!(is_similar_transcription(output_device, input_device, 0.85));+ }++ #[test]+ fn test_production_case_single_course_college() {+ // Partial overlap case from production+ let s1 = "the first computer with beautiful typography.";+ let s2 = "If I had never dropped in on that single course in college,";++ assert!(+ !is_similar_transcription(s1, s2, 0.85),+ "Different content should NOT be marked as duplicate"+ );+ }++ // ==================== EDGE CASES ====================++ #[test]+ fn test_short_phrases_exact_match_deduplicated() {+ // Very short phrases that are EXACTLY the same should be deduplicated+ // (they're genuine duplicates from cross-device capture)+ assert!(+ is_similar_transcription("So like", "So like", 0.85),+ "Exact short phrases should be deduplicated"+ );+ assert!(+ is_similar_transcription("Yeah okay", "Yeah okay", 0.85),+ "Exact 2-word phrases should be deduplicated"+ );+ }++ #[test]+ fn test_short_phrases_different_not_deduplicated() {+ // Very short phrases that are DIFFERENT should NOT be deduplicated+ // (short strings are too common to use fuzzy matching)+ assert!(+ !is_similar_transcription("So like", "So yeah", 0.85),+ "Different short phrases should NOT match"+ );+ assert!(+ !is_similar_transcription("Yes", "No", 0.85),+ "Single different words should NOT match"+ );+ }++ #[test]+ fn test_minimum_meaningful_length() {+ // 4+ words should be deduplicated if similar+ assert!(is_similar_transcription(+ "the first computer ever",+ "the first computer ever",+ 0.85+ ));+ }++ #[test]+ fn test_completely_different_content() {+ let s1 = "The quick brown fox jumps over the lazy dog";+ let s2 = "Python is a programming language used for web development";++ assert!(+ !is_similar_transcription(s1, s2, 0.85),+ "Completely different content should not match"+ );+ }++ #[test]+ fn test_whisper_transcription_variations() {+ // Whisper sometimes adds/removes leading spaces, changes punctuation+ let s1 = " It was the first computer with beautiful typography.";+ let s2 = "It was the first computer with beautiful typography";++ assert!(is_similar_transcription(s1, s2, 0.85));+ }++ #[test]+ fn test_threshold_boundary() {+ // Test around the threshold boundary+ // "a b c d" vs "a b c e" = intersection {a,b,c}, union {a,b,c,d,e} = 3/5 = 0.6+ let s1 = "word1 word2 word3 word4";+ let s2 = "word1 word2 word3 word5";++ assert!(+ !is_similar_transcription(s1, s2, 0.85),+ "60% similarity should not pass 85% threshold"+ );+ assert!(+ is_similar_transcription(s1, s2, 0.5),+ "60% similarity should pass 50% threshold"+ );+ }+}diff --git a/screenpipe-db/tests/audio_duplicate_test.rs b/screenpipe-db/tests/audio_duplicate_test.rsindex 442012ee3..d8d964e2a 100644--- a/screenpipe-db/tests/audio_duplicate_test.rs+++ b/screenpipe-db/tests/audio_duplicate_test.rs@@ -1,7 +1,8 @@-/// Audio Transcription Duplicate Prevention Test+/// Audio Transcription Deduplication Tests///-/// This test verifies that the UNIQUE constraint on (audio_chunk_id, transcription)-/// prevents duplicate audio transcriptions from being inserted.+/// This test suite verifies BOTH types of deduplication:+/// 1. Same-chunk duplicates (UNIQUE constraint on audio_chunk_id + transcription)+/// 2. Cross-device duplicates (similarity check across all devices)////// Run with: cargo test --package screenpipe-db --test audio_duplicate_test -- --nocapture@@ -23,393 +24,584 @@ mod tests {db}- /// Verify the UNIQUE constraint exists after migration+ fn output_device() -> AudioDevice {+ AudioDevice {+ name: "Display 4 (output)".to_string(),+ device_type: DeviceType::Output,+ }+ }++ fn input_device() -> AudioDevice {+ AudioDevice {+ name: "MacBook Pro Microphone (input)".to_string(),+ device_type: DeviceType::Input,+ }+ }++ // ===========================================================================+ // CROSS-DEVICE DEDUPLICATION TESTS (The main bug we're fixing)+ // ===========================================================================++ /// THE CRITICAL TEST: Same content captured by different devices should be deduplicated.+ /// This is the exact scenario from production logs.#[tokio::test]- async fn test_unique_constraint_exists() {+ async fn test_cross_device_exact_same_content() {let db = setup_test_db().await;- // Check that the index exists- let index_exists: (i64,) = sqlx::query_as(- "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_audio_transcription_chunk_text'"- )- .fetch_one(&db.pool)- .await- .unwrap();-- assert_eq!(index_exists.0, 1, "UNIQUE index should exist after migration");- println!("✓ UNIQUE constraint idx_audio_transcription_chunk_text exists");+ // Simulate system output capturing "It was the first computer with beautiful typography."+ let chunk_output = db.insert_audio_chunk("output_audio.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk_output,+ "It was the first computer with beautiful typography.",+ 0,+ "whisper",+ &output_device(),+ None,+ Some(0.0),+ Some(3.0),+ )+ .await+ .unwrap();+ assert!(id1 > 0, "First insert should succeed");++ // Simulate microphone picking up the SAME content (different chunk, different device)+ let chunk_input = db.insert_audio_chunk("input_audio.mp4").await.unwrap();+ let id2 = db+ .insert_audio_transcription(+ chunk_input, // Different chunk!+ "It was the first computer with beautiful typography.", // Same text+ 0,+ "whisper",+ &input_device(), // Different device!+ None,+ Some(0.0),+ Some(3.0),+ )+ .await+ .unwrap();++ assert_eq!(+ id2, 0,+ "Cross-device duplicate should be rejected (returned 0)"+ );+ println!("✓ Cross-device exact duplicate was correctly rejected");}- /// Test that INSERT OR IGNORE prevents exact duplicates+ /// Test the production case: short transcription contained in longer one from different device#[tokio::test]- async fn test_duplicate_insert_is_ignored() {+ async fn test_cross_device_short_contained_in_long() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-- let chunk_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();-- // First insert should succeed and return a valid id- let id1 = db.insert_audio_transcription(- chunk_id,- "So like if",- 0,- "whisper",- &device,- Some(1),- Some(0.0),- Some(2.5),- ).await.unwrap();-- assert!(id1 > 0, "First insert should return valid id");- println!("✓ First insert returned id: {}", id1);-- // Second insert with SAME chunk_id and transcription should be ignored- let id2 = db.insert_audio_transcription(- chunk_id,- "So like if", // Same text- 0,- "whisper",- &device,- Some(1),- Some(5.0), // Different time - doesn't matter- Some(7.5),- ).await.unwrap();-- // INSERT OR IGNORE returns 0 when the insert is ignored- assert_eq!(id2, 0, "Duplicate insert should return 0 (ignored)");- println!("✓ Duplicate insert returned 0 (correctly ignored)");-- // Verify only one row exists- let count = db.count_audio_transcriptions(chunk_id).await.unwrap();- assert_eq!(count, 1, "Should have exactly 1 transcription, not 2");- println!("✓ Only 1 row in database (duplicate was prevented)");+ // Output device captures short segment+ let chunk1 = db.insert_audio_chunk("output.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk1,+ "the first computer with beautiful typography.",+ 0,+ "whisper",+ &output_device(),+ None,+ Some(24.0),+ Some(27.0),+ )+ .await+ .unwrap();+ assert!(id1 > 0);++ // Input device captures longer segment containing the same content+ let chunk2 = db.insert_audio_chunk("input.mp4").await.unwrap();+ let id2 = db+ .insert_audio_transcription(+ chunk2,+ "in a way that science can't capture. And I found it fascinating. It was the first computer with beautiful typography.",+ 0,+ "whisper",+ &input_device(),+ None,+ Some(0.0),+ Some(30.0),+ )+ .await+ .unwrap();++ assert_eq!(+ id2, 0,+ "Transcription containing duplicate content should be rejected"+ );+ println!("✓ Short-in-long cross-device duplicate was correctly rejected");}- /// Test that different transcriptions for the same chunk are allowed+ /// Test the production case: nearly identical transcriptions with minor Whisper variations#[tokio::test]- async fn test_different_transcriptions_same_chunk_allowed() {+ async fn test_cross_device_whisper_variations() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-- let chunk_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();-- // Insert first transcription- let id1 = db.insert_audio_transcription(- chunk_id,- "Hello world",- 0,- "whisper",- &device,- Some(1),- Some(0.0),- Some(2.5),- ).await.unwrap();+ // Output device transcription+ let chunk1 = db.insert_audio_chunk("output.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk1,+ "You can't connect the dots looking forward. You can only connect them looking backwards.",+ 0,+ "whisper",+ &output_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();assert!(id1 > 0);- // Insert DIFFERENT transcription for same chunk - should succeed- let id2 = db.insert_audio_transcription(- chunk_id,- "Goodbye world", // Different text- 0,- "whisper",- &device,- Some(1),- Some(2.5),- Some(5.0),- ).await.unwrap();- assert!(id2 > 0);- assert_ne!(id1, id2);+ // Input device captures same audio with minor variation (comma vs period, etc)+ let chunk2 = db.insert_audio_chunk("input.mp4").await.unwrap();+ let id2 = db+ .insert_audio_transcription(+ chunk2,+ "You can't connect the dots looking forward, you can only connect them looking backwards.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();++ assert_eq!(+ id2, 0,+ "Near-identical transcription with punctuation differences should be rejected"+ );+ println!("✓ Whisper variation cross-device duplicate was correctly rejected");+ }- let count = db.count_audio_transcriptions(chunk_id).await.unwrap();- assert_eq!(count, 2, "Different transcriptions should both be inserted");- println!("✓ Different transcriptions for same chunk are allowed (count: {})", count);+ /// REGRESSION TEST: Exact scenario from production logs that caused the bug+ #[tokio::test]+ async fn test_regression_production_logs_scenario() {+ let db = setup_test_db().await;++ // From production logs at 14:17:22 - Display 4 (output)+ let chunk1 = db.insert_audio_chunk("output_14_17.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk1,+ " It was the first computer with beautiful typography.",+ 0,+ "whisper",+ &AudioDevice {+ name: "Display 4 (output)".to_string(),+ device_type: DeviceType::Output,+ },+ None,+ None,+ None,+ )+ .await+ .unwrap();+ assert!(id1 > 0, "First transcription should be inserted");++ // From production logs at 14:17:54 - MacBook Pro Microphone (input)+ // Contains the same phrase in a longer transcription+ let chunk2 = db.insert_audio_chunk("input_14_17.mp4").await.unwrap();+ let id2 = db+ .insert_audio_transcription(+ chunk2,+ " in a way that science can't capture. And I found it fascinating. None of this had even a hope of any practical application in my life. But 10 years later, when we were designing the first Macintosh computer, it all came back to me. And we designed it all into the Mac. It was the first computer with beautiful typography.",+ 0,+ "whisper",+ &AudioDevice {+ name: "MacBook Pro Microphone (input)".to_string(),+ device_type: DeviceType::Input,+ },+ None,+ None,+ None,+ )+ .await+ .unwrap();++ // This MUST be rejected - it was the exact bug+ assert_eq!(+ id2, 0,+ "REGRESSION: This is the exact production bug - must be rejected"+ );+ println!("✓ REGRESSION TEST PASSED: Production duplicate scenario is now fixed");}- /// Test that same transcription in different chunks is allowed+ /// Test that legitimately different content from different devices is allowed#[tokio::test]- async fn test_same_transcription_different_chunks_allowed() {+ async fn test_cross_device_different_content_allowed() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-- let chunk_id_1 = db.insert_audio_chunk("audio_1.mp4").await.unwrap();- let chunk_id_2 = db.insert_audio_chunk("audio_2.mp4").await.unwrap();-- // Insert same transcription in different chunks - both should succeed- let id1 = db.insert_audio_transcription(- chunk_id_1,- "Thank you",- 0,- "whisper",- &device,- None,- None,- None,- ).await.unwrap();+ // Output device says one thing+ let chunk1 = db.insert_audio_chunk("output.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk1,+ "The quick brown fox jumps over the lazy dog.",+ 0,+ "whisper",+ &output_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();assert!(id1 > 0);- let id2 = db.insert_audio_transcription(- chunk_id_2,- "Thank you", // Same text, different chunk- 0,- "whisper",- &device,- None,- None,- None,- ).await.unwrap();- assert!(id2 > 0);+ // Input device says completely different thing+ let chunk2 = db.insert_audio_chunk("input.mp4").await.unwrap();+ let id2 = db+ .insert_audio_transcription(+ chunk2,+ "Python is a programming language used for web development.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();++ assert!(+ id2 > 0,+ "Different content from different devices should be allowed"+ );+ println!("✓ Different content across devices was correctly allowed");+ }++ // ===========================================================================+ // SAME-CHUNK DEDUPLICATION TESTS (Original functionality - must still work)+ // ===========================================================================++ /// Verify the UNIQUE constraint exists after migration+ #[tokio::test]+ async fn test_unique_constraint_exists() {+ let db = setup_test_db().await;++ let index_exists: (i64,) = sqlx::query_as(+ "SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name='idx_audio_transcription_chunk_text'",+ )+ .fetch_one(&db.pool)+ .await+ .unwrap();- println!("✓ Same transcription in different chunks is allowed (ids: {}, {})", id1, id2);+ assert_eq!(+ index_exists.0, 1,+ "UNIQUE index should exist after migration"+ );+ println!("✓ UNIQUE constraint idx_audio_transcription_chunk_text exists");}- /// Test the production scenario that was causing duplicates+ /// Test that INSERT OR IGNORE prevents exact duplicates within same chunk#[tokio::test]- async fn test_production_duplicate_scenario_prevented() {+ async fn test_same_chunk_duplicate_prevented() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-- // Simulate the production bug:- // audio_chunk_id 9994 had two records with transcription "So like if"- // at different time ranges (21.56-29.54 and 29.86-31.97)- let chunk_id = db.insert_audio_chunk("production_audio.mp4").await.unwrap();-- // First VAD segment produces "So like if"- let id1 = db.insert_audio_transcription(- chunk_id,- "So like if",- 0,- "whisper",- &device,- Some(1),- Some(21.56),- Some(29.54),- ).await.unwrap();+ let chunk_id = db.insert_audio_chunk("test.mp4").await.unwrap();++ // First insert+ let id1 = db+ .insert_audio_transcription(+ chunk_id,+ "Hello world this is a test transcription.",+ 0,+ "whisper",+ &input_device(),+ None,+ Some(0.0),+ Some(2.5),+ )+ .await+ .unwrap();assert!(id1 > 0);- // Second VAD segment (due to overlap) also produces "So like if"- // This should now be IGNORED- let id2 = db.insert_audio_transcription(- chunk_id,- "So like if",- 0,- "whisper",- &device,- Some(1),- Some(29.86),- Some(31.97),- ).await.unwrap();- assert_eq!(id2, 0, "Duplicate should be ignored");-- // Verify only one row+ // Same chunk, same text - should be rejected+ let id2 = db+ .insert_audio_transcription(+ chunk_id,+ "Hello world this is a test transcription.",+ 0,+ "whisper",+ &input_device(),+ None,+ Some(5.0),+ Some(7.5),+ )+ .await+ .unwrap();+ assert_eq!(id2, 0, "Same-chunk duplicate should be rejected");+let count = db.count_audio_transcriptions(chunk_id).await.unwrap();assert_eq!(count, 1);-- println!("✓ Production duplicate scenario is now PREVENTED");- println!(" - First 'So like if' inserted with id {}", id1);- println!(" - Second 'So like if' was ignored (returned 0)");- println!(" - Total count: {} (was 2 before fix)", count);+ println!("✓ Same-chunk duplicate was correctly rejected");}- /// Test multiple rapid duplicate attempts (simulating race conditions)+ /// Test that different transcriptions for the same chunk are allowed#[tokio::test]- async fn test_rapid_duplicate_attempts() {+ async fn test_different_transcriptions_same_chunk_allowed() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-let chunk_id = db.insert_audio_chunk("test.mp4").await.unwrap();- // Try to insert the same transcription 10 times rapidly- let mut successful_inserts = 0;- for i in 0..10 {- let id = db.insert_audio_transcription(+ let id1 = db+ .insert_audio_transcription(chunk_id,- "Repeated phrase",+ "First segment of the conversation about technology.",0,"whisper",- &device,+ &input_device(),None,- Some(i as f64),- Some((i + 1) as f64),- ).await.unwrap();-- if id > 0 {- successful_inserts += 1;- }- }+ Some(0.0),+ Some(5.0),+ )+ .await+ .unwrap();+ assert!(id1 > 0);- assert_eq!(successful_inserts, 1, "Only first insert should succeed");+ let id2 = db+ .insert_audio_transcription(+ chunk_id,+ "Second completely different segment about cooking recipes.",+ 0,+ "whisper",+ &input_device(),+ None,+ Some(5.0),+ Some(10.0),+ )+ .await+ .unwrap();+ assert!(id2 > 0);let count = db.count_audio_transcriptions(chunk_id).await.unwrap();- assert_eq!(count, 1, "Should have exactly 1 row despite 10 attempts");-- println!("✓ 10 rapid duplicate attempts resulted in only 1 row");+ assert_eq!(count, 2);+ println!("✓ Different transcriptions for same chunk are allowed");}- /// Test that the deduplication SQL logic works correctly- /// This verifies the migration's DELETE logic keeps the first row (lowest id)+ // ===========================================================================+ // EDGE CASES+ // ===========================================================================++ /// Very short common phrases should NOT be aggressively deduplicated+ /// (they appear naturally in different conversations)#[tokio::test]- async fn test_migration_deduplication_logic() {+ async fn test_short_phrases_handled_correctly() {let db = setup_test_db().await;- // First, drop the unique index so we can insert duplicates for testing- sqlx::query("DROP INDEX IF EXISTS idx_audio_transcription_chunk_text")- .execute(&db.pool).await.unwrap();+ // Short phrase from device 1+ let chunk1 = db.insert_audio_chunk("output.mp4").await.unwrap();+ let id1 = db+ .insert_audio_transcription(+ chunk1, "Yeah", 0, "whisper", &output_device(), None, None, None,+ )+ .await+ .unwrap();- // Insert a chunk- let chunk_id = sqlx::query("INSERT INTO audio_chunks (file_path) VALUES ('test.mp4')")- .execute(&db.pool).await.unwrap()- .last_insert_rowid();+ // Note: Very short phrases (< 4 words) are handled specially+ // They should either both be inserted OR both rejected depending on threshold+ // The key is consistency - not breaking on edge cases- // Insert 3 duplicate transcriptions with different ids- for i in 0..3 {- sqlx::query(- "INSERT INTO audio_transcriptions (audio_chunk_id, transcription, offset_index, timestamp, start_time, end_time)- VALUES (?, 'Duplicate text', 0, datetime('now'), ?, ?)"+ let chunk2 = db.insert_audio_chunk("input.mp4").await.unwrap();+ let _id2 = db+ .insert_audio_transcription(+ chunk2, "Yeah", 0, "whisper", &input_device(), None, None, None,)- .bind(chunk_id)- .bind(i as f64)- .bind((i + 1) as f64)- .execute(&db.pool).await.unwrap();- }+ .await+ .unwrap();- // Verify we have 3 rows- let count_before: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM audio_transcriptions WHERE audio_chunk_id = ?")- .bind(chunk_id)- .fetch_one(&db.pool).await.unwrap();- assert_eq!(count_before.0, 3);- println!("Before deduplication: {} rows", count_before.0);-- // Get the ids before dedup- let ids_before: Vec<(i64,)> = sqlx::query_as("SELECT id FROM audio_transcriptions WHERE audio_chunk_id = ? ORDER BY id")- .bind(chunk_id)- .fetch_all(&db.pool).await.unwrap();- let first_id = ids_before[0].0;- println!("IDs before dedup: {:?}", ids_before.iter().map(|r| r.0).collect::<Vec<_>>());-- // Run the deduplication logic using a subquery (simpler than temp table)- // This is equivalent to what the migration does- sqlx::query(- "DELETE FROM audio_transcriptions- WHERE id NOT IN (- SELECT MIN(id)- FROM audio_transcriptions- GROUP BY audio_chunk_id, transcription- )"- ).execute(&db.pool).await.unwrap();-- // Verify deduplication worked- let count_after: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM audio_transcriptions WHERE audio_chunk_id = ?")- .bind(chunk_id)- .fetch_one(&db.pool).await.unwrap();- assert_eq!(count_after.0, 1);- println!("After deduplication: {} rows", count_after.0);-- // Verify the first row (lowest id) was kept- let kept_row: (i64,) = sqlx::query_as("SELECT id FROM audio_transcriptions WHERE audio_chunk_id = ?")- .bind(chunk_id)- .fetch_one(&db.pool).await.unwrap();- assert_eq!(kept_row.0, first_id, "Should keep the row with lowest id");-- println!("✓ Deduplication logic correctly reduced {} -> {} rows, kept id {}", count_before.0, count_after.0, first_id);+ // At minimum, first one should be inserted+ assert!(id1 > 0, "First short phrase should be inserted");+ println!("✓ Short phrases handled without error");}- /// Test no errors when no duplicates exist+ /// Empty transcriptions should be skipped#[tokio::test]- async fn test_no_error_when_no_duplicates() {+ async fn test_empty_transcription_skipped() {let db = setup_test_db().await;- let device = AudioDevice {- name: "Test".to_string(),- device_type: DeviceType::Input,- };+ let chunk_id = db.insert_audio_chunk("test.mp4").await.unwrap();- // Insert unique transcriptions- for i in 0..5 {- let chunk_id = db.insert_audio_chunk(&format!("audio_{}.mp4", i)).await.unwrap();- let id = db.insert_audio_transcription(+ let id = db+ .insert_audio_transcription(chunk_id,- &format!("Unique transcription {}", i),+ " ", // Only whitespace0,"whisper",- &device,+ &input_device(),None,None,None,- ).await.unwrap();- assert!(id > 0, "Unique insert should succeed");- }+ )+ .await+ .unwrap();- // Count total- let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM audio_transcriptions")- .fetch_one(&db.pool).await.unwrap();- assert_eq!(count.0, 5);- println!("✓ 5 unique transcriptions inserted successfully");+ assert_eq!(id, 0, "Empty/whitespace transcription should be skipped");+ println!("✓ Empty transcription correctly skipped");}- /// Summary test showing before/after behavior+ /// Test rapid consecutive inserts (potential race condition scenario)#[tokio::test]- async fn test_summary_before_after() {+ async fn test_rapid_inserts_deduplicated() {let db = setup_test_db().await;- let device = AudioDevice {- name: "MacBook Pro Microphone".to_string(),- device_type: DeviceType::Input,- };-- let chunk_id = db.insert_audio_chunk("test.mp4").await.unwrap();+ let text = "This is a test transcription that should only appear once in the database.";- println!("\n=== DUPLICATE PREVENTION SUMMARY ===");- println!("Attempting to insert 'So like if' 3 times for same chunk...\n");+ // Insert same content rapidly from different "devices"+ let mut successful = 0;+ for i in 0..5 {+ let chunk = db+ .insert_audio_chunk(&format!("audio_{}.mp4", i))+ .await+ .unwrap();+ let device = if i % 2 == 0 {+ output_device()+ } else {+ input_device()+ };++ let id = db+ .insert_audio_transcription(chunk, text, 0, "whisper", &device, None, None, None)+ .await+ .unwrap();- let mut ids = Vec::new();- for i in 0..3 {- let id = db.insert_audio_transcription(- chunk_id,- "So like if",- 0,- "whisper",- &device,- Some(1),- Some(i as f64 * 10.0),- Some((i + 1) as f64 * 10.0),- ).await.unwrap();- println!(" Insert attempt {}: returned id = {}", i + 1, id);- ids.push(id);+ if id > 0 {+ successful += 1;+ }}- let count = db.count_audio_transcriptions(chunk_id).await.unwrap();+ assert_eq!(+ successful, 1,+ "Only first of 5 rapid duplicate inserts should succeed"+ );+ println!("✓ Rapid consecutive duplicates correctly deduplicated (1 of 5 inserted)");+ }- println!("\nResults:");- println!(" - First insert: id = {} (SUCCESS)", ids[0]);- println!(" - Second insert: id = {} (IGNORED - duplicate)", ids[1]);- println!(" - Third insert: id = {} (IGNORED - duplicate)", ids[2]);- println!(" - Total rows in DB: {}", count);- println!("\n✓ BEFORE FIX: Would have 3 rows");- println!("✓ AFTER FIX: Only 1 row (duplicates prevented)");+ // ===========================================================================+ // SUMMARY / INTEGRATION TEST+ // ===========================================================================- assert_eq!(count, 1);- assert!(ids[0] > 0);- assert_eq!(ids[1], 0);- assert_eq!(ids[2], 0);+ /// Comprehensive test showing the full deduplication behavior+ #[tokio::test]+ async fn test_full_deduplication_behavior() {+ let db = setup_test_db().await;++ println!("\n=== AUDIO DEDUPLICATION COMPREHENSIVE TEST ===\n");++ // Scenario 1: Same device, same chunk - UNIQUE constraint+ println!("Scenario 1: Same device, same chunk");+ let chunk1 = db.insert_audio_chunk("chunk1.mp4").await.unwrap();+ let id1a = db+ .insert_audio_transcription(+ chunk1,+ "Test phrase for scenario one.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ let id1b = db+ .insert_audio_transcription(+ chunk1,+ "Test phrase for scenario one.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ println!(+ " First insert: id={} (success), Second insert: id={} (blocked by UNIQUE)",+ id1a, id1b+ );+ assert!(id1a > 0 && id1b == 0);++ // Scenario 2: Different device, different chunk, SAME content - Cross-device dedup+ println!("\nScenario 2: Different devices, same content (THE BUG WE FIXED)");+ let chunk2a = db.insert_audio_chunk("output_chunk.mp4").await.unwrap();+ let chunk2b = db.insert_audio_chunk("input_chunk.mp4").await.unwrap();+ let id2a = db+ .insert_audio_transcription(+ chunk2a,+ "Unique content that appears on both output and input devices.",+ 0,+ "whisper",+ &output_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ let id2b = db+ .insert_audio_transcription(+ chunk2b,+ "Unique content that appears on both output and input devices.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ println!(+ " Output device: id={} (success), Input device: id={} (blocked by similarity)",+ id2a, id2b+ );+ assert!(id2a > 0 && id2b == 0);++ // Scenario 3: Different devices, DIFFERENT content - Should both succeed+ println!("\nScenario 3: Different devices, different content");+ let chunk3a = db.insert_audio_chunk("output_different.mp4").await.unwrap();+ let chunk3b = db.insert_audio_chunk("input_different.mp4").await.unwrap();+ let id3a = db+ .insert_audio_transcription(+ chunk3a,+ "The weather today is sunny and warm.",+ 0,+ "whisper",+ &output_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ let id3b = db+ .insert_audio_transcription(+ chunk3b,+ "I need to buy groceries for dinner tonight.",+ 0,+ "whisper",+ &input_device(),+ None,+ None,+ None,+ )+ .await+ .unwrap();+ println!(+ " Output device: id={} (success), Input device: id={} (success - different content)",+ id3a, id3b+ );+ assert!(id3a > 0 && id3b > 0);++ println!("\n✓ All deduplication scenarios working correctly");+ println!("=== TEST COMPLETE ===\n");}}