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

fix: speaker delete fails silently due to missing audio chunk files (#3346)

Colwilso1b24929ed95d
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index f9a00cdb4..bf7f94248 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -5484,16 +5484,20 @@ impl DatabaseManager {
pub async fn delete_speaker(&self, id: i64) -> Result<(), sqlx::Error> {
let mut tx = self.begin_immediate_with_retry().await?;
- // Array of (query, operation description) tuples
+ // Collect candidate chunk IDs before deleting transcriptions
+ let candidate_chunk_ids: Vec<(i64,)> = sqlx::query_as(
+ "SELECT DISTINCT audio_chunk_id FROM audio_transcriptions WHERE speaker_id = ?",
+ )
+ .bind(id)
+ .fetch_all(&mut **tx.conn())
+ .await?;
+
+ // Delete in FK-safe order: transcriptions first (they reference chunks), then chunks
let operations = [
(
"DELETE FROM audio_transcriptions WHERE speaker_id = ?",
"audio transcriptions",
),
- (
- "DELETE FROM audio_chunks WHERE id IN (SELECT audio_chunk_id FROM audio_transcriptions WHERE speaker_id = ? AND start_time IS NULL)",
- "audio chunks",
- ),
(
"DELETE FROM speaker_embeddings WHERE speaker_id = ?",
"speaker embeddings",
@@ -5504,16 +5508,30 @@ impl DatabaseManager {
),
];
- // Execute each deletion operation
for (query, operation) in operations {
if let Err(e) = sqlx::query(query).bind(id).execute(&mut **tx.conn()).await {
error!("Failed to delete {} for speaker {}: {}", operation, id, e);
- // tx will rollback automatically on drop
return Err(e);
}
debug!("Successfully deleted {} for speaker {}", operation, id);
}
+ // Delete only orphaned chunks (not referenced by any remaining transcription)
+ for (chunk_id,) in &candidate_chunk_ids {
+ if let Err(e) = sqlx::query(
+ "DELETE FROM audio_chunks WHERE id = ? \
+ AND NOT EXISTS (SELECT 1 FROM audio_transcriptions WHERE audio_chunk_id = ?)",
+ )
+ .bind(chunk_id)
+ .bind(chunk_id)
+ .execute(&mut **tx.conn())
+ .await
+ {
+ error!("Failed to delete audio chunk {} for speaker {}: {}", chunk_id, id, e);
+ return Err(e);
+ }
+ }
+
tx.commit().await.map_err(|e| {
error!("Failed to commit speaker deletion transaction: {}", e);
e
diff --git a/crates/screenpipe-db/tests/db.rs b/crates/screenpipe-db/tests/db.rs
index 97f7c8e21..7737ad088 100644
--- a/crates/screenpipe-db/tests/db.rs
+++ b/crates/screenpipe-db/tests/db.rs
@@ -1143,9 +1143,68 @@ mod tests {
let speakers = db.search_speakers("").await.unwrap();
assert_eq!(speakers.len(), 0);
- // make sure audio_chunks are deleted
- let audio_chunks = db.get_audio_chunks_for_speaker(speaker.id).await.unwrap();
- assert_eq!(audio_chunks.len(), 0);
+ // Directly verify the orphaned chunk row was deleted
+ assert!(
+ !db.audio_chunk_exists(audio_chunk_id).await.unwrap(),
+ "orphaned audio_chunk row should be deleted"
+ );
+ }
+
+ #[tokio::test]
+ async fn test_delete_speaker_shared_chunk_preserved() {
+ let db = setup_test_db().await;
+
+ let speaker_a = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ let speaker_b = db.insert_speaker(&vec![0.2; 512]).await.unwrap();
+
+ // Both speakers reference the same audio chunk
+ let shared_chunk_id = db.insert_audio_chunk("shared.mp4", None).await.unwrap();
+ let device = AudioDevice {
+ name: "test".to_string(),
+ device_type: DeviceType::Output,
+ };
+ db.insert_audio_transcription(
+ shared_chunk_id,
+ "speaker a says hello",
+ 0,
+ "",
+ &device,
+ Some(speaker_a.id),
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ db.insert_audio_transcription(
+ shared_chunk_id,
+ "speaker b says goodbye",
+ 1,
+ "",
+ &device,
+ Some(speaker_b.id),
+ None,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ // Delete speaker_a -- shared chunk must survive
+ db.delete_speaker(speaker_a.id).await.unwrap();
+
+ assert!(
+ db.audio_chunk_exists(shared_chunk_id).await.unwrap(),
+ "shared chunk still referenced by speaker_b must not be deleted"
+ );
+
+ // Delete speaker_b -- now the chunk is orphaned and should be removed
+ db.delete_speaker(speaker_b.id).await.unwrap();
+
+ assert!(
+ !db.audio_chunk_exists(shared_chunk_id).await.unwrap(),
+ "chunk should be deleted once all referencing transcriptions are gone"
+ );
}
#[tokio::test]
diff --git a/crates/screenpipe-engine/src/routes/speakers.rs b/crates/screenpipe-engine/src/routes/speakers.rs
index d872de998..e09971e24 100644
--- a/crates/screenpipe-engine/src/routes/speakers.rs
+++ b/crates/screenpipe-engine/src/routes/speakers.rs
@@ -219,15 +219,14 @@ pub(crate) async fn delete_speaker_handler(
)
})?;
- // delete all audio chunks from the file system
+ // delete all audio chunks from the file system (best-effort)
for audio_chunk in audio_chunks {
if audio_chunk.start_time.is_some() && audio_chunk.end_time.is_some() {
- std::fs::remove_file(audio_chunk.file_path).map_err(|e| {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- JsonResponse(json!({"error": e.to_string()})),
- )
- })?;
+ if let Err(e) = std::fs::remove_file(&audio_chunk.file_path) {
+ if e.kind() != std::io::ErrorKind::NotFound {
+ tracing::warn!("failed to remove audio chunk file {}: {}", audio_chunk.file_path, e);
+ }
+ }
}
}