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(audio): unblock batch-mode transcription + kill false stall alarms

Louis Beaumonte9696fb5d0c6
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index ee1954ced..293fc8d9f 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -204,6 +204,7 @@ impl AudioManager {
let options_ref = self.options.clone();
let seg_mgr = self.segmentation_manager.clone();
let output_path_bg = self.options.read().await.output_path.clone();
+ let metrics_bg = self.metrics.clone();
let handle = tokio::spawn(async move {
// Wait for model to load + initial recordings
tokio::time::sleep(Duration::from_secs(120)).await;
@@ -224,6 +225,7 @@ impl AudioManager {
Some(seg_mgr.clone()),
data_dir,
batch_max_dur,
+ Some(metrics_bg.clone()),
)
.await;
if count > 0 {
@@ -733,6 +735,7 @@ impl AudioManager {
Some(segmentation_manager.clone()),
data_dir,
batch_max_duration_secs,
+ Some(metrics.clone()),
)
.await;
for _ in 0..count {
diff --git a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
index 39c64499d..b7fb28a8d 100644
--- a/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
+++ b/crates/screenpipe-audio/src/audio_manager/reconciliation.rs
@@ -22,6 +22,7 @@ const BACKFILL_MIN_INTERVAL: Duration = Duration::from_secs(30);
const BACKFILL_MAX_CHUNKS_PER_PASS: usize = 12;
use crate::core::engine::AudioTranscriptionEngine;
+use crate::metrics::AudioPipelineMetrics;
use crate::segmentation::segmentation_manager::SegmentationManager;
use crate::speaker::segment::get_segments;
use crate::transcription::engine::{TranscriptionEngine, TranscriptionSession};
@@ -86,6 +87,7 @@ pub async fn reconcile_untranscribed(
segmentation_manager: Option<Arc<SegmentationManager>>,
data_dir: Option<&Path>,
batch_max_duration_secs: Option<u64>,
+ metrics: Option<Arc<AudioPipelineMetrics>>,
) -> usize {
// Nothing to reconcile when transcription is disabled — skip entirely
// to avoid the silent-audio deletion path nuking audio files.
@@ -112,7 +114,7 @@ pub async fn reconcile_untranscribed(
// Retry any previously failed transcriptions before processing new chunks
if let Some(dir) = data_dir {
- retry_pending_transcriptions(db, dir, on_insert).await;
+ retry_pending_transcriptions(db, dir, on_insert, metrics.as_ref()).await;
}
let since = chrono::Utc::now() - chrono::Duration::hours(24);
@@ -383,7 +385,16 @@ pub async fn reconcile_untranscribed(
.iter()
.map(|c| c.file_path.clone())
.collect();
- match finalize_batch(db, &pending, on_insert, data_dir, &secondary_paths).await {
+ match finalize_batch(
+ db,
+ &pending,
+ on_insert,
+ data_dir,
+ &secondary_paths,
+ metrics.as_ref(),
+ )
+ .await
+ {
Ok(count) => {
consecutive_db_errors = 0;
success_count += count;
@@ -453,6 +464,7 @@ async fn finalize_batch(
on_insert: Option<&AudioInsertCallback>,
data_dir: Option<&Path>,
secondary_file_paths: &[String],
+ metrics: Option<&Arc<AudioPipelineMetrics>>,
) -> Result<usize, String> {
db.replace_audio_transcription(
pending.audio_chunk_id,
@@ -467,6 +479,15 @@ async fn finalize_batch(
.await
.map_err(|e| e.to_string())?;
+ // Record the DB write so health-check doesn't flag a false "stalled" alarm.
+ // Without this, sessions where reconciliation does most of the writes (batch
+ // mode, retry path) leave `last_db_write_ts` stale and the health endpoint
+ // reports "audio DB writes stalled — restart recommended" to a healthy system.
+ if let Some(m) = metrics {
+ let word_count = pending.transcription.split_whitespace().count() as u64;
+ m.record_db_insert(word_count);
+ }
+
// Success — remove the pending file
if let Some(dir) = data_dir {
remove_pending(dir, pending.audio_chunk_id);
@@ -517,6 +538,7 @@ async fn retry_pending_transcriptions(
db: &DatabaseManager,
data_dir: &Path,
on_insert: Option<&AudioInsertCallback>,
+ metrics: Option<&Arc<AudioPipelineMetrics>>,
) {
let dir = pending_dir(data_dir);
let entries = match std::fs::read_dir(&dir) {
@@ -576,7 +598,7 @@ async fn retry_pending_transcriptions(
// We don't have secondary file paths from the pending file, but they
// may already have been cleaned up. Pass empty slice — the DB deletion
// of secondary chunk IDs still happens.
- match finalize_batch(db, &pending, on_insert, Some(data_dir), &[]).await {
+ match finalize_batch(db, &pending, on_insert, Some(data_dir), &[], metrics).await {
Ok(_) => {
retried += 1;
debug!(
diff --git a/crates/screenpipe-audio/src/core/mod.rs b/crates/screenpipe-audio/src/core/mod.rs
index ffeb454b0..88c46971d 100644
--- a/crates/screenpipe-audio/src/core/mod.rs
+++ b/crates/screenpipe-audio/src/core/mod.rs
@@ -16,9 +16,8 @@ use dashmap::DashMap;
use lazy_static::lazy_static;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
-use std::time::{Duration, SystemTime, UNIX_EPOCH};
+use std::time::{SystemTime, UNIX_EPOCH};
use stream::AudioStream;
-use tracing::debug;
lazy_static! {
// Global fallback timestamp for backward compatibility
@@ -58,48 +57,34 @@ pub fn get_device_capture_time(device_name: &str) -> u64 {
.unwrap_or_else(|| LAST_AUDIO_CAPTURE.load(Ordering::Relaxed))
}
-fn is_normal_shutdown(is_running: &Arc<AtomicBool>) -> bool {
- !is_running.load(Ordering::Relaxed)
-}
-
#[cfg(all(test, target_os = "macos"))]
mod e2e_ghost_word_silent_room;
+/// Runs one recording session for the device. Returns `Ok(())` on normal
+/// shutdown (is_running went false) and `Err` when the underlying stream is
+/// dead (is_disconnected latched, timeout, CPAL error).
+///
+/// There is no in-function retry loop — on `Err`, the task handle finishes
+/// and `device_monitor::check_stale_recording_handles` notices within ~2s.
+/// That path calls `cleanup_stale_device` which removes the dead AudioStream
+/// from device_manager, then `start_device` rebuilds it. Retrying inside this
+/// function with the same `Arc<AudioStream>` cannot work — once `is_disconnected`
+/// latches to true, every subsequent `run_record_and_transcribe` returns Err
+/// in microseconds, so the previous exponential-backoff loop just produced
+/// log spam + CPU churn without making progress.
pub async fn record_and_transcribe(
audio_stream: Arc<AudioStream>,
- duration: Duration,
+ duration: std::time::Duration,
whisper_sender: Arc<crossbeam::channel::Sender<AudioInput>>,
is_running: Arc<AtomicBool>,
metrics: Arc<crate::metrics::AudioPipelineMetrics>,
) -> Result<()> {
- let mut consecutive_failures: u32 = 0;
- while is_running.load(Ordering::Relaxed) {
- match run_record_and_transcribe::run_record_and_transcribe(
- audio_stream.clone(),
- duration,
- whisper_sender.clone(),
- is_running.clone(),
- metrics.clone(),
- )
- .await
- {
- Ok(_) => break, // Normal shutdown
- Err(e) => {
- if is_normal_shutdown(&is_running) {
- return Err(e);
- }
- consecutive_failures += 1;
- // Exponential backoff: 1s, 2s, 4s, 8s, ... capped at 30s.
- // Prevents a hot loop when a device is persistently unavailable
- // (e.g. MacBook Air mic reporting "disconnected" every attempt).
- let backoff_secs = std::cmp::min(1u64 << (consecutive_failures - 1), 30);
- debug!(
- "record_and_transcribe error (attempt {}), restarting in {}s: {}",
- consecutive_failures, backoff_secs, e
- );
- tokio::time::sleep(Duration::from_secs(backoff_secs)).await;
- }
- }
- }
- Ok(())
+ run_record_and_transcribe::run_record_and_transcribe(
+ audio_stream,
+ duration,
+ whisper_sender,
+ is_running,
+ metrics,
+ )
+ .await
}
diff --git a/crates/screenpipe-engine/src/routes/health.rs b/crates/screenpipe-engine/src/routes/health.rs
index 87cae5b50..01bf139a5 100644
--- a/crates/screenpipe-engine/src/routes/health.rs
+++ b/crates/screenpipe-engine/src/routes/health.rs
@@ -28,6 +28,22 @@ static HEALTH_CACHE: std::sync::LazyLock<RwLock<(u64, Option<HealthCheckResponse
/// Minimum interval between full health recomputations (in seconds).
const HEALTH_CACHE_TTL_SECS: u64 = 1;
+/// Describe the most likely cause of a DB-write stall from pool stats.
+/// Old message always said "pool exhaustion likely" which was wrong when the
+/// real cause was elsewhere (e.g. metrics gap on reconciliation path) and the
+/// pools were fully idle. Only call out pool saturation when idle counts are 0.
+fn suspected_stall_cause(read_idle: u32, write_idle: u32) -> &'static str {
+ if write_idle == 0 && read_idle == 0 {
+ "both pools saturated"
+ } else if write_idle == 0 {
+ "write pool saturated"
+ } else if read_idle == 0 {
+ "read pool saturated"
+ } else {
+ "pools idle — cause upstream (writer path, lock contention, or missing metrics)"
+ }
+}
+
use screenpipe_screen::monitor::{
get_cached_monitor_descriptions, get_monitor_by_id, list_monitors, list_monitors_detailed,
MonitorListError,
@@ -280,9 +296,10 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
LAST_VISION_STALL_LOG.store(now_ts, Ordering::Relaxed);
let (rs, ri, ws, wi) = state.db.pool_stats();
warn!(
- "health_check: vision DB writes stalled — capture heartbeat {}s ago but last DB write {}s ago (pool exhaustion likely) | pool: read={}/{} idle, write={}/{} idle",
+ "health_check: vision DB writes stalled — capture heartbeat {}s ago but last DB write {}s ago ({}) | pool: read={}/{} idle, write={}/{} idle",
now_ts.saturating_sub(vision_snap.last_capture_attempt_ts),
now_ts.saturating_sub(vision_snap.last_db_write_ts),
+ suspected_stall_cause(ri, wi),
ri, rs, wi, ws,
);
}
@@ -312,8 +329,9 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
LAST_AUDIO_STALL_LOG.store(now_ts, Ordering::Relaxed);
let (rs, ri, ws, wi) = state.db.pool_stats();
warn!(
- "health_check: audio DB writes stalled — transcription active but last DB write {}s ago (pool exhaustion/lock contention likely) | pool: read={}/{} idle, write={}/{} idle",
+ "health_check: audio transcription writes stalled — transcription active but last DB write {}s ago ({}) | pool: read={}/{} idle, write={}/{} idle",
if audio_snap.last_db_write_ts > 0 { now_ts.saturating_sub(audio_snap.last_db_write_ts) } else { 0 },
+ suspected_stall_cause(ri, wi),
ri, rs, wi, ws,
);
}
@@ -473,7 +491,7 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
}
if vision_db_write_stalled {
detail_parts.push(format!(
- "vision DB writes stalled for {}s — capture running but data not saved (restart recommended)",
+ "vision DB writes stalled for {}s — capture running but DB writes not landing",
now_ts.saturating_sub(vision_snap.last_db_write_ts)
));
}
@@ -486,8 +504,11 @@ async fn health_check_inner(state: &Arc<AppState>) -> HealthCheckResponse {
));
}
if audio_db_write_stalled {
+ // Audio files themselves are persisted to disk + audio_chunks table
+ // before transcription is attempted. This stall reflects
+ // audio_transcriptions writes, not raw audio loss.
detail_parts.push(format!(
- "audio DB writes stalled for {}s — devices active but data not saved (restart recommended)",
+ "audio transcription writes stalled for {}s — audio captured, transcription not landing",
now_ts.saturating_sub(audio_snap.last_db_write_ts)
));
}