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

perf: cache monitor handle, add video_chunks index, WAL tuning, capture retry with refresh (#2197)

Louis Beaumont920bbcfd2ac2
diff --git a/crates/screenpipe-db/src/db.rs b/crates/screenpipe-db/src/db.rs
index 7e387f3c9..b8293722b 100644
--- a/crates/screenpipe-db/src/db.rs
+++ b/crates/screenpipe-db/src/db.rs
@@ -124,7 +124,12 @@ impl DatabaseManager {
.pragma("journal_mode", "WAL")
.pragma("cache_size", "-64000") // 64 MB page cache
.pragma("mmap_size", "268435456") // 256 MB memory-mapped I/O
- .pragma("temp_store", "MEMORY");
+ .pragma("temp_store", "MEMORY")
+ // Checkpoint after 4000 pages (~16MB) instead of default 1000 (~4MB).
+ // Reduces checkpoint stalls during write bursts — checkpoint happens
+ // during idle periods instead. WAL grows to ~16MB max (+12MB).
+ // Crash recovery: ~200ms replay at most.
+ .pragma("wal_autocheckpoint", "4000");
let pool = SqlitePoolOptions::new()
// SQLite only allows a single writer; keep the pool modest to reduce write contention.
diff --git a/crates/screenpipe-db/src/migrations/20260207000000_index_video_chunks_device_name.sql b/crates/screenpipe-db/src/migrations/20260207000000_index_video_chunks_device_name.sql
new file mode 100644
index 000000000..3de449681
--- /dev/null
+++ b/crates/screenpipe-db/src/migrations/20260207000000_index_video_chunks_device_name.sql
@@ -0,0 +1,11 @@
+-- Add missing index on video_chunks.device_name
+-- This query runs inside BEGIN IMMEDIATE transactions on every frame insert:
+-- SELECT id, file_path FROM video_chunks WHERE device_name = ?1 ORDER BY id DESC LIMIT 1
+-- Without this index, it's a full table scan holding the write lock.
+-- On a DB with weeks of data (thousands of video_chunks rows), this causes
+-- multi-second stalls and cascading contention.
+CREATE INDEX IF NOT EXISTS idx_video_chunks_device_name ON video_chunks(device_name);
+
+-- Also add a compound index for the exact query pattern (device_name + id DESC)
+-- SQLite can use this to satisfy both the WHERE and ORDER BY in a single index scan.
+CREATE INDEX IF NOT EXISTS idx_video_chunks_device_name_id ON video_chunks(device_name, id DESC);
diff --git a/crates/screenpipe-vision/src/core.rs b/crates/screenpipe-vision/src/core.rs
index d8b07462e..b362e1658 100644
--- a/crates/screenpipe-vision/src/core.rs
+++ b/crates/screenpipe-vision/src/core.rs
@@ -187,14 +187,17 @@ pub async fn continuous_capture(
"continuous_capture: Starting using monitor: {:?}",
monitor_id
);
- // 1. Get monitor
- let monitor = match get_monitor_by_id(monitor_id).await {
+ // 1. Get monitor (mutable so we can refresh() the cached handle on failure)
+ let mut monitor = match get_monitor_by_id(monitor_id).await {
Some(m) => m,
None => {
error!("Monitor not found");
return Err(ContinuousCaptureError::MonitorNotFound);
}
};
+ let mut consecutive_capture_failures: u32 = 0;
+ const MAX_CAPTURE_RETRIES: u32 = 3;
+ const MAX_CONSECUTIVE_FAILURES: u32 = 30;
// Suppress unused variable warning when feature is disabled
#[cfg(not(feature = "adaptive-fps"))]
@@ -205,16 +208,70 @@ pub async fn continuous_capture(
// Window capture is deferred until after frame comparison to skip
// expensive per-window work on unchanged frames.
let captured_at = Utc::now();
- let (image, _capture_duration) =
- match capture_monitor_image(&monitor).await {
- Ok(result) => result,
- Err(e) => {
- debug!("error capturing screenshot: {}", e);
- return Err(ContinuousCaptureError::ErrorCapturingScreenshot(
- e.to_string(),
- ));
+ let (image, _capture_duration) = {
+ let mut last_err = None;
+ let mut captured = None;
+
+ for attempt in 0..=MAX_CAPTURE_RETRIES {
+ match capture_monitor_image(&monitor).await {
+ Ok(result) => {
+ if attempt > 0 {
+ debug!(
+ "capture succeeded after {} retries for monitor {}",
+ attempt, monitor_id
+ );
+ }
+ consecutive_capture_failures = 0;
+ captured = Some(result);
+ break;
+ }
+ Err(e) => {
+ last_err = Some(e);
+ if attempt < MAX_CAPTURE_RETRIES {
+ // Refresh the cached monitor handle — resolution may have
+ // changed, or the display may have been reconnected.
+ debug!(
+ "capture failed for monitor {} (attempt {}/{}), refreshing handle",
+ monitor_id,
+ attempt + 1,
+ MAX_CAPTURE_RETRIES
+ );
+ if let Err(refresh_err) = monitor.refresh().await {
+ debug!("monitor refresh failed: {}", refresh_err);
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
}
- };
+ }
+
+ match captured {
+ Some(result) => result,
+ None => {
+ consecutive_capture_failures += 1;
+ let err = last_err.unwrap();
+ if consecutive_capture_failures >= MAX_CONSECUTIVE_FAILURES {
+ error!(
+ "monitor {} failed {} consecutive captures, bailing: {}",
+ monitor_id, consecutive_capture_failures, err
+ );
+ return Err(ContinuousCaptureError::ErrorCapturingScreenshot(
+ err.to_string(),
+ ));
+ }
+ debug!(
+ "all {} capture retries failed for monitor {} ({}/{}): {}",
+ MAX_CAPTURE_RETRIES,
+ monitor_id,
+ consecutive_capture_failures,
+ MAX_CONSECUTIVE_FAILURES,
+ err
+ );
+ tokio::time::sleep(interval).await;
+ continue;
+ }
+ }
+ };
// 4. Optimized frame comparison: downscales once (proportional to preserve
// ultrawide aspect ratios), hashes the thumbnail, then compares histograms.
diff --git a/crates/screenpipe-vision/src/monitor.rs b/crates/screenpipe-vision/src/monitor.rs
index b4be26931..1b8abfbd5 100644
--- a/crates/screenpipe-vision/src/monitor.rs
+++ b/crates/screenpipe-vision/src/monitor.rs
@@ -41,6 +41,16 @@ pub struct SafeMonitor {
monitor_data: Arc<MonitorData>,
#[cfg(target_os = "macos")]
use_sck: bool,
+ /// Cached native monitor handle to avoid re-enumerating all monitors on every frame.
+ /// SckMonitor/XcapMonitor are lightweight Clone data structs (just display_id + dimensions).
+ /// The capture methods use the display_id internally, so caching is safe.
+ /// On capture failure, call `refresh()` to re-enumerate (monitor may have changed).
+ #[cfg(target_os = "macos")]
+ cached_sck: Option<SckMonitor>,
+ #[cfg(target_os = "macos")]
+ cached_xcap: Option<XcapMonitor>,
+ #[cfg(not(target_os = "macos"))]
+ cached_xcap: Option<XcapMonitor>,
}
#[derive(Clone, Debug)]
@@ -110,6 +120,8 @@ impl SafeMonitor {
monitor_id,
monitor_data,
use_sck: true,
+ cached_sck: Some(monitor),
+ cached_xcap: None,
}
}
@@ -130,6 +142,8 @@ impl SafeMonitor {
monitor_id,
monitor_data,
use_sck: false,
+ cached_sck: None,
+ cached_xcap: Some(monitor),
}
}
@@ -149,22 +163,38 @@ impl SafeMonitor {
Self {
monitor_id,
monitor_data,
+ cached_xcap: Some(monitor),
}
}
+ /// Capture a screenshot using the cached monitor handle.
+ ///
+ /// Uses `tokio::task::spawn_blocking` instead of `std::thread::spawn` to reuse
+ /// the tokio blocking thread pool (bounded concurrency, no thread creation overhead).
+ ///
+ /// Uses the cached native monitor handle directly — no `Monitor::all()` re-enumeration.
+ /// If the cache is empty (shouldn't happen in normal flow), falls back to enumeration.
#[cfg(target_os = "macos")]
pub async fn capture_image(&self) -> Result<DynamicImage> {
let monitor_id = self.monitor_id;
let use_sck = self.use_sck;
+ let cached_sck = self.cached_sck.clone();
+ let cached_xcap = self.cached_xcap.clone();
- let image = std::thread::spawn(move || -> Result<DynamicImage> {
+ let image = tokio::task::spawn_blocking(move || -> Result<DynamicImage> {
if use_sck {
- // Use sck-rs (ScreenCaptureKit)
- let monitor = SckMonitor::all()
- .map_err(Error::from)?
- .into_iter()
- .find(|m| m.id() == monitor_id)
- .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
+ // Use cached sck-rs handle, fall back to enumeration if not cached
+ let monitor = match cached_sck {
+ Some(m) => m,
+ None => {
+ tracing::debug!("sck-rs cache miss for monitor {}, re-enumerating", monitor_id);
+ SckMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id() == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?
+ }
+ };
if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
@@ -175,12 +205,18 @@ impl SafeMonitor {
.map_err(|e| anyhow::anyhow!("{}", e))
.map(DynamicImage::ImageRgba8)
} else {
- // Use xcap (fallback for older macOS)
- let monitor = XcapMonitor::all()
- .map_err(Error::from)?
- .into_iter()
- .find(|m| m.id().unwrap_or(0) == monitor_id)
- .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
+ // Use cached xcap handle, fall back to enumeration if not cached
+ let monitor = match cached_xcap {
+ Some(m) => m,
+ None => {
+ tracing::debug!("xcap cache miss for monitor {}, re-enumerating", monitor_id);
+ XcapMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id().unwrap_or(0) == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?
+ }
+ };
if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
@@ -192,8 +228,8 @@ impl SafeMonitor {
.map(DynamicImage::ImageRgba8)
}
})
- .join()
- .unwrap()?;
+ .await
+ .map_err(|e| anyhow::anyhow!("capture task panicked: {}", e))??;
Ok(image)
}
@@ -201,13 +237,20 @@ impl SafeMonitor {
#[cfg(not(target_os = "macos"))]
pub async fn capture_image(&self) -> Result<DynamicImage> {
let monitor_id = self.monitor_id;
-
- let image = std::thread::spawn(move || -> Result<DynamicImage> {
- let monitor = XcapMonitor::all()
- .map_err(Error::from)?
- .into_iter()
- .find(|m| m.id().unwrap_or(0) == monitor_id)
- .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?;
+ let cached_xcap = self.cached_xcap.clone();
+
+ let image = tokio::task::spawn_blocking(move || -> Result<DynamicImage> {
+ let monitor = match cached_xcap {
+ Some(m) => m,
+ None => {
+ tracing::debug!("xcap cache miss for monitor {}, re-enumerating", monitor_id);
+ XcapMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id().unwrap_or(0) == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor not found"))?
+ }
+ };
if monitor.width().unwrap_or(0) == 0 || monitor.height().unwrap_or(0) == 0 {
return Err(anyhow::anyhow!("Invalid monitor dimensions"));
@@ -218,12 +261,96 @@ impl SafeMonitor {
.map_err(Error::from)
.map(DynamicImage::ImageRgba8)
})
- .join()
- .unwrap()?;
+ .await
+ .map_err(|e| anyhow::anyhow!("capture task panicked: {}", e))??;
Ok(image)
}
+ /// Refresh the cached monitor handle by re-enumerating all monitors.
+ /// Call this after a capture failure — the monitor may have been reconnected
+ /// with different properties (resolution change, etc.).
+ #[cfg(target_os = "macos")]
+ pub async fn refresh(&mut self) -> Result<()> {
+ let monitor_id = self.monitor_id;
+ let use_sck = self.use_sck;
+
+ let refreshed = tokio::task::spawn_blocking(move || -> Result<(Option<SckMonitor>, Option<XcapMonitor>, MonitorData)> {
+ if use_sck {
+ let monitor = SckMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id() == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor {} not found during refresh", monitor_id))?;
+
+ let data = MonitorData {
+ width: monitor.width().unwrap_or(0),
+ height: monitor.height().unwrap_or(0),
+ x: monitor.x(),
+ y: monitor.y(),
+ name: monitor.name().to_string(),
+ is_primary: monitor.is_primary(),
+ };
+ Ok((Some(monitor), None, data))
+ } else {
+ let monitor = XcapMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id().unwrap_or(0) == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor {} not found during refresh", monitor_id))?;
+
+ let data = MonitorData {
+ width: monitor.width().unwrap_or(0),
+ height: monitor.height().unwrap_or(0),
+ x: monitor.x().unwrap_or(0),
+ y: monitor.y().unwrap_or(0),
+ name: monitor.name().unwrap_or_default().to_string(),
+ is_primary: monitor.is_primary().unwrap_or(false),
+ };
+ Ok((None, Some(monitor), data))
+ }
+ })
+ .await
+ .map_err(|e| anyhow::anyhow!("refresh task panicked: {}", e))??;
+
+ self.cached_sck = refreshed.0;
+ self.cached_xcap = refreshed.1;
+ self.monitor_data = Arc::new(refreshed.2);
+ tracing::debug!("Refreshed monitor {} cache", self.monitor_id);
+ Ok(())
+ }
+
+ /// Refresh the cached monitor handle by re-enumerating all monitors.
+ #[cfg(not(target_os = "macos"))]
+ pub async fn refresh(&mut self) -> Result<()> {
+ let monitor_id = self.monitor_id;
+
+ let refreshed = tokio::task::spawn_blocking(move || -> Result<(XcapMonitor, MonitorData)> {
+ let monitor = XcapMonitor::all()
+ .map_err(Error::from)?
+ .into_iter()
+ .find(|m| m.id().unwrap_or(0) == monitor_id)
+ .ok_or_else(|| anyhow::anyhow!("Monitor {} not found during refresh", monitor_id))?;
+
+ let data = MonitorData {
+ width: monitor.width().unwrap_or(0),
+ height: monitor.height().unwrap_or(0),
+ x: monitor.x().unwrap_or(0),
+ y: monitor.y().unwrap_or(0),
+ name: monitor.name().unwrap_or_default().to_string(),
+ is_primary: monitor.is_primary().unwrap_or(false),
+ };
+ Ok((monitor, data))
+ })
+ .await
+ .map_err(|e| anyhow::anyhow!("refresh task panicked: {}", e))??;
+
+ self.cached_xcap = Some(refreshed.0);
+ self.monitor_data = Arc::new(refreshed.1);
+ tracing::debug!("Refreshed monitor {} cache", self.monitor_id);
+ Ok(())
+ }
+
pub fn id(&self) -> u32 {
self.monitor_id
}
diff --git a/crates/screenpipe-vision/tests/capture_retry_test.rs b/crates/screenpipe-vision/tests/capture_retry_test.rs
new file mode 100644
index 000000000..53b253ef0
--- /dev/null
+++ b/crates/screenpipe-vision/tests/capture_retry_test.rs
@@ -0,0 +1,492 @@
+/// Rigorous tests for the capture retry + refresh logic in continuous_capture.
+///
+/// The retry pattern (from core.rs):
+/// - Up to MAX_CAPTURE_RETRIES (3) attempts per capture cycle
+/// - On failure, calls monitor.refresh() then retries after 100ms
+/// - On all retries exhausted: increments consecutive_capture_failures
+/// - After MAX_CONSECUTIVE_FAILURES (30) consecutive all-retry-exhausted cycles, returns Err
+/// - On any success: resets consecutive_capture_failures to 0
+///
+/// We replicate the exact control flow here with a mock capture function
+/// to verify every branch.
+
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::Arc;
+
+const MAX_CAPTURE_RETRIES: u32 = 3;
+const MAX_CONSECUTIVE_FAILURES: u32 = 30;
+
+/// Outcome of a single capture cycle (one iteration of the outer loop)
+#[derive(Debug, PartialEq)]
+enum CycleOutcome {
+ /// Capture succeeded (possibly after retries)
+ Success { attempts_used: u32 },
+ /// All retries exhausted, but haven't hit consecutive failure limit yet
+ RetryExhausted { consecutive_failures: u32 },
+ /// Hit the consecutive failure limit — bail
+ Bail { consecutive_failures: u32 },
+}
+
+/// Replicate the exact retry logic from continuous_capture.
+/// `capture_fn` returns Ok(()) on success, Err on failure.
+/// `refresh_fn` is called between retries.
+/// Returns the outcome of a single capture cycle.
+fn run_capture_cycle<F: ?Sized, R: ?Sized>(
+ capture_fn: &mut F,
+ refresh_fn: &mut R,
+ consecutive_failures: &mut u32,
+) -> CycleOutcome
+where
+ F: FnMut() -> Result<(), String>,
+ R: FnMut() -> Result<(), String>,
+{
+ let mut captured = false;
+ let mut attempts_used = 0;
+
+ // Exact replica of the for loop in core.rs
+ for attempt in 0..=MAX_CAPTURE_RETRIES {
+ match capture_fn() {
+ Ok(()) => {
+ *consecutive_failures = 0;
+ captured = true;
+ attempts_used = attempt + 1;
+ break;
+ }
+ Err(_e) => {
+ if attempt < MAX_CAPTURE_RETRIES {
+ // refresh() between retries
+ let _ = refresh_fn();
+ }
+ }
+ }
+ }
+
+ if captured {
+ CycleOutcome::Success { attempts_used }
+ } else {
+ *consecutive_failures += 1;
+ if *consecutive_failures >= MAX_CONSECUTIVE_FAILURES {
+ CycleOutcome::Bail {
+ consecutive_failures: *consecutive_failures,
+ }
+ } else {
+ CycleOutcome::RetryExhausted {
+ consecutive_failures: *consecutive_failures,
+ }
+ }
+ }
+}
+
+// =============================================================================
+// Tests for the retry logic
+// =============================================================================
+
+#[test]
+fn test_immediate_success_resets_consecutive_failures() {
+ let mut consecutive = 5; // simulate prior failures
+ let mut capture = || Ok(());
+ let mut refresh = || Ok(());
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(outcome, CycleOutcome::Success { attempts_used: 1 });
+ assert_eq!(consecutive, 0, "consecutive failures must reset on success");
+}
+
+#[test]
+fn test_success_on_second_attempt() {
+ let call_count = AtomicU32::new(0);
+ let mut capture = || {
+ let n = call_count.fetch_add(1, Ordering::SeqCst);
+ if n == 0 {
+ Err("first attempt fails".into())
+ } else {
+ Ok(())
+ }
+ };
+ let refresh_count = AtomicU32::new(0);
+ let mut refresh = || {
+ refresh_count.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ };
+ let mut consecutive = 0;
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(outcome, CycleOutcome::Success { attempts_used: 2 });
+ assert_eq!(consecutive, 0);
+ assert_eq!(
+ refresh_count.load(Ordering::SeqCst),
+ 1,
+ "refresh should be called once between attempt 0 and 1"
+ );
+}
+
+#[test]
+fn test_success_on_last_retry() {
+ let call_count = AtomicU32::new(0);
+ let mut capture = || {
+ let n = call_count.fetch_add(1, Ordering::SeqCst);
+ if n < MAX_CAPTURE_RETRIES {
+ Err(format!("attempt {} fails", n))
+ } else {
+ Ok(()) // succeeds on last retry (attempt == MAX_CAPTURE_RETRIES)
+ }
+ };
+ let refresh_count = AtomicU32::new(0);
+ let mut refresh = || {
+ refresh_count.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ };
+ let mut consecutive = 10;
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ outcome,
+ CycleOutcome::Success {
+ attempts_used: MAX_CAPTURE_RETRIES + 1
+ }
+ );
+ assert_eq!(consecutive, 0, "consecutive must reset even on last-retry success");
+ assert_eq!(
+ refresh_count.load(Ordering::SeqCst),
+ MAX_CAPTURE_RETRIES,
+ "refresh called between each failed attempt (not after the last)"
+ );
+}
+
+#[test]
+fn test_all_retries_fail_increments_consecutive() {
+ let mut capture = || Err("always fails".to_string());
+ let refresh_count = AtomicU32::new(0);
+ let mut refresh = || {
+ refresh_count.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ };
+ let mut consecutive = 0;
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ outcome,
+ CycleOutcome::RetryExhausted {
+ consecutive_failures: 1
+ }
+ );
+ assert_eq!(consecutive, 1);
+ // refresh called between attempts 0→1, 1→2, 2→3, but NOT after attempt 3 (the last)
+ assert_eq!(
+ refresh_count.load(Ordering::SeqCst),
+ MAX_CAPTURE_RETRIES,
+ "refresh called exactly MAX_CAPTURE_RETRIES times"
+ );
+}
+
+#[test]
+fn test_bail_after_max_consecutive_failures() {
+ let mut capture = || Err("always fails".to_string());
+ let mut refresh = || Ok(());
+ let mut consecutive = MAX_CONSECUTIVE_FAILURES - 1; // one more will trigger bail
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ outcome,
+ CycleOutcome::Bail {
+ consecutive_failures: MAX_CONSECUTIVE_FAILURES
+ }
+ );
+ assert_eq!(consecutive, MAX_CONSECUTIVE_FAILURES);
+}
+
+#[test]
+fn test_exactly_at_threshold_bails() {
+ // Verify >= not > in the comparison
+ let mut capture = || Err("fail".to_string());
+ let mut refresh = || Ok(());
+ let mut consecutive = MAX_CONSECUTIVE_FAILURES - 1;
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ // consecutive becomes 30, which is >= 30, so we bail
+ assert!(
+ matches!(outcome, CycleOutcome::Bail { .. }),
+ "must bail at exactly MAX_CONSECUTIVE_FAILURES"
+ );
+}
+
+#[test]
+fn test_one_below_threshold_does_not_bail() {
+ let mut capture = || Err("fail".to_string());
+ let mut refresh = || Ok(());
+ let mut consecutive = MAX_CONSECUTIVE_FAILURES - 2; // will become 29
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ outcome,
+ CycleOutcome::RetryExhausted {
+ consecutive_failures: MAX_CONSECUTIVE_FAILURES - 1
+ }
+ );
+}
+
+#[test]
+fn test_success_after_29_consecutive_failures_resets() {
+ let mut consecutive = MAX_CONSECUTIVE_FAILURES - 1; // 29 prior failures
+ let mut capture = || Ok(()); // this one succeeds
+ let mut refresh = || Ok(());
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(outcome, CycleOutcome::Success { attempts_used: 1 });
+ assert_eq!(
+ consecutive, 0,
+ "must reset to 0 even at 29 consecutive failures"
+ );
+}
+
+#[test]
+fn test_refresh_failure_does_not_prevent_retry() {
+ let call_count = AtomicU32::new(0);
+ let mut capture = || {
+ let n = call_count.fetch_add(1, Ordering::SeqCst);
+ if n == 0 {
+ Err("first fails".into())
+ } else {
+ Ok(())
+ }
+ };
+ // refresh always fails
+ let mut refresh = || Err("refresh broken".to_string());
+ let mut consecutive = 0;
+
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ outcome,
+ CycleOutcome::Success { attempts_used: 2 },
+ "capture should still retry even if refresh fails"
+ );
+}
+
+#[test]
+fn test_total_capture_calls_on_full_failure() {
+ let call_count = AtomicU32::new(0);
+ let mut capture = || {
+ call_count.fetch_add(1, Ordering::SeqCst);
+ Err("fail".to_string())
+ };
+ let mut refresh = || Ok(());
+ let mut consecutive = 0;
+
+ let _ = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ call_count.load(Ordering::SeqCst),
+ MAX_CAPTURE_RETRIES + 1,
+ "should attempt 0..=MAX_CAPTURE_RETRIES = {} total calls",
+ MAX_CAPTURE_RETRIES + 1
+ );
+}
+
+#[test]
+fn test_refresh_not_called_on_first_success() {
+ let refresh_count = AtomicU32::new(0);
+ let mut capture = || Ok(());
+ let mut refresh = || {
+ refresh_count.fetch_add(1, Ordering::SeqCst);
+ Ok(())
+ };
+ let mut consecutive = 0;
+
+ let _ = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ assert_eq!(
+ refresh_count.load(Ordering::SeqCst),
+ 0,
+ "refresh must NOT be called when first attempt succeeds"
+ );
+}
+
+#[test]
+fn test_refresh_not_called_after_last_failed_attempt() {
+ // Verify that refresh is NOT called after the final failed attempt
+ // (only between retries, not after the last one)
+ let call_count = AtomicU32::new(0);
+ let refresh_calls = Arc::new(std::sync::Mutex::new(Vec::new()));
+
+ let mut capture = || {
+ let n = call_count.fetch_add(1, Ordering::SeqCst);
+ Err(format!("attempt {}", n))
+ };
+ let refresh_calls_clone = refresh_calls.clone();
+ let mut refresh = || {
+ let n = call_count.load(Ordering::SeqCst);
+ refresh_calls_clone.lock().unwrap().push(n);
+ Ok(())
+ };
+ let mut consecutive = 0;
+
+ let _ = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ let calls = refresh_calls.lock().unwrap();
+ // refresh is called after attempts 0, 1, 2 (when attempt < MAX_CAPTURE_RETRIES)
+ // NOT after attempt 3 (the final one)
+ assert_eq!(calls.len(), MAX_CAPTURE_RETRIES as usize);
+ // All refresh calls should happen BEFORE the last attempt
+ for &call_after_attempt in calls.iter() {
+ assert!(
+ call_after_attempt <= MAX_CAPTURE_RETRIES,
+ "refresh called after attempt {} which is beyond the retry window",
+ call_after_attempt
+ );
+ }
+}
+
+#[test]
+fn test_30_consecutive_failure_cycles_then_bail() {
+ // Simulate the full outer loop: 30 cycles where all retries fail
+ let mut capture = || Err("fail".to_string());
+ let mut refresh = || Ok(());
+ let mut consecutive = 0;
+
+ for cycle in 0..MAX_CONSECUTIVE_FAILURES {
+ let outcome = run_capture_cycle(&mut capture, &mut refresh, &mut consecutive);
+
+ if cycle < MAX_CONSECUTIVE_FAILURES - 1 {
+ assert_eq!(
+ outcome,
+ CycleOutcome::RetryExhausted {
+ consecutive_failures: cycle + 1
+ },
+ "cycle {} should be RetryExhausted",
+ cycle
+ );
+ } else {
+ assert_eq!(
+ outcome,
+ CycleOutcome::Bail {
+ consecutive_failures: MAX_CONSECUTIVE_FAILURES
+ },
+ "cycle {} should Bail",
+ cycle
+ );
+ }
+ }
+}
+
+#[test]
+fn test_intermittent_failure_never_bails() {
+ // Every other cycle fails, but successes reset the counter
+ // Should never reach bail threshold
+ let cycle_num = AtomicU32::new(0);
+
+ let mut consecutive = 0;
+ let mut refresh = || Ok(());
+
+ for _ in 0..100 {
+ let n = cycle_num.fetch_add(1, Ordering::SeqCst);
+ let mut capture = if n % 2 == 0 {
+ Box::new(|| Err("fail".to_string())) as Box<dyn FnMut() -> Result<(), String>>
+ } else {
+ Box::new(|| Ok(())) as Box<dyn FnMut() -> Result<(), String>>
+ };
+
+ let outcome = run_capture_cycle(&mut *capture, &mut refresh, &mut consecutive);
+
+ match outcome {
+ CycleOutcome::Bail { .. } => {
+ panic!("should never bail with alternating success/failure");
+ }
+ CycleOutcome::Success { .. } => {
+ assert_eq!(consecutive, 0);
+ }
+ CycleOutcome::RetryExhausted { consecutive_failures } => {
+ assert!(
+ consecutive_failures < MAX_CONSECUTIVE_FAILURES,
+ "consecutive failures should stay low with intermittent success"
+ );
+ }
+ }
+ }
+}
+
+#[test]
+fn test_recovery_at_failure_29_prevents_bail() {
+ // 29 consecutive failure cycles, then one success, then 29 more failures
+ // Should never bail
+ let mut capture_fails = || Err("fail".to_string());
+ let mut capture_succeeds = || Ok(());
+ let mut refresh = || Ok(());
+ let mut consecutive = 0;
+
+ // 29 failure cycles
+ for _ in 0..(MAX_CONSECUTIVE_FAILURES - 1) {
+ let outcome = run_capture_cycle(&mut capture_fails, &mut refresh, &mut consecutive);
+ assert!(matches!(outcome, CycleOutcome::RetryExhausted { .. }));
+ }
+ assert_eq!(consecutive, MAX_CONSECUTIVE_FAILURES - 1);
+
+ // One success resets everything
+ let outcome = run_capture_cycle(&mut capture_succeeds, &mut refresh, &mut consecutive);
+ assert_eq!(outcome, CycleOutcome::Success { attempts_used: 1 });
+ assert_eq!(consecutive, 0);
+
+ // 29 more failure cycles — still shouldn't bail
+ for i in 0..(MAX_CONSECUTIVE_FAILURES - 1) {
+ let outcome = run_capture_cycle(&mut capture_fails, &mut refresh, &mut consecutive);
+ assert_eq!(
+ outcome,
+ CycleOutcome::RetryExhausted {
+ consecutive_failures: i + 1
+ }
+ );
+ }
+ assert_eq!(consecutive, MAX_CONSECUTIVE_FAILURES - 1);
+}
+
+// =============================================================================
+// Tests for the index migration SQL
+// =============================================================================
+
+#[test]
+fn test_index_migration_sql_is_valid() {
+ // Verify the migration SQL parses correctly
+ let sql = include_str!(
+ "../../screenpipe-db/src/migrations/20260207000000_index_video_chunks_device_name.sql"
+ );
+
+ // Should contain exactly 2 CREATE INDEX statements
+ let create_count = sql.matches("CREATE INDEX").count();
+ assert_eq!(
+ create_count, 2,
+ "migration should have exactly 2 CREATE INDEX statements"
+ );
+
+ // Should use IF NOT EXISTS (idempotent)
+ let if_not_exists_count = sql.matches("IF NOT EXISTS").count();
+ assert_eq!(
+ if_not_exists_count, 2,
+ "both indexes should use IF NOT EXISTS"
+ );
+
+ // Should target video_chunks table
+ assert!(
+ sql.contains("ON video_chunks"),
+ "indexes should be on video_chunks table"
+ );
+
+ // Should index device_name column
+ assert!(
+ sql.contains("(device_name)"),
+ "should have single-column index on device_name"
+ );
+
+ // Should have compound index for the exact query pattern
+ assert!(
+ sql.contains("(device_name, id DESC)"),
+ "should have compound index matching ORDER BY id DESC"
+ );
+}
diff --git a/crates/screenpipe-vision/tests/monitor_cache_test.rs b/crates/screenpipe-vision/tests/monitor_cache_test.rs
new file mode 100644
index 000000000..00862247e
--- /dev/null
+++ b/crates/screenpipe-vision/tests/monitor_cache_test.rs
@@ -0,0 +1,205 @@
+/// Tests for monitor handle caching optimization.
+///
+/// The optimization: SafeMonitor now caches the native monitor handle (SckMonitor/XcapMonitor)
+/// at construction time and reuses it for every capture_image() call, instead of calling
+/// Monitor::all() + find() on every frame.
+///
+/// Also replaced std::thread::spawn with tokio::task::spawn_blocking to reuse the
+/// tokio blocking thread pool instead of creating a new OS thread per frame.
+///
+/// These tests verify the structural properties. Actual capture requires a real display.
+
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::sync::Arc;
+
+
+/// Simulate the OLD behavior: enumerate all monitors and find by ID every frame.
+/// Returns the number of enumerations performed.
+fn old_capture_pattern(monitor_id: u32, frame_count: u32, enumerate_counter: &AtomicU32) {
+ for _ in 0..frame_count {
+ // OLD: enumerate all monitors every frame
+ enumerate_counter.fetch_add(1, Ordering::SeqCst);
+ let _monitors: Vec<u32> = vec![1, 2, 3]; // simulate Monitor::all()
+ let _found = _monitors.iter().find(|&&id| id == monitor_id);
+ }
+}
+
+/// Simulate the NEW behavior: use cached handle, only enumerate on cache miss.
+fn new_capture_pattern(
+ monitor_id: u32,
+ cached: bool,
+ frame_count: u32,
+ enumerate_counter: &AtomicU32,
+) {
+ let mut has_cache = cached;
+ for _ in 0..frame_count {
+ if has_cache {
+ // NEW: use cached handle directly — no enumeration
+ let _ = monitor_id; // simulate capture with cached ID
+ } else {
+ // Cache miss: enumerate once, then cache
+ enumerate_counter.fetch_add(1, Ordering::SeqCst);
+ let _monitors: Vec<u32> = vec![1, 2, 3];
+ let _found = _monitors.iter().find(|&&id| id == monitor_id);
+ has_cache = true; // cache is now populated
+ }
+ }
+}
+
+#[test]
+fn test_old_pattern_enumerates_every_frame() {
+ let counter = AtomicU32::new(0);
+ old_capture_pattern(1, 100, &counter);
+ assert_eq!(
+ counter.load(Ordering::SeqCst),
+ 100,
+ "Old pattern should enumerate on every frame"
+ );
+}
+
+#[test]
+fn test_new_pattern_enumerates_zero_times_with_cache() {
+ let counter = AtomicU32::new(0);
+ new_capture_pattern(1, true, 100, &counter);
+ assert_eq!(
+ counter.load(Ordering::SeqCst),
+ 0,
+ "New pattern should never enumerate when cache is populated"
+ );
+}
+
+#[test]
+fn test_new_pattern_enumerates_once_on_cache_miss() {
+ let counter = AtomicU32::new(0);
+ new_capture_pattern(1, false, 100, &counter);
+ assert_eq!(
+ counter.load(Ordering::SeqCst),
+ 1,
+ "New pattern should enumerate exactly once on cache miss"
+ );
+}
+
+#[test]
+fn test_enumeration_savings_multi_monitor() {
+ // Simulate 3 monitors at 0.5 FPS for 60 seconds = 30 frames each = 90 total
+ let old_counter = AtomicU32::new(0);
+ let new_counter = AtomicU32::new(0);
+
+ for monitor_id in 1..=3 {
+ old_capture_pattern(monitor_id, 30, &old_counter);
+ new_capture_pattern(monitor_id, true, 30, &new_counter);
+ }
+
+ let old_enumerations = old_counter.load(Ordering::SeqCst);
+ let new_enumerations = new_counter.load(Ordering::SeqCst);
+
+ println!(
+ "3 monitors, 30 frames each: old={} enumerations, new={} enumerations",
+ old_enumerations, new_enumerations
+ );
+
+ assert_eq!(old_enumerations, 90);
+ assert_eq!(new_enumerations, 0);
+}
+
+#[test]
+fn test_enumeration_savings_adaptive_fps_burst() {
+ // Simulate 3 monitors at 10 FPS adaptive burst for 5 seconds = 50 frames each = 150 total
+ let old_counter = AtomicU32::new(0);
+ let new_counter = AtomicU32::new(0);
+
+ for monitor_id in 1..=3 {
+ old_capture_pattern(monitor_id, 50, &old_counter);
+ new_capture_pattern(monitor_id, true, 50, &new_counter);
+ }
+
+ let old = old_counter.load(Ordering::SeqCst);
+ let new = new_counter.load(Ordering::SeqCst);
+
+ println!(
+ "Adaptive burst (10 FPS × 3 monitors × 5s): old={} enumerations, new={} enumerations",
+ old, new
+ );
+
+ assert_eq!(old, 150);
+ assert_eq!(new, 0);
+}
+
+/// Verify that spawn_blocking reuses threads while std::thread::spawn creates new ones.
+#[tokio::test]
+async fn test_spawn_blocking_reuses_threads() {
+ let thread_ids = Arc::new(std::sync::Mutex::new(Vec::new()));
+
+ // Run 20 blocking tasks
+ let mut handles = vec![];
+ for _ in 0..20 {
+ let ids = thread_ids.clone();
+ handles.push(tokio::task::spawn_blocking(move || {
+ let tid = format!("{:?}", std::thread::current().id());
+ ids.lock().unwrap().push(tid);
+ }));
+ }
+
+ for h in handles {
+ h.await.unwrap();
+ }
+
+ let ids = thread_ids.lock().unwrap();
+ let unique_threads: std::collections::HashSet<&String> = ids.iter().collect();
+
+ println!(
+ "spawn_blocking: {} tasks used {} unique threads",
+ ids.len(),
+ unique_threads.len()
+ );
+
+ // spawn_blocking should reuse threads — far fewer unique threads than tasks
+ // The default tokio blocking pool is ~512 threads max, but for 20 fast tasks
+ // it should reuse aggressively
+ assert!(
+ unique_threads.len() <= ids.len(),
+ "spawn_blocking should not create more threads than tasks"
+ );
+ // In practice, 20 fast tasks typically reuse ~2-4 threads
+ assert!(
+ unique_threads.len() < 15,
+ "Expected significant thread reuse, got {} unique threads for {} tasks",
+ unique_threads.len(),
+ ids.len()
+ );
+}
+
+/// Compare thread creation: std::thread::spawn creates a new thread each time
+#[test]
+fn test_std_thread_spawn_creates_new_threads() {
+ let thread_ids = Arc::new(std::sync::Mutex::new(Vec::new()));
+ let mut handles = vec![];
+
+ for _ in 0..20 {
+ let ids = thread_ids.clone();
+ handles.push(std::thread::spawn(move || {
+ let tid = format!("{:?}", std::thread::current().id());
+ ids.lock().unwrap().push(tid);
+ }));
+ }
+
+ for h in handles {
+ h.join().unwrap();
+ }
+
+ let ids = thread_ids.lock().unwrap();
+ let unique_threads: std::collections::HashSet<&String> = ids.iter().collect();
+
+ println!(
+ "std::thread::spawn: {} tasks used {} unique threads",
+ ids.len(),
+ unique_threads.len()
+ );
+
+ // std::thread::spawn creates a new thread for each call
+ assert_eq!(
+ unique_threads.len(),
+ ids.len(),
+ "std::thread::spawn should create a unique thread per call"
+ );
+}