#7392·screenpipe

Native batch transcription loses sentence context and persisted/searchable audio rows

Author: diegormquintelaCreated Sep 30, 2026Updated Sep 30, 2026

Native batch transcription can lose sentence context and stored/searchable words even when the captured recording contains the complete sentence. This report provides a reproducible, source-bound repair for maintainer review and an official signed Windows release.

Base commit: f956583aba065371b58ea903bb14e9488c9d1833 (0.4.50 source). The patch below is tested against this immutable base; it needs maintainer integration with current main. No private recordings, database contents, account paths or credentials are included.

The failures are independent:

  • Native speaker segmentation can send a short tail separately from its sentence. The repair forms bounded linguistic windows from each original capture buffer, keeps genuine speaker/source/timestamp evidence separately, and recognizes connected overlapping samples once.
  • Text overlap cleanup can remove words from disjoint utterances. The repair removes only a proven suffix/prefix duplicate.
  • Public search groups by capture/offset, collapsing distinct native rows with the same offset. The repair groups and orders by the actual transcription row ID.
  • The local caller's 30-second deadline can expire before 12 seconds of admission plus up to 90 seconds of bounded long-audio processing. The optional exact-loopback port-8080 repair uses one 125-second remaining budget covering encoding, request, retry/backoff and response. Other provider defaults stay unchanged. The companion local broker patch makes identical-request followers consume the original leader's remaining 102-second admission/processing budget.

Validation completed in isolated workers with real cached dependencies, no external networking, no host mounts, non-root execution and bounded resources:

  • Corrected full baseline/candidate validator: original compiles and fails three of four expected SQLite preservation cases; repaired code passes all six real DatabaseManager/SQLite tests and sixteen context/overlap tests. Validator regression coverage rejects compile failures, skipped/truncated output and unrelated assertions as behavioral proof.
  • Deadline component: thirteen actual Rust/reqwest HTTP tests, including the public transcription entry point with a pooled client's shorter default, response-body deadlines, retries sharing one budget and endpoint scoping. Nineteen context/planner tests include 60/120-second windows and eight independent concurrent streams.
  • Full changed Windows audio library type check passed for x86_64-pc-windows-msvc. This is metadata/type checking, not a linked release executable or signing proof.
  • Companion broker: nine deadline/follower behavior regressions and forty-six existing capture/recording regressions passed. Existing 12-second queue, 28-second per-segment and 90-second long-processing limits are preserved.

Latest combined validation of the complete nine-file repair passed against the pinned source and real cached dependencies: baseline compilation succeeded and reproduced exactly the three expected SQLite preservation failures; the repaired code passed all six SQLite tests, nineteen context/long/concurrent-stream tests, and thirteen real native HTTP/deadline/encoder tests. The isolated worker was independently confirmed removed after completion. The passing full-run receipt SHA-256 is 0c672459598ec854cabebbbe617a2de9ff02dd7b8195459ba782c4cd7c5a678e. The patch below is unchanged.

Limits preserved: complete Windows release linking, official signing and supported delivery remain outstanding. Windows library metadata is not a final executable, and an older cached executable is not this repaired build. The unchanged 3 GiB admission guard is retained. Two distinct saved long-audio requests failed queue/backend deadlines on the current unpatched runtime. Neither the candidate nor replay results have been installed or inserted as native transcript evidence. No full microphone/playback completeness claim or production observation claim is made.

The immutable 0.4.51 npm source commit 68d02ba05c8a34175476d9796c14c3af9343099d was also compared: its duration-aware timeout/429 retries improve transport behavior, but it still processes individual speaker segments and retains the overlap/search behaviors addressed here.

Please review/integrate the exact patches, complete the release-link/native smoke checks and produce the candidate through the existing protected Windows signing workflow. An immutable source/run identity, package/executable hashes, approved Authenticode publisher/timestamp and dependency smoke results are needed before supported installation and separate native microphone/output acceptance.

Recorder patch SHA-256: 4fa3577b0a302781ce3ef753723cb12c559344160a8c4f7ec98aa8bca1d4d19d.

Complete recorder patch against the pinned base (nine files)
diff
--- a/crates/screenpipe-audio/src/speaker/prepare_segments.rs
+++ b/crates/screenpipe-audio/src/speaker/prepare_segments.rs
@@ -19,7 +19,7 @@
 };
 
 #[allow(clippy::too_many_arguments)]
-pub async fn prepare_segments(
+async fn prepare_segments_data(
     audio_data: &[f32],
     vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
     segmentation_model_path: Option<&PathBuf>,
@@ -28,7 +28,7 @@
     device: &str,
     is_output_device: bool,
     filter_music: bool,
-) -> Result<(tokio::sync::mpsc::Receiver<SpeechSegment>, bool, f32)> {
+) -> Result<(Vec<SpeechSegment>, Vec<f32>, bool, f32)> {
     let mut audio_data = normalize_v2(audio_data);
 
     if filter_music {
@@ -98,27 +98,18 @@
 
     let threshold_met = speech_ratio > current_min_ratio;
 
-    let (tx, rx) = tokio::sync::mpsc::channel(100);
+    let mut prepared = Vec::new();
     if !audio_frames.is_empty() && threshold_met {
         if segmentation_model_path.is_none() || embedding_extractor.is_none() {
             let mut fallback_segment = Vec::new();
             fallback_segment.extend_from_slice(&audio_data);
 
-            if tx
-                .send(SpeechSegment {
-                    start: 0.0,
-                    end: fallback_segment.len() as f64 / 16000.0,
-                    samples: fallback_segment,
-                    speaker: "unknown".to_string(),
-                    embedding: Vec::new(),
-                    sample_rate: 16000,
-                })
-                .await
-                .is_ok()
-            {
-                debug!("fallback speech segment sent for {}", device);
-            }
-            return Ok((rx, threshold_met, speech_ratio));
+            prepared.push(SpeechSegment {
+                start:0.0,end:fallback_segment.len() as f64/16000.0,
+                samples:fallback_segment,speaker:"unknown".to_string(),
+                embedding:Vec::new(),sample_rate:16000,
+            });
+            return Ok((prepared, audio_data, threshold_met, speech_ratio));
         }
 
         let segmentation_model_path = segmentation_model_path.unwrap();
@@ -137,10 +128,8 @@
         for segment in segments {
             match segment {
                 Ok(segment) => {
-                    if let Err(e) = tx.send(segment).await {
-                        error!("failed to send segment: {:?}", e);
-                        break;
-                    }
+                    if prepared.len() >= 512 { anyhow::bail!("too many native speaker regions"); }
+                    prepared.push(segment);
                 }
                 Err(e) => {
                     error!("failed to get segment: {:?}", e);
@@ -150,5 +139,38 @@
         }
     }
 
-    Ok((rx, threshold_met, speech_ratio))
+    Ok((prepared, audio_data, threshold_met, speech_ratio))
 }
+
+#[allow(clippy::too_many_arguments)]
+pub async fn prepare_segments(
+    audio_data: &[f32],
+    vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
+    segmentation_model_path: Option<&PathBuf>,
+    embedding_manager: Arc<StdMutex<EmbeddingManager>>,
+    embedding_extractor: Option<Arc<StdMutex<EmbeddingExtractor>>>,
+    device: &str,
+    is_output_device: bool,
+    filter_music: bool,
+) -> Result<(tokio::sync::mpsc::Receiver<SpeechSegment>, bool, f32)> {
+    let (prepared, _, met, ratio) = prepare_segments_data(audio_data, vad_engine, segmentation_model_path, embedding_manager, embedding_extractor, device, is_output_device, filter_music).await?;
+    let (tx,rx) = tokio::sync::mpsc::channel(prepared.len().max(1));
+    for segment in prepared { tx.try_send(segment).map_err(|_|anyhow::anyhow!("native segment channel unavailable"))?; }
+    Ok((rx,met,ratio))
+}
+
+#[allow(clippy::too_many_arguments)]
+pub async fn prepare_stt_windows(
+    audio_data: &[f32],
+    vad_engine: Arc<Mutex<Box<dyn VadEngine + Send>>>,
+    segmentation_model_path: Option<&PathBuf>,
+    embedding_manager: Arc<StdMutex<EmbeddingManager>>,
+    embedding_extractor: Option<Arc<StdMutex<EmbeddingExtractor>>>,
+    device: &str,
+    is_output_device: bool,
+    filter_music: bool,
+) -> Result<(Vec<super::stt_context::SttWindow>, bool, f32)> {
+    let (prepared, source, met, ratio) = prepare_segments_data(audio_data, vad_engine, segmentation_model_path, embedding_manager, embedding_extractor, device, is_output_device, filter_music).await?;
+    let windows = super::stt_context::plan_stt_windows(&source,16000,prepared).map_err(anyhow::Error::msg)?;
+    Ok((windows,met,ratio))
+}
--- a/crates/screenpipe-audio/src/speaker/mod.rs
+++ b/crates/screenpipe-audio/src/speaker/mod.rs
@@ -313,3 +313,6 @@
         );
     }
 }
+
+pub(crate) mod stt_context;
+pub(crate) use prepare_segments::prepare_stt_windows;
--- a/crates/screenpipe-audio/src/transcription/stt.rs
+++ b/crates/screenpipe-audio/src/transcription/stt.rs
@@ -7,7 +7,7 @@
 use crate::metrics::AudioPipelineMetrics;
 use crate::speaker::embedding::EmbeddingExtractor;
 use crate::speaker::embedding_manager::EmbeddingManager;
-use crate::speaker::prepare_segments;
+use crate::speaker::prepare_stt_windows;
 use crate::speaker::segment::SpeechSegment;
 use crate::transcription::deepgram::batch::transcribe_with_deepgram;
 use crate::transcription::deepgram::DeepgramTranscriptionConfig;
@@ -299,7 +299,7 @@
 
     let is_output_device = audio.device.device_type == crate::core::device::DeviceType::Output;
     let device_name = audio.device.to_string();
-    let (mut segments, speech_ratio_ok, speech_ratio) = prepare_segments(
+    let (segments, speech_ratio_ok, speech_ratio) = prepare_stt_windows(
         &audio_data,
         vad_engine,
         segmentation_model_path.as_ref(),
@@ -336,10 +336,10 @@
         new_file_path
     };
 
-    while let Some(segment) = segments.recv().await {
+    for window in segments {
         let path = file_path.clone();
-        let transcription_result = run_stt(
-            segment,
+        let mut transcription_result = run_stt(
+            window.audio,
             audio.device.clone(),
             &device_name,
             path,
@@ -347,6 +347,8 @@
             session,
         )
         .await?;
+
+        if transcription_result.diarization_segments.is_empty() { transcription_result.local_segments = window.diarization; }
 
         if output_sender.send(transcription_result).is_err() {
             break;
@@ -389,6 +391,7 @@
                 end_time: segment.end,
                 diarization_provider: diarization_segments.diarization_provider,
                 diarization_segments: diarization_segments.diarization_segments,
+                local_segments:Vec::new(),
             })
         }
         Err(e) => {
@@ -410,6 +413,7 @@
                 end_time: segment.end,
                 diarization_provider: None,
                 diarization_segments: Vec::new(),
+                local_segments:Vec::new(),
             })
         }
     }
--- a/crates/screenpipe-audio/src/transcription/transcription_result.rs
+++ b/crates/screenpipe-audio/src/transcription/transcription_result.rs
@@ -16,7 +16,7 @@
 };
 
 use super::{
-    text_utils::longest_common_word_substring, AudioInput, TranscriptionDiarizationSegment,
+    text_utils::deduplicate_transcript_prefix, AudioInput, TranscriptionDiarizationSegment,
 };
 
 #[derive(Debug, Clone)]
@@ -31,34 +31,16 @@
     pub end_time: f64,
     pub diarization_provider: Option<String>,
     pub diarization_segments: Vec<TranscriptionDiarizationSegment>,
+    /// Original local regions, independent from linguistic context windows.
+    pub local_segments: Vec<crate::speaker::segment::SpeechSegment>,
 }
 
 impl TranscriptionResult {
     // TODO --optimize
     pub fn cleanup_overlap(&mut self, previous_transcript: String) -> Option<(String, String)> {
-        if let Some(transcription) = &self.transcription {
-            let transcription = transcription.to_string();
-            if let Some((prev_idx, cur_idx, match_len)) =
-                longest_common_word_substring(previous_transcript.as_str(), transcription.as_str())
-            {
-                // strip old transcript from prev_idx word pos (keep words before the overlap)
-                let prev_words: Vec<&str> = previous_transcript.split_whitespace().collect();
-                let new_prev = prev_words[..prev_idx].join(" ");
-
-                // strip new transcript AFTER the overlap ends (skip the overlapped portion)
-                let curr_words: Vec<&str> = transcription.split_whitespace().collect();
-                let skip_until = cur_idx + match_len;
-                let new_cur = if skip_until < curr_words.len() {
-                    curr_words[skip_until..].join(" ")
-                } else {
-                    String::new() // Entire current transcript was overlap
-                };
-
-                return Some((new_prev, new_cur));
-            }
-        }
-
-        None
+        let current = self.transcription.as_ref()?;
+        let tail = deduplicate_transcript_prefix(&previous_transcript, current)?;
+        Some((previous_transcript, tail))
     }
 }
 
@@ -102,7 +84,11 @@
         return Ok(None);
     }
 
-    let speaker_id = if result.speaker_embedding.is_empty() {
+    let resolved_local = if !result.local_segments.is_empty() && result.diarization_segments.is_empty() {
+        Some(resolve_local_context(db,&result.local_segments).await?)
+    } else { None };
+    let has_local = resolved_local.is_some();
+    let speaker_id = if let Some((speaker,_)) = &resolved_local { *speaker } else if result.speaker_embedding.is_empty() {
         debug!("empty speaker embedding; storing transcript without speaker");
         None
     } else {
@@ -131,6 +117,10 @@
     };
     let transcription_engine = audio_transcription_engine.to_string();
     let mut chunk_id: Option<i64> = None;
+    let segments = match resolved_local {
+        Some((_,regions)) => regions,
+        None => diarization_segments_for_insert(&result,speaker_id),
+    };
 
     debug!("device {} inserting audio chunk", result.input.device);
     if let Some(id) = previous_transcript_id {
@@ -190,14 +180,13 @@
                     "Inserted audio chunk+transcription for device {} using {}",
                     result.input.device, transcription_engine
                 );
-                let segments = diarization_segments_for_insert(&result, speaker_id);
-                let provider = result.diarization_provider.as_deref().unwrap_or(
+                let provider = if has_local { "local" } else { result.diarization_provider.as_deref().unwrap_or(
                     if result.speaker_embedding.is_empty() {
                         "none"
                     } else {
                         "local"
                     },
-                );
+                ) };
                 if let Err(e) = db
                     .insert_diarization_run_with_segments(
                         audio_chunk_id,
@@ -585,6 +574,7 @@
             end_time: 1.0,
             diarization_provider: None,
             diarization_segments: Vec::new(),
+            local_segments:Vec::new(),
         };
 
         let data_dir = tempfile::tempdir().unwrap();
@@ -636,3 +626,29 @@
         );
     }
 }
+
+// Resolve each speaker from its ORIGINAL duration and embedding, not the ASR window.
+// Text remains at window level; no duration-proportional or guessed word alignment.
+async fn resolve_local_context(
+    db: &DatabaseManager, regions: &[crate::speaker::segment::SpeechSegment],
+) -> Result<(Option<i64>, Vec<NewDiarizationSegment>), anyhow::Error> {
+    let mut records = Vec::with_capacity(regions.len());
+    let mut identities = Vec::with_capacity(regions.len());
+    for region in regions {
+        let id = if region.embedding.is_empty() { None } else {
+            get_or_create_speaker_from_embedding(db, &region.embedding,
+                segment_duration_secs(region.start, region.end)).await?.map(|speaker|speaker.id)
+        };
+        identities.push(id);
+        records.push(NewDiarizationSegment {
+            provider_speaker_label: id.map_or_else(|| format!("local:{}",region.speaker),|id|format!("speaker:{id}")),
+            speaker_id:id,source:if id.is_some() { "local_embedding" } else { "none" }.to_string(),
+            start_time:region.start,end_time:region.end,confidence:None,overlap:false,
+            metadata:Some(serde_json::json!({"text_alignment":"unavailable",
+                "transcript_scope":"separate_context_window","local_label":region.speaker}).to_string()),
+        });
+    }
+    let shared = identities.first().copied().flatten()
+        .filter(|id|identities.iter().all(|other|*other==Some(*id)));
+    Ok((shared,records))
+}
--- a/crates/screenpipe-audio/src/transcription/handle_new_transcript.rs
+++ b/crates/screenpipe-audio/src/transcription/handle_new_transcript.rs
@@ -11,7 +11,7 @@
 use screenpipe_db::DatabaseManager;
 use tracing::{debug, error, info};
 
-use super::TranscriptionResult;
+use super::{text_utils::TranscriptSpan, TranscriptionResult};
 
 /// Information about a successfully inserted audio transcription.
 /// Passed to the optional on_insert callback so callers (e.g. the hot
@@ -59,6 +59,7 @@
     // could incorrectly trim device B's content.
     let mut prev_transcript_by_device: HashMap<String, String> = HashMap::new();
     let mut prev_id_by_device: HashMap<String, i64> = HashMap::new();
+    let mut prev_span_by_device: HashMap<String, TranscriptSpan> = HashMap::new();
     while let Ok(mut transcription) = transcription_receiver.recv() {
         // Heartbeat: record that the consumer is alive and processing, even when
         // VAD filters everything. The health check uses this to distinguish
@@ -97,12 +98,19 @@
             .cloned()
             .unwrap_or_default();
         let previous_transcript_id = prev_id_by_device.get(&device_key).copied();
+        let current_span = TranscriptSpan {
+            device: device_key.clone(), source: transcription.path.clone(),
+            capture_timestamp: transcription.timestamp,
+            start: transcription.start_time, end: transcription.end_time,
+        };
+        let physical_overlap = prev_span_by_device.get(&device_key)
+            .is_some_and(|previous| previous.overlaps_same_source(&current_span));
         let mut current_transcript: Option<String> = transcription.transcription.clone();
         let mut processed_previous: Option<String> = None;
         let mut was_trimmed = false;
 
         if let Some((previous, current)) =
-            transcription.cleanup_overlap(previous_transcript.clone())
+            if physical_overlap { transcription.cleanup_overlap(previous_transcript.clone()) } else { None }
         {
             // If current is empty after cleanup, the entire transcript was a duplicate - skip it
             if current.is_empty() {
@@ -128,12 +136,7 @@
         }
 
         transcription.transcription = current_transcript.clone();
-        if current_transcript.is_some() {
-            prev_transcript_by_device
-                .insert(device_key.clone(), current_transcript.clone().unwrap());
-