Skip to content

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

feat(db): add audio transcription deduplication migration and tests

Louis Beaumontef45c4373080
diff --git a/Cargo.lock b/Cargo.lock
index e8f013169..cbff7bec8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6567,7 +6567,7 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "screenpipe-audio"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"anyhow",
"bytemuck",
@@ -6620,7 +6620,7 @@ dependencies = [
[[package]]
name = "screenpipe-core"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"accessibility",
"accessibility-sys",
@@ -6663,7 +6663,7 @@ dependencies = [
[[package]]
name = "screenpipe-db"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"anyhow",
"chrono",
@@ -6687,7 +6687,7 @@ dependencies = [
[[package]]
name = "screenpipe-events"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"anyhow",
"chrono",
@@ -6705,7 +6705,7 @@ dependencies = [
[[package]]
name = "screenpipe-integrations"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"anyhow",
"image",
@@ -6720,7 +6720,7 @@ dependencies = [
[[package]]
name = "screenpipe-server"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"anyhow",
"axum",
@@ -6783,7 +6783,7 @@ dependencies = [
[[package]]
name = "screenpipe-vision"
-version = "0.2.86"
+version = "0.2.92"
dependencies = [
"accessibility-sys",
"anyhow",
diff --git a/screenpipe-db/src/db.rs b/screenpipe-db/src/db.rs
index 1171f9e64..6eadfd94c 100644
--- a/screenpipe-db/src/db.rs
+++ b/screenpipe-db/src/db.rs
@@ -146,9 +146,10 @@ impl DatabaseManager {
let text_length = transcription.len() as i64;
let mut tx = self.pool.begin().await?;
- // Insert the full transcription
- let id = sqlx::query(
- "INSERT 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)",
+ // Insert the transcription, ignoring duplicates (same audio_chunk_id + transcription)
+ // This prevents duplicates from VAD segment overlap issues
+ let 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)",
)
.bind(audio_chunk_id)
.bind(transcription)
@@ -162,13 +163,19 @@ impl DatabaseManager {
.bind(end_time)
.bind(text_length)
.execute(&mut *tx)
- .await?
- .last_insert_rowid();
+ .await?;
- // Commit the transaction for the full transcription
+ // Commit the transaction
tx.commit().await?;
- Ok(id)
+ // Returns 0 if the insert was ignored (duplicate), otherwise returns the new id
+ // Note: last_insert_rowid() returns the previous successful insert's id when ignored,
+ // so we check rows_affected() to detect ignored inserts
+ if result.rows_affected() == 0 {
+ Ok(0)
+ } else {
+ Ok(result.last_insert_rowid())
+ }
}
pub async fn update_audio_transcription(
diff --git a/screenpipe-db/src/migrations/20260126200000_dedupe_audio_transcriptions.sql b/screenpipe-db/src/migrations/20260126200000_dedupe_audio_transcriptions.sql
new file mode 100644
index 000000000..715ff32d4
--- /dev/null
+++ b/screenpipe-db/src/migrations/20260126200000_dedupe_audio_transcriptions.sql
@@ -0,0 +1,47 @@
+-- Migration: Deduplicate audio transcriptions and add UNIQUE constraint
+-- This prevents the same transcription text from being inserted multiple times
+-- for the same audio chunk (caused by VAD segment overlap issues)
+--
+-- Safe for production: handles FTS triggers correctly
+
+PRAGMA foreign_keys = OFF;
+
+-- Step 1: Create a table with IDs to delete (keeping the row with lowest id for each duplicate group)
+CREATE TABLE IF NOT EXISTS _temp_audio_ids_to_delete AS
+SELECT id FROM audio_transcriptions
+WHERE id NOT IN (
+ SELECT MIN(id)
+ FROM audio_transcriptions
+ GROUP BY audio_chunk_id, transcription
+);
+
+-- Step 2: Delete from FTS table first to avoid trigger conflicts
+-- The FTS table uses audio_chunk_id as the key
+DELETE FROM audio_transcriptions_fts
+WHERE audio_chunk_id IN (
+ SELECT audio_chunk_id FROM audio_transcriptions
+ WHERE id IN (SELECT id FROM _temp_audio_ids_to_delete)
+);
+
+-- Step 3: Temporarily drop the delete trigger to avoid FTS issues
+DROP TRIGGER IF EXISTS audio_transcriptions_delete;
+
+-- Step 4: Delete the duplicate rows from the main table
+DELETE FROM audio_transcriptions WHERE id IN (SELECT id FROM _temp_audio_ids_to_delete);
+
+-- Step 5: Recreate the delete trigger
+CREATE TRIGGER IF NOT EXISTS audio_transcriptions_delete AFTER DELETE ON audio_transcriptions
+BEGIN
+ DELETE FROM audio_transcriptions_fts
+ WHERE audio_chunk_id = OLD.audio_chunk_id;
+END;
+
+-- Step 6: Clean up the temporary table
+DROP TABLE IF EXISTS _temp_audio_ids_to_delete;
+
+-- Step 7: Add the UNIQUE constraint to prevent future duplicates
+-- This index ensures (audio_chunk_id, transcription) is unique
+CREATE UNIQUE INDEX IF NOT EXISTS idx_audio_transcription_chunk_text
+ON audio_transcriptions(audio_chunk_id, transcription);
+
+PRAGMA foreign_keys = ON;
diff --git a/screenpipe-db/tests/audio_duplicate_test.rs b/screenpipe-db/tests/audio_duplicate_test.rs
new file mode 100644
index 000000000..442012ee3
--- /dev/null
+++ b/screenpipe-db/tests/audio_duplicate_test.rs
@@ -0,0 +1,415 @@
+/// Audio Transcription Duplicate Prevention Test
+///
+/// This test verifies that the UNIQUE constraint on (audio_chunk_id, transcription)
+/// prevents duplicate audio transcriptions from being inserted.
+///
+/// Run with: cargo test --package screenpipe-db --test audio_duplicate_test -- --nocapture
+
+#[cfg(test)]
+mod tests {
+ use screenpipe_db::{AudioDevice, DatabaseManager, DeviceType};
+
+ async fn setup_test_db() -> DatabaseManager {
+ let db = DatabaseManager::new("sqlite::memory:").await.unwrap();
+
+ match sqlx::migrate!("./src/migrations").run(&db.pool).await {
+ Ok(_) => {}
+ Err(e) => {
+ eprintln!("Migration error: {:?}", e);
+ panic!("Database migration failed: {}", e);
+ }
+ }
+
+ db
+ }
+
+ /// Verify the UNIQUE constraint exists after migration
+ #[tokio::test]
+ async fn test_unique_constraint_exists() {
+ 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");
+ }
+
+ /// Test that INSERT OR IGNORE prevents exact duplicates
+ #[tokio::test]
+ async fn test_duplicate_insert_is_ignored() {
+ 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)");
+ }
+
+ /// Test that different transcriptions for the same chunk are allowed
+ #[tokio::test]
+ 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_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();
+ 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);
+
+ 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);
+ }
+
+ /// Test that same transcription in different chunks is allowed
+ #[tokio::test]
+ async fn test_same_transcription_different_chunks_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();
+ 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);
+
+ println!("✓ Same transcription in different chunks is allowed (ids: {}, {})", id1, id2);
+ }
+
+ /// Test the production scenario that was causing duplicates
+ #[tokio::test]
+ async fn test_production_duplicate_scenario_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();
+ 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
+ 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);
+ }
+
+ /// Test multiple rapid duplicate attempts (simulating race conditions)
+ #[tokio::test]
+ async fn test_rapid_duplicate_attempts() {
+ 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(
+ chunk_id,
+ "Repeated phrase",
+ 0,
+ "whisper",
+ &device,
+ None,
+ Some(i as f64),
+ Some((i + 1) as f64),
+ ).await.unwrap();
+
+ if id > 0 {
+ successful_inserts += 1;
+ }
+ }
+
+ assert_eq!(successful_inserts, 1, "Only first insert should succeed");
+
+ 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");
+ }
+
+ /// Test that the deduplication SQL logic works correctly
+ /// This verifies the migration's DELETE logic keeps the first row (lowest id)
+ #[tokio::test]
+ async fn test_migration_deduplication_logic() {
+ 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();
+
+ // 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();
+
+ // 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'), ?, ?)"
+ )
+ .bind(chunk_id)
+ .bind(i as f64)
+ .bind((i + 1) as f64)
+ .execute(&db.pool).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);
+ }
+
+ /// Test no errors when no duplicates exist
+ #[tokio::test]
+ async fn test_no_error_when_no_duplicates() {
+ let db = setup_test_db().await;
+
+ let device = AudioDevice {
+ name: "Test".to_string(),
+ device_type: DeviceType::Input,
+ };
+
+ // 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(
+ chunk_id,
+ &format!("Unique transcription {}", i),
+ 0,
+ "whisper",
+ &device,
+ None,
+ None,
+ None,
+ ).await.unwrap();
+ assert!(id > 0, "Unique insert should succeed");
+ }
+
+ // 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");
+ }
+
+ /// Summary test showing before/after behavior
+ #[tokio::test]
+ async fn test_summary_before_after() {
+ 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();
+
+ println!("\n=== DUPLICATE PREVENTION SUMMARY ===");
+ println!("Attempting to insert 'So like if' 3 times for same chunk...\n");
+
+ 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);
+ }
+
+ let count = db.count_audio_transcriptions(chunk_id).await.unwrap();
+
+ 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)");
+
+ assert_eq!(count, 1);
+ assert!(ids[0] > 0);
+ assert_eq!(ids[1], 0);
+ assert_eq!(ids[2], 0);
+ }
+}
diff --git a/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts b/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts
index 7047f353d..605561e4f 100644
--- a/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts
+++ b/screenpipe-js/ai-proxy/src/handlers/vertex-proxy.ts
@@ -55,6 +55,8 @@ export async function handleVertexProxy(request: Request, env: Env): Promise<Res
*/
export async function handleVertexModels(env: Env): Promise<Response> {
const models = [
+ { id: 'gemini-3-pro-preview', object: 'model', created: 1747180800, owned_by: 'google' },
+ { id: 'gemini-3-flash-preview', object: 'model', created: 1747180800, owned_by: 'google' },
{ id: 'claude-opus-4-5@20251101', object: 'model', created: 1747180800, owned_by: 'anthropic' },
{ id: 'claude-haiku-4-5@20251001', object: 'model', created: 1747180800, owned_by: 'anthropic' },
];
diff --git a/screenpipe-js/ai-proxy/src/providers/vertex.ts b/screenpipe-js/ai-proxy/src/providers/vertex.ts
index 29476ea62..ccc82fb88 100644
--- a/screenpipe-js/ai-proxy/src/providers/vertex.ts
+++ b/screenpipe-js/ai-proxy/src/providers/vertex.ts
@@ -396,6 +396,8 @@ export class VertexAIProvider implements AIProvider {
*/
async listModels(): Promise<{ id: string; name: string; provider: string }[]> {
const models = [
+ { id: 'gemini-3-pro-preview', name: 'Gemini 3 Pro', provider: 'google' },
+ { id: 'gemini-3-flash-preview', name: 'Gemini 3 Flash', provider: 'google' },
{ id: 'claude-opus-4-5@20251101', name: 'Claude Opus 4.5', provider: 'vertex' },
{ id: 'claude-haiku-4-5@20251001', name: 'Claude Haiku 4.5', provider: 'vertex' },
];