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): pause write queue during macOS sleep to prevent WAL corruption

Louis Beaumont092cc6496de4
diff --git a/crates/screenpipe-db/src/lib.rs b/crates/screenpipe-db/src/lib.rs
index c27075454..e4152f946 100644
--- a/crates/screenpipe-db/src/lib.rs
+++ b/crates/screenpipe-db/src/lib.rs
@@ -19,4 +19,4 @@ pub use migration_worker::{
};
pub use text_normalizer::{expand_search_query, sanitize_fts5_query};
pub use types::*;
-pub use write_queue::SyncTable;
+pub use write_queue::{request_write_pause, request_write_resume, SyncTable};
diff --git a/crates/screenpipe-db/src/write_queue.rs b/crates/screenpipe-db/src/write_queue.rs
index bfb7e85f7..290bb5a82 100644
--- a/crates/screenpipe-db/src/write_queue.rs
+++ b/crates/screenpipe-db/src/write_queue.rs
@@ -20,10 +20,11 @@
use chrono::{DateTime, Utc};
use sqlx::{Pool, Sqlite};
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, OwnedSemaphorePermit, Semaphore};
-use tracing::{debug, error, warn};
+use tracing::{debug, error, info, warn};
/// Maximum writes per batch. Caps transaction size to avoid holding
/// the write lock too long and starving readers.
@@ -36,6 +37,31 @@ const DRAIN_INTERVAL: Duration = Duration::from_millis(100);
/// backpressure reaching capture threads.
const CHANNEL_CAPACITY: usize = 4096;
+// ── Sleep/wake pause mechanism ───────────────────────────────────────────
+
+/// When true, the drain loop holds pending writes instead of executing them.
+/// Set by the sleep monitor before macOS sleep, cleared on wake.
+static WRITE_PAUSED: AtomicBool = AtomicBool::new(false);
+
+/// Notifies the drain loop to resume after being paused.
+static RESUME_NOTIFY: std::sync::OnceLock<tokio::sync::Notify> = std::sync::OnceLock::new();
+
+/// Pause the write queue. Safe to call from any thread (including ObjC callbacks).
+/// The drain loop will finish its current in-flight batch, then block.
+pub fn request_write_pause() {
+ WRITE_PAUSED.store(true, Ordering::SeqCst);
+ info!("write_queue: pause requested (sleep)");
+}
+
+/// Resume the write queue. Safe to call from any thread.
+pub fn request_write_resume() {
+ WRITE_PAUSED.store(false, Ordering::SeqCst);
+ if let Some(notify) = RESUME_NOTIFY.get() {
+ notify.notify_one();
+ }
+ info!("write_queue: resume requested (wake)");
+}
+
// ── Write operation definitions ──────────────────────────────────────────
/// A database write operation with all parameters owned (no borrows).
@@ -373,6 +399,27 @@ async fn drain_loop(
}
}
+ // ── Sleep/wake pause gate ──
+ // If paused (system going to sleep), hold all pending writes
+ // until resumed. This prevents WAL corruption from I/O errors
+ // during sleep transitions.
+ if WRITE_PAUSED.load(Ordering::SeqCst) {
+ if !batch.is_empty() {
+ info!("write_queue: paused for sleep, holding {} writes", batch.len());
+ }
+ let notify = RESUME_NOTIFY.get_or_init(|| tokio::sync::Notify::new());
+ tokio::select! {
+ _ = notify.notified() => {
+ info!("write_queue: resumed after sleep, {} pending", batch.len());
+ }
+ _ = tokio::time::sleep(Duration::from_secs(120)) => {
+ warn!("write_queue: pause timed out after 120s, auto-resuming");
+ WRITE_PAUSED.store(false, Ordering::SeqCst);
+ }
+ }
+ continue;
+ }
+
if batch.is_empty() {
continue;
}
diff --git a/crates/screenpipe-engine/src/sleep_monitor.rs b/crates/screenpipe-engine/src/sleep_monitor.rs
index 3e5824129..1e60abe1e 100644
--- a/crates/screenpipe-engine/src/sleep_monitor.rs
+++ b/crates/screenpipe-engine/src/sleep_monitor.rs
@@ -422,6 +422,13 @@ pub fn start_sleep_monitor() {
fn on_will_sleep() {
SCREEN_IS_LOCKED.store(true, Ordering::SeqCst);
screenpipe_config::set_screen_locked(true);
+
+ // Pause DB write queue before sleep to prevent WAL corruption.
+ // The drain loop will finish its current in-flight batch (already
+ // mid-COMMIT), then block until resumed on wake. This ensures no
+ // SQLite I/O happens while the disk is asleep.
+ screenpipe_db::request_write_pause();
+
capture_event_nonblocking(
"system_will_sleep",
json!({
@@ -473,6 +480,10 @@ fn on_did_wake(handle: &tokio::runtime::Handle) {
screenpipe_screen::stream_invalidation::request();
}
+ // Resume DB write queue now that the system is stable.
+ // The 5-second delay above gives the disk time to fully wake.
+ screenpipe_db::request_write_resume();
+
// Check if recording is healthy
let (audio_healthy, vision_healthy) = check_recording_health().await;