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: DB pool saturation stability — retry audio inserts, reduce compaction starvation, harden tray health

Louis Beaumont6d74ced39232
diff --git a/Cargo.toml b/Cargo.toml
index f762a74a8..41ebc719d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -6,7 +6,7 @@ exclude = ["apps/screenpipe-app-tauri/src-tauri", "crates/screenpipe-integration
resolver = "2"
[workspace.package]
-version = "0.3.183"
+version = "0.3.184"
authors = ["louis030195 <[email protected]>"]
description = ""
repository = "https://github.com/screenpipe/screenpipe"
diff --git a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
index c02b2bfc4..41e647cfb 100644
--- a/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
+++ b/apps/screenpipe-app-tauri/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "screenpipe-app"
-version = "2.2.126"
+version = "2.2.127"
description = "24/7 memory for your desktop. 100% local."
authors = ["you"]
license = ""
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/health.rs b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
index ee85d325a..3c4f44907 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/health.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/health.rs
@@ -12,9 +12,15 @@ use tracing::error;
/// The recording server needs time to load whisper models, FFmpeg, etc.
const STARTUP_GRACE_PERIOD: Duration = Duration::from_secs(30);
-/// Number of consecutive failures required before transitioning from Recording to Stopped/Error.
-/// This prevents transient timeouts or momentary server busyness from flickering the tray icon.
-const CONSECUTIVE_FAILURES_THRESHOLD: u32 = 3;
+/// Consecutive connection failures (refused/timeout) before showing Stopped.
+/// Must be high enough to ride out transient DB pool saturation, which can cause
+/// the health endpoint to timeout for 10-20 seconds without the server being down.
+const CONSECUTIVE_FAILURES_THRESHOLD: u32 = 30;
+
+/// Consecutive explicit "unhealthy"/"error" responses from a *responding* server
+/// before showing Error. Lower than connection failures because the server is
+/// actively confirming the problem, but still debounced to survive brief spikes.
+const CONSECUTIVE_UNHEALTHY_THRESHOLD: u32 = 10;
// Shared recording status that can be read by the tray menu
#[derive(Clone, Copy, PartialEq, Debug)]
@@ -122,6 +128,11 @@ struct HealthCheckResponse {
/// When transitioning away from Recording, we require `consecutive_failures`
/// to meet or exceed `failure_threshold` to prevent flickering caused by
/// transient timeouts or momentary server busyness.
+///
+/// "stale" responses (server responding but frame/audio timestamps are old)
+/// are treated as Recording — the server IS running, it's just behind on
+/// DB writes (e.g. pool saturation). Showing the error icon for this causes
+/// false alarms and user panic when data is actually still being captured.
fn decide_status(
health_result: &Result<HealthCheckResponse>,
elapsed_since_start: Duration,
@@ -129,15 +140,29 @@ fn decide_status(
ever_connected: bool,
consecutive_failures: u32,
failure_threshold: u32,
+ consecutive_unhealthy: u32,
+ unhealthy_threshold: u32,
current_status: RecordingStatus,
) -> RecordingStatus {
match health_result {
Ok(health) if health.status == "unhealthy" || health.status == "error" => {
- // Explicit unhealthy from the server — no debouncing needed,
- // the server itself is confirming the problem.
- RecordingStatus::Error
+ // Server is responding but explicitly reporting a problem.
+ // Debounce: require sustained unhealthy responses before showing Error,
+ // because transient DB pool pressure can cause brief unhealthy blips.
+ if consecutive_unhealthy >= unhealthy_threshold {
+ RecordingStatus::Error
+ } else if current_status == RecordingStatus::Recording {
+ RecordingStatus::Recording
+ } else {
+ current_status
+ }
+ }
+ Ok(_) => {
+ // Server is responding (healthy, degraded, or stale) — it's running.
+ // "stale" means timestamps are old but the server process is alive;
+ // this happens during DB pool saturation and resolves on its own.
+ RecordingStatus::Recording
}
- Ok(_) => RecordingStatus::Recording,
Err(_) => {
// Connection error — is the server still starting up?
if !ever_connected && elapsed_since_start < grace_period {
@@ -249,6 +274,7 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
let start_time = Instant::now();
let mut ever_connected = false;
let mut consecutive_failures: u32 = 0;
+ let mut consecutive_unhealthy: u32 = 0;
tokio::spawn(async move {
loop {
@@ -257,12 +283,27 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
let theme = dark_light::detect().unwrap_or(Mode::Dark);
let health_result = check_health(&client).await;
- // Track if we've ever successfully connected
- if health_result.is_ok() {
- ever_connected = true;
- consecutive_failures = 0;
- } else {
- consecutive_failures = consecutive_failures.saturating_add(1);
+ // Track consecutive failures (connection errors) and unhealthy responses separately.
+ // Connection errors = server unreachable (crash, restart, port conflict).
+ // Unhealthy = server responding but reporting a problem (DB issues, stalls).
+ match &health_result {
+ Ok(health)
+ if health.status == "unhealthy" || health.status == "error" =>
+ {
+ ever_connected = true;
+ consecutive_failures = 0;
+ consecutive_unhealthy = consecutive_unhealthy.saturating_add(1);
+ }
+ Ok(_) => {
+ ever_connected = true;
+ consecutive_failures = 0;
+ consecutive_unhealthy = 0;
+ }
+ Err(_) => {
+ consecutive_failures = consecutive_failures.saturating_add(1);
+ // Don't reset consecutive_unhealthy on connection error — if the server
+ // was unhealthy and then crashed, we want the counter to persist.
+ }
}
let current_status = get_recording_status();
@@ -273,6 +314,8 @@ pub async fn start_health_check(app: tauri::AppHandle) -> Result<()> {
ever_connected,
consecutive_failures,
CONSECUTIVE_FAILURES_THRESHOLD,
+ consecutive_unhealthy,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
current_status,
);
@@ -440,7 +483,7 @@ mod tests {
Err(anyhow::anyhow!("connection refused"))
}
- // Helper: call decide_status with default debounce params (no debouncing active)
+ // Helper: call decide_status with thresholds exceeded (no debouncing active)
// Used for tests that don't care about debouncing behavior
fn decide_no_debounce(
health_result: &Result<HealthCheckResponse>,
@@ -456,6 +499,8 @@ mod tests {
ever_connected,
CONSECUTIVE_FAILURES_THRESHOLD,
CONSECUTIVE_FAILURES_THRESHOLD,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Stopped,
)
}
@@ -465,23 +510,57 @@ mod tests {
#[test]
fn test_healthy_response_always_recording() {
let result = make_healthy_response();
- // Even at 0s elapsed, a healthy response means recording
let status =
decide_no_debounce(&result, Duration::from_secs(0), STARTUP_GRACE_PERIOD, false);
assert_eq!(status, RecordingStatus::Recording);
}
#[test]
- fn test_unhealthy_response_always_error() {
+ fn test_unhealthy_below_threshold_holds_recording() {
+ // Unhealthy responses below the threshold should NOT flip to Error
let result = make_unhealthy_response();
- let status =
- decide_no_debounce(&result, Duration::from_secs(0), STARTUP_GRACE_PERIOD, false);
- assert_eq!(status, RecordingStatus::Error);
+ let status = decide_status(
+ &result,
+ Duration::from_secs(60),
+ STARTUP_GRACE_PERIOD,
+ true,
+ 0,
+ CONSECUTIVE_FAILURES_THRESHOLD,
+ 1, // only 1 unhealthy — below threshold of 10
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Recording,
+ );
+ assert_eq!(
+ status,
+ RecordingStatus::Recording,
+ "single unhealthy response should NOT flip to Error"
+ );
+ }
+
+ #[test]
+ fn test_unhealthy_at_threshold_transitions_to_error() {
+ // Unhealthy responses at threshold should transition to Error
+ let result = make_unhealthy_response();
+ let status = decide_status(
+ &result,
+ Duration::from_secs(60),
+ STARTUP_GRACE_PERIOD,
+ true,
+ 0,
+ CONSECUTIVE_FAILURES_THRESHOLD,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Recording,
+ );
+ assert_eq!(
+ status,
+ RecordingStatus::Error,
+ "sustained unhealthy should transition to Error"
+ );
}
#[test]
fn test_connection_error_during_grace_period_is_starting() {
- // During the grace period, connection errors should show "starting"
let result = make_connection_error();
let status =
decide_no_debounce(&result, Duration::from_secs(0), STARTUP_GRACE_PERIOD, false);
@@ -516,28 +595,20 @@ mod tests {
false,
);
assert_eq!(status, RecordingStatus::Stopped);
-
- let result = make_connection_error();
- let status = decide_no_debounce(
- &result,
- Duration::from_secs(120),
- STARTUP_GRACE_PERIOD,
- false,
- );
- assert_eq!(status, RecordingStatus::Stopped);
}
#[test]
fn test_connection_error_after_previous_connection_is_stopped() {
- // If we connected before and now get enough consecutive errors, it's stopped
let result = make_connection_error();
let status = decide_status(
&result,
Duration::from_secs(5),
STARTUP_GRACE_PERIOD,
true,
- CONSECUTIVE_FAILURES_THRESHOLD, // enough failures
CONSECUTIVE_FAILURES_THRESHOLD,
+ CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
assert_eq!(status, RecordingStatus::Stopped);
@@ -547,12 +618,10 @@ mod tests {
fn test_grace_period_boundary() {
let grace = Duration::from_secs(30);
- // Exactly at boundary = still within grace
let result = make_connection_error();
let status = decide_no_debounce(&result, Duration::from_secs(29), grace, false);
assert_eq!(status, RecordingStatus::Starting);
- // One second past = no longer in grace
let result = make_connection_error();
let status = decide_no_debounce(&result, Duration::from_secs(30), grace, false);
assert_eq!(status, RecordingStatus::Stopped);
@@ -562,15 +631,16 @@ mod tests {
#[test]
fn test_single_failure_while_recording_holds_recording() {
- // THE KEY FIX: a single transient failure should NOT flip to Stopped
let result = make_connection_error();
let status = decide_status(
&result,
Duration::from_secs(60),
STARTUP_GRACE_PERIOD,
true,
- 1, // only 1 consecutive failure
+ 1,
CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
assert_eq!(
@@ -580,29 +650,8 @@ mod tests {
);
}
- #[test]
- fn test_two_failures_while_recording_holds_recording() {
- // 2 failures < threshold of 3 — still hold Recording
- let result = make_connection_error();
- let status = decide_status(
- &result,
- Duration::from_secs(60),
- STARTUP_GRACE_PERIOD,
- true,
- 2,
- CONSECUTIVE_FAILURES_THRESHOLD,
- RecordingStatus::Recording,
- );
- assert_eq!(
- status,
- RecordingStatus::Recording,
- "two failures while recording should NOT flip to Stopped"
- );
- }
-
#[test]
fn test_threshold_failures_while_recording_transitions_to_stopped() {
- // Exactly at threshold — now we transition
let result = make_connection_error();
let status = decide_status(
&result,
@@ -611,222 +660,153 @@ mod tests {
true,
CONSECUTIVE_FAILURES_THRESHOLD,
CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
assert_eq!(
status,
RecordingStatus::Stopped,
- "should transition to Stopped after reaching failure threshold"
+ "should transition to Stopped after 30s of consecutive failures"
);
}
#[test]
fn test_debounce_does_not_apply_when_not_recording() {
- // If we're already Stopped, failures don't get debounced
let result = make_connection_error();
let status = decide_status(
&result,
Duration::from_secs(60),
STARTUP_GRACE_PERIOD,
true,
- 1, // even just 1 failure
+ 1,
CONSECUTIVE_FAILURES_THRESHOLD,
- RecordingStatus::Stopped, // already stopped
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Stopped,
);
assert_eq!(status, RecordingStatus::Stopped);
}
#[test]
fn test_healthy_response_resets_after_failures() {
- // After failures, a healthy response immediately restores Recording
let result = make_healthy_response();
let status = decide_status(
&result,
Duration::from_secs(60),
STARTUP_GRACE_PERIOD,
true,
- 2, // had some failures
+ 2,
CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
assert_eq!(status, RecordingStatus::Recording);
}
#[test]
- fn test_unhealthy_response_bypasses_debounce() {
- // An explicit "unhealthy" from the server should always be Error,
- // regardless of debounce state
- let result = make_unhealthy_response();
+ fn test_pool_saturation_scenario() {
+ // Simulate DB pool saturation: server responds but with unhealthy status
+ // for a few seconds, then recovers. Tray should stay green the whole time.
+ let grace = Duration::from_secs(30);
+
+ // tick 1-5: unhealthy responses (below threshold of 10)
+ for i in 1..=5 {
+ let status = decide_status(
+ &make_unhealthy_response(),
+ Duration::from_secs(60),
+ grace,
+ true,
+ 0,
+ CONSECUTIVE_FAILURES_THRESHOLD,
+ i,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Recording,
+ );
+ assert_eq!(
+ status,
+ RecordingStatus::Recording,
+ "unhealthy tick {i}: should hold Recording (below threshold)"
+ );
+ }
+
+ // tick 6: server recovers
let status = decide_status(
- &result,
- Duration::from_secs(60),
- STARTUP_GRACE_PERIOD,
+ &make_healthy_response(),
+ Duration::from_secs(65),
+ grace,
true,
- 0, // no failures yet
+ 0,
CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
- assert_eq!(
- status,
- RecordingStatus::Error,
- "explicit unhealthy should bypass debounce"
- );
+ assert_eq!(status, RecordingStatus::Recording);
}
#[test]
fn test_flicker_scenario_simulation() {
- // Simulate the exact scenario from the user report:
- // Server is running, but under load causes intermittent timeouts
+ // Server under load: intermittent timeouts that never exceed threshold
let grace = Duration::from_secs(30);
let threshold = CONSECUTIVE_FAILURES_THRESHOLD;
- let mut current = RecordingStatus::Recording;
- let mut consecutive_failures: u32 = 0;
-
- // tick 1: healthy
- let status = decide_status(
- &make_healthy_response(),
- Duration::from_secs(60),
- grace,
- true,
- 0,
- threshold,
- current,
- );
- assert_eq!(status, RecordingStatus::Recording);
- current = status;
- consecutive_failures = 0;
- // tick 2: timeout (failure 1)
- consecutive_failures += 1;
+ // 10 consecutive failures — still below threshold of 30
let status = decide_status(
&make_connection_error(),
- Duration::from_secs(61),
+ Duration::from_secs(70),
grace,
true,
- consecutive_failures,
+ 10,
threshold,
- current,
- );
- assert_eq!(
- status,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
- "tick 2: should hold Recording after 1 failure"
- );
- current = status;
-
- // tick 3: healthy again — reset
- consecutive_failures = 0;
- let status = decide_status(
- &make_healthy_response(),
- Duration::from_secs(62),
- grace,
- true,
- consecutive_failures,
- threshold,
- current,
- );
- assert_eq!(status, RecordingStatus::Recording, "tick 3: healthy again");
- current = status;
-
- // tick 4: timeout (failure 1)
- consecutive_failures += 1;
- let status = decide_status(
- &make_connection_error(),
- Duration::from_secs(63),
- grace,
- true,
- consecutive_failures,
- threshold,
- current,
);
assert_eq!(
status,
RecordingStatus::Recording,
- "tick 4: should hold Recording"
+ "10s of failures should NOT flip to Stopped (threshold is 30)"
);
- current = status;
- // tick 5: timeout (failure 2)
- consecutive_failures += 1;
- let status = decide_status(
- &make_connection_error(),
- Duration::from_secs(64),
- grace,
- true,
- consecutive_failures,
- threshold,
- current,
- );
- assert_eq!(
- status,
- RecordingStatus::Recording,
- "tick 5: should still hold Recording"
- );
- current = status;
-
- // tick 6: healthy — all good
- consecutive_failures = 0;
+ // Back to healthy
let status = decide_status(
&make_healthy_response(),
- Duration::from_secs(65),
+ Duration::from_secs(71),
grace,
true,
- consecutive_failures,
+ 0,
threshold,
- current,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Recording,
);
- assert_eq!(status, RecordingStatus::Recording, "tick 6: healthy");
-
- // The user would have seen NO flickering through this whole sequence!
+ assert_eq!(status, RecordingStatus::Recording);
}
#[test]
fn test_real_crash_still_detected() {
- // Server truly crashes — consecutive failures exceed threshold
+ // Server truly crashes — 30 consecutive seconds of failures
let grace = Duration::from_secs(30);
let threshold = CONSECUTIVE_FAILURES_THRESHOLD;
- let mut current = RecordingStatus::Recording;
- // Failure 1
+ // At threshold (30 failures = 30s) — transitions to Stopped
let status = decide_status(
&make_connection_error(),
- Duration::from_secs(60),
+ Duration::from_secs(90),
grace,
true,
- 1,
threshold,
- current,
- );
- assert_eq!(status, RecordingStatus::Recording);
- current = status;
-
- // Failure 2
- let status = decide_status(
- &make_connection_error(),
- Duration::from_secs(61),
- grace,
- true,
- 2,
threshold,
- current,
- );
- assert_eq!(status, RecordingStatus::Recording);
- current = status;
-
- // Failure 3 — at threshold, transitions
- let status = decide_status(
- &make_connection_error(),
- Duration::from_secs(62),
- grace,
- true,
- 3,
- threshold,
- current,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
+ RecordingStatus::Recording,
);
assert_eq!(
status,
RecordingStatus::Stopped,
- "should detect real crash after threshold failures"
+ "should detect real crash after 30s of failures"
);
}
@@ -834,30 +814,22 @@ mod tests {
#[test]
fn test_starting_shows_healthy_icon() {
- let key = status_to_icon_key(RecordingStatus::Starting);
- assert_eq!(key, "starting");
- assert!(!is_unhealthy_icon(key));
+ assert!(!is_unhealthy_icon(status_to_icon_key(RecordingStatus::Starting)));
}
#[test]
fn test_recording_shows_healthy_icon() {
- let key = status_to_icon_key(RecordingStatus::Recording);
- assert_eq!(key, "healthy");
- assert!(!is_unhealthy_icon(key));
+ assert!(!is_unhealthy_icon(status_to_icon_key(RecordingStatus::Recording)));
}
#[test]
fn test_stopped_shows_failed_icon() {
- let key = status_to_icon_key(RecordingStatus::Stopped);
- assert_eq!(key, "error");
- assert!(is_unhealthy_icon(key));
+ assert!(is_unhealthy_icon(status_to_icon_key(RecordingStatus::Stopped)));
}
#[test]
fn test_error_shows_failed_icon() {
- let key = status_to_icon_key(RecordingStatus::Error);
- assert_eq!(key, "unhealthy");
- assert!(is_unhealthy_icon(key));
+ assert!(is_unhealthy_icon(status_to_icon_key(RecordingStatus::Error)));
}
// ==================== realistic boot sequence simulation ====================
@@ -866,7 +838,6 @@ mod tests {
fn test_boot_sequence_no_false_positive() {
let grace = Duration::from_secs(30);
- // t=0s: first health check, server not started yet
let status = decide_no_debounce(
&make_connection_error(),
Duration::from_secs(0),
@@ -874,22 +845,8 @@ mod tests {
false,
);
assert_eq!(status, RecordingStatus::Starting);
- assert!(
- !is_unhealthy_icon(status_to_icon_key(status)),
- "should NOT show failed icon at boot"
- );
-
- // t=1s: still starting
- let status = decide_no_debounce(
- &make_connection_error(),
- Duration::from_secs(1),
- grace,
- false,
- );
- assert_eq!(status, RecordingStatus::Starting);
assert!(!is_unhealthy_icon(status_to_icon_key(status)));
- // t=5s: server is up, healthy response
let status = decide_no_debounce(
&make_healthy_response(),
Duration::from_secs(5),
@@ -904,7 +861,7 @@ mod tests {
fn test_server_crash_after_boot_shows_error() {
let grace = Duration::from_secs(30);
- // Server was healthy, now crashes — after threshold failures
+ // Server was healthy, now crashes — after threshold failures (30s)
let status = decide_status(
&make_connection_error(),
Duration::from_secs(60),
@@ -912,6 +869,8 @@ mod tests {
true,
CONSECUTIVE_FAILURES_THRESHOLD,
CONSECUTIVE_FAILURES_THRESHOLD,
+ 0,
+ CONSECUTIVE_UNHEALTHY_THRESHOLD,
RecordingStatus::Recording,
);
assert_eq!(status, RecordingStatus::Stopped);
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
index 0af43651a..44a187181 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -10,7 +10,7 @@ use serde_json::json;
use std::env;
use std::path::PathBuf;
use std::str::FromStr;
-use std::sync::atomic::AtomicBool;
+use std::sync::atomic::{AtomicBool, AtomicU64};
use std::sync::Arc;
use tauri::Emitter;
use tauri::Manager;
@@ -1421,6 +1421,7 @@ async fn main() {
let recording_state = RecordingState {
handle: Arc::new(tokio::sync::Mutex::new(None)),
is_starting: Arc::new(AtomicBool::new(false)),
+ last_spawn_epoch: Arc::new(AtomicU64::new(0)),
};
let pi_state = pi::PiState(Arc::new(tokio::sync::Mutex::new(pi::PiPool::new())));
let suggestions_state = suggestions::SuggestionsState::new();
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
index 99ee23f02..ce831b9ad 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/recording.rs
@@ -7,17 +7,23 @@ use crate::embedded_server::{start_embedded_server, EmbeddedServerHandle};
use crate::permissions::do_permissions_check;
use crate::store::SettingsStore;
use serde::{Deserialize, Serialize};
-use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use tauri::{Emitter, State};
use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};
+/// Minimum seconds between consecutive stop→spawn cycles.
+/// Prevents restart spam from cascading permission recovery or settings changes.
+const RESTART_COOLDOWN_SECS: u64 = 30;
+
/// State holding the embedded server handle
pub struct RecordingState {
pub handle: Arc<Mutex<Option<EmbeddedServerHandle>>>,
/// True while a server start is in progress (prevents race between main.rs boot and frontend)
pub is_starting: Arc<AtomicBool>,
+ /// Epoch seconds of last successful spawn — enforces cooldown between restarts
+ pub last_spawn_epoch: Arc<AtomicU64>,
}
#[derive(Debug, Serialize, Deserialize, Clone, specta::Type)]
@@ -142,6 +148,22 @@ pub async fn spawn_screenpipe(
) -> Result<(), String> {
info!("Starting screenpipe server");
+ // Enforce cooldown between restarts to prevent cascading restart spam.
+ // Permission recovery and settings changes can trigger rapid stop→spawn cycles
+ // that starve the DB pool and cause data loss.
+ let now_epoch = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ let last_spawn = state.last_spawn_epoch.load(Ordering::SeqCst);
+ if last_spawn > 0 && now_epoch.saturating_sub(last_spawn) < RESTART_COOLDOWN_SECS {
+ let remaining = RESTART_COOLDOWN_SECS - now_epoch.saturating_sub(last_spawn);
+ warn!(
+ "Restart cooldown active ({remaining}s remaining). Skipping spawn to prevent restart spam."
+ );
+ return Ok(());
+ }
+
let store = SettingsStore::get(&app).ok().flatten().unwrap_or_default();
let port = store.port;
let health_url = format!("http://localhost:{}/health", port);
@@ -370,6 +392,12 @@ pub async fn spawn_screenpipe(
match result_rx.await {
Ok(Ok(())) => {
info!("Screenpipe server started successfully");
+ // Record spawn time for cooldown enforcement
+ let spawn_epoch = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_secs();
+ state.last_spawn_epoch.store(spawn_epoch, Ordering::SeqCst);
// is_starting stays true — it's cleared when stop_screenpipe() is called
// This prevents another spawn_screenpipe from racing with the running server
Ok(())
diff --git a/crates/screenpipe-audio/src/audio_manager/manager.rs b/crates/screenpipe-audio/src/audio_manager/manager.rs
index 9a722075d..2f1e87c83 100644
--- a/crates/screenpipe-audio/src/audio_manager/manager.rs
+++ b/crates/screenpipe-audio/src/audio_manager/manager.rs
@@ -527,8 +527,26 @@ impl AudioManager {
// even if transcription is deferred. No transcription yet — just the chunk.
// Use the original capture timestamp so audio appears at the correct
// position on the timeline, not when processing happened.
- if let Err(e) = db.insert_audio_chunk(&path, capture_dt).await {
- error!("failed to insert audio chunk into db: {:?}", e);
+ // Retry DB insertion with backoff to survive transient pool saturation.
+ // Without this, audio files are written to disk but orphaned from the DB,
+ // causing silent data loss on the timeline.
+ let mut inserted = false;
+ for retry in 0..3u32 {
+ match db.insert_audio_chunk(&path, capture_dt).await {
+ Ok(_) => { inserted = true; break; }
+ Err(e) => {
+ warn!(
+ "failed to insert audio chunk into db (attempt {}/3): {:?}",
+ retry + 1, e
+ );
+ if retry < 2 {
+ tokio::time::sleep(std::time::Duration::from_millis(500 * (retry as u64 + 1))).await;
+ }
+ }
+ }
+ }
+ if !inserted {
+ error!("audio chunk DB insert failed after 3 retries, data may be missing from timeline: {}", path);
}
Some(path)
}
diff --git a/crates/screenpipe-audio/src/transcription/transcription_result.rs b/crates/screenpipe-audio/src/transcription/transcription_result.rs
index 20e5f4915..94c82842a 100644
--- a/crates/screenpipe-audio/src/transcription/transcription_result.rs
+++ b/crates/screenpipe-audio/src/transcription/transcription_result.rs
@@ -7,7 +7,7 @@ use std::sync::Arc;
use chrono::{DateTime, Utc};
use screenpipe_core::pii_removal::remove_pii;
use screenpipe_db::{DatabaseManager, Speaker};
-use tracing::{debug, error};
+use tracing::{debug, error, warn};
use crate::core::engine::AudioTranscriptionEngine;
@@ -120,37 +120,52 @@ pub async fn process_transcription_result(
// if smart mode deferred transcription by 20 minutes.
let capture_ts: Option<DateTime<Utc>> = DateTime::from_timestamp(result.timestamp as i64, 0);
- match db
- .insert_audio_chunk_and_transcription(
- &result.path,
- &transcription,
- 0,
- &transcription_engine,
- &screenpipe_db::AudioDevice {
- name: result.input.device.name.clone(),
- device_type: match result.input.device.device_type {
- crate::core::device::DeviceType::Input => screenpipe_db::DeviceType::Input,
- crate::core::device::DeviceType::Output => screenpipe_db::DeviceType::Output,
+ // Retry DB insertion with backoff to survive transient pool saturation.
+ // Without this, transcribed audio is silently dropped from the timeline.
+ for retry in 0..3u32 {
+ match db
+ .insert_audio_chunk_and_transcription(
+ &result.path,
+ &transcription,
+ 0,
+ &transcription_engine,
+ &screenpipe_db::AudioDevice {
+ name: result.input.device.name.clone(),
+ device_type: match result.input.device.device_type {
+ crate::core::device::DeviceType::Input => screenpipe_db::DeviceType::Input,
+ crate::core::device::DeviceType::Output => screenpipe_db::DeviceType::Output,
+ },
},
- },
- Some(speaker.id),
- Some(result.start_time),
- Some(result.end_time),
- capture_ts,
- )
- .await
- {
- Ok(audio_chunk_id) => {
- debug!(
- "Inserted audio chunk+transcription for device {} using {}",
- result.input.device, transcription_engine
- );
- chunk_id = Some(audio_chunk_id);
+ Some(speaker.id),
+ Some(result.start_time),
+ Some(result.end_time),
+ capture_ts,
+ )
+ .await
+ {
+ Ok(audio_chunk_id) => {
+ debug!(
+ "Inserted audio chunk+transcription for device {} using {}",
+ result.input.device, transcription_engine
+ );
+ chunk_id = Some(audio_chunk_id);
+ break;
+ }
+ Err(e) => {
+ if retry < 2 {
+ warn!(
+ "Failed to insert audio chunk+transcription for device {} (attempt {}/3): {}, retrying...",
+ result.input.device, retry + 1, e
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(500 * (retry as u64 + 1))).await;
+ } else {
+ error!(
+ "Failed to insert audio chunk+transcription for device {} after 3 retries: {}",
+ result.input.device, e
+ );
+ }
+ }
}
- Err(e) => error!(
- "Failed to insert audio chunk+transcription for device {}: {}",
- result.input.device, e
- ),
}
Ok(chunk_id.map(|id| AudioInsertResult {
audio_chunk_id: id,
diff --git a/crates/screenpipe-engine/src/snapshot_compaction.rs b/crates/screenpipe-engine/src/snapshot_compaction.rs
index 89ea58ea0..78accb7ad 100644
--- a/crates/screenpipe-engine/src/snapshot_compaction.rs
+++ b/crates/screenpipe-engine/src/snapshot_compaction.rs
@@ -302,7 +302,9 @@ async fn compact_chunk(
// Only update frames that were actually encoded into the video.
// Use their real video position as offset_index (not array index).
- let mut tx = db.begin_immediate_with_retry().await?;
+ // Process in separate transactions per batch to avoid holding the write
+ // semaphore for too long, which starves audio/frame insertion and causes
+ // PoolTimedOut errors (data loss).
for batch in encoded_frames.chunks(100) {
let ids: Vec<i64> = batch.iter().map(|(id, _)| *id).collect();
let placeholders: Vec<String> = ids.iter().map(|_| "?".to_string()).collect();
@@ -320,13 +322,16 @@ async fn compact_chunk(
placeholders.join(",")
);
+ let mut tx = db.begin_immediate_with_retry().await?;
let mut query = sqlx::query(&sql).bind(chunk_id);
for id in &ids {
query = query.bind(id);
}
query.execute(&mut **tx.conn()).await?;
+ tx.commit().await?;
+ // Yield briefly between batches so audio/frame insertions can acquire the write semaphore
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
}
- tx.commit().await?;
// Step 3: Delete source JPEGs (safe — DB already points to MP4)
let mut deleted = 0u32;