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
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(redact): clean shutdown signal stops tokio-teardown panics
Louis Beaumont61a4ea3a8663
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/main.rs b/apps/screenpipe-app-tauri/src-tauri/src/main.rsindex 698c7ced2..87c246f92 100755--- a/apps/screenpipe-app-tauri/src-tauri/src/main.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/main.rs@@ -592,6 +592,23 @@ async fn main() {.map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column())).unwrap_or_default();+ // Suppress "tokio context being shutdown" panics from background+ // tasks (redact workers, etc.) — these fire when a task is mid-+ // sqlx/timer poll at the moment the runtime tears down on app+ // quit. ServerCore::shutdown signals workers to exit cleanly, but+ // a residual race is possible if the worker is inside an await+ // that doesn't include the shutdown future. Either way, this is+ // orderly-shutdown noise — not a crash — and logging it to+ // last-panic.log + Sentry makes the app look unstable to users+ // and skews crash-rate dashboards.+ if payload.contains("Tokio 1.x context was found, but it is being shutdown") {+ eprintln!(+ "(suppressed tokio shutdown-time panic on thread '{}' at {})",+ thread_name, location+ );+ return;+ }+// Force-capture a backtrace before abort() kills uslet backtrace = std::backtrace::Backtrace::force_capture();diff --git a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rsindex 854caec3d..a27608fb6 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/server_core.rs@@ -25,6 +25,7 @@ use screenpipe_engine::{analytics, hot_frame_cache::HotFrameCache, power::PowerManagerHandle, server::bind_listener,start_power_manager_with_pref, start_sleep_monitor, RecordingConfig, ResourceMonitor, SCServer,};+use tokio::sync::Notify;use tracing::{error, info, warn};/// Shared references that survive capture start/stop cycles.@@ -44,6 +45,12 @@ pub struct ServerCore {/// Local API auth key — exposed to the frontend via Tauri command so/// localFetch can inject it synchronously (no async store race).pub local_api_key: Option<String>,+ /// Shutdown signal for the redaction reconciliation workers. Fired+ /// from `shutdown()` so the workers exit before the tokio runtime+ /// tears down — otherwise their in-flight sqlx queries (which use+ /// `tokio::time::timeout` internally) panic with "A Tokio 1.x context+ /// was found, but it is being shutdown."+ redact_shutdown: Arc<Notify>,}impl ServerCore {@@ -484,6 +491,10 @@ impl ServerCore {let backend = config.pii_backend.as_str();let use_tinfoil = matches!(backend, "tinfoil" | "cloud" | "enclave");+ // One shutdown signal, shared across both worker spawn paths and+ // stored on Self for `shutdown()` to fire on app quit.+ let redact_shutdown = Arc::new(Notify::new());+if config.async_pii_redaction {use screenpipe_redact::adapters::opf::{OpfAdapter, OpfConfig};use screenpipe_redact::adapters::tinfoil::TinfoilRedactor;@@ -514,13 +525,15 @@ impl ServerCore {tables: ALL_TARGET_TABLES.to_vec(),..Default::default()};- let _ = Worker::new(db.pool.clone(), pipeline_arc, cfg).spawn();+ let _ = Worker::new(db.pool.clone(), pipeline_arc, cfg)+ .spawn_with_shutdown(redact_shutdown.clone());} else {// Local mode: spawn the download+load off the boot path// so a slow first-run HF pull doesn't block the app// launch. The worker is created inside the spawned// task once the model is ready.let pool = db.pool.clone();+ let shutdown = redact_shutdown.clone();tokio::spawn(async move {info!("fetching local OPF v6 checkpoint (~2.8 GB on first run, cached at \@@ -550,7 +563,8 @@ impl ServerCore {tables: ALL_TARGET_TABLES.to_vec(),..Default::default()};- let _ = Worker::new(pool, pipeline_arc, cfg).spawn();+ let _ = Worker::new(pool, pipeline_arc, cfg)+ .spawn_with_shutdown(shutdown);});}}@@ -566,11 +580,13 @@ impl ServerCore {info!("starting async image-PII worker (backend=tinfoil)");let detector =Arc::new(TinfoilImageRedactor::from_env()) as Arc<dyn ImageRedactor>;- let _ = ImageWorker::new(pool, detector, ImageWorkerConfig::default()).spawn();+ let _ = ImageWorker::new(pool, detector, ImageWorkerConfig::default())+ .spawn_with_shutdown(redact_shutdown.clone());} else {// Local mode: rfdetr_v8 ONNX. First-run downloads// ~108 MB from huggingface.co/screenpipe/pii-image-redactor// and verifies SHA-256 before landing in ~/.screenpipe/models/.+ let shutdown = redact_shutdown.clone();tokio::spawn(async move {match RfdetrRedactor::load_or_download(RfdetrConfig::default()).await {Ok(detector) => {@@ -582,7 +598,7 @@ impl ServerCore {detector_arc,ImageWorkerConfig::default(),)- .spawn();+ .spawn_with_shutdown(shutdown);}Err(e) => {warn!(@@ -609,6 +625,7 @@ impl ServerCore {data_path,port: config.port,local_api_key: config.api_auth_key.clone(),+ redact_shutdown,})}@@ -617,6 +634,14 @@ impl ServerCore {info!("Shutting down server core");screenpipe_connect::mdns::shutdown();+ // Tell redaction workers to exit BEFORE the tokio runtime tears+ // down — otherwise their in-flight sqlx queries panic with+ // "A Tokio 1.x context was found, but it is being shutdown."+ // Workers loop polling, so signaling early gives them headroom+ // to land on a select! boundary and exit cleanly.+ self.redact_shutdown.notify_waiters();+ info!("Signaled redaction workers to shut down");+// Stop pipe scheduler{info!("Stopping pipe scheduler...");diff --git a/crates/screenpipe-redact/src/image/worker.rs b/crates/screenpipe-redact/src/image/worker.rsindex 4e72b225e..40700d0be 100644--- a/crates/screenpipe-redact/src/image/worker.rs+++ b/crates/screenpipe-redact/src/image/worker.rs@@ -25,7 +25,7 @@ use std::sync::Arc;use std::time::Duration;use sqlx::{Row, SqlitePool};-use tokio::sync::Mutex;+use tokio::sync::{Mutex, Notify};use tokio::task::JoinHandle;use tokio::time;use tracing::{debug, info, warn};@@ -105,13 +105,24 @@ impl ImageWorker {self.status.lock().await.clone()}- /// Spawn on the current tokio runtime. Caller is responsible for- /// graceful shutdown via the returned join handle.+ /// Spawn on the current tokio runtime, no shutdown signal — for tests+ /// + the standalone CLI. Production callers should use+ /// [`Self::spawn_with_shutdown`] so the worker exits before the tokio+ /// runtime tears down (otherwise in-flight sqlx queries holding+ /// `tokio::time::timeout` futures panic with "A Tokio 1.x context was+ /// found, but it is being shutdown.").pub fn spawn(self) -> JoinHandle<()> {- tokio::spawn(self.run())+ tokio::spawn(self.run(None))}- async fn run(self) {+ /// Spawn with a shutdown signal. The worker exits cleanly on the next+ /// `shutdown.notify_waiters()` call (or mid-frame if the signal fires+ /// during a detect/redact). Use this from `ServerCore`.+ pub fn spawn_with_shutdown(self, shutdown: Arc<Notify>) -> JoinHandle<()> {+ tokio::spawn(self.run(Some(shutdown)))+ }++ async fn run(self, shutdown: Option<Arc<Notify>>) {info!(redactor = self.redactor.name(),version = self.redactor.version(),@@ -122,28 +133,63 @@ impl ImageWorker {s.running = true;}+ async fn race<F: std::future::Future<Output = ()>>(+ fut: F,+ shutdown: Option<&Arc<Notify>>,+ ) -> Option<()> {+ match shutdown {+ Some(n) => tokio::select! {+ _ = fut => Some(()),+ _ = n.notified() => None,+ },+ None => {+ fut.await;+ Some(())+ }+ }+ }+loop {if self.paused.load(Ordering::SeqCst) {self.set_paused(true).await;- time::sleep(self.cfg.poll_interval).await;+ if race(time::sleep(self.cfg.poll_interval), shutdown.as_ref())+ .await+ .is_none()+ {+ info!("image redact worker: shutdown signal received, exiting");+ return;+ }continue;}self.set_paused(false).await;- match self.process_one().await {- Ok(Some(_)) => {- time::sleep(self.cfg.idle_between_frames).await;- }- Ok(None) => {- time::sleep(self.cfg.poll_interval).await;+ let result = match shutdown.as_ref() {+ Some(n) => tokio::select! {+ r = self.process_one() => Some(r),+ _ = n.notified() => None,+ },+ None => Some(self.process_one().await),+ };++ let nap = match result {+ None => {+ info!("image redact worker: shutdown signal received mid-frame, exiting");+ return;}- Err(e) => {+ Some(Ok(Some(_))) => self.cfg.idle_between_frames,+ Some(Ok(None)) => self.cfg.poll_interval,+ Some(Err(e)) => {warn!(error = %e, "image reconciliation error; backing off");let mut s = self.status.lock().await;s.last_error = Some(e.to_string());drop(s);- time::sleep(Duration::from_secs(2)).await;+ Duration::from_secs(2)}+ };++ if race(time::sleep(nap), shutdown.as_ref()).await.is_none() {+ info!("image redact worker: shutdown signal received, exiting");+ return;}}}diff --git a/crates/screenpipe-redact/src/worker/mod.rs b/crates/screenpipe-redact/src/worker/mod.rsindex 9336ba30e..220318e49 100644--- a/crates/screenpipe-redact/src/worker/mod.rs+++ b/crates/screenpipe-redact/src/worker/mod.rs@@ -21,7 +21,7 @@ use std::sync::Arc;use std::time::Duration;use sqlx::SqlitePool;-use tokio::sync::Mutex;+use tokio::sync::{Mutex, Notify};use tokio::task::JoinHandle;use tokio::time;use tracing::{debug, info, warn};@@ -107,14 +107,24 @@ impl Worker {self.status.lock().await.clone()}- /// Spawn the worker on the current tokio runtime. Returns the- /// task handle — caller is responsible for graceful shutdown- /// (e.g. `handle.abort()` on app close).+ /// Spawn the worker on the current tokio runtime. Without a shutdown+ /// signal — left for tests + the standalone CLI. Production callers+ /// should use [`Self::spawn_with_shutdown`] so the worker exits before+ /// the tokio runtime tears down (otherwise in-flight sqlx queries+ /// holding `tokio::time::timeout` futures panic with "A Tokio 1.x+ /// context was found, but it is being shutdown.").pub fn spawn(self) -> JoinHandle<()> {- tokio::spawn(self.run())+ tokio::spawn(self.run(None))}- async fn run(self) {+ /// Spawn with a shutdown signal. The worker exits cleanly on the next+ /// `shutdown.notify_waiters()` call (or on the next loop boundary if+ /// it's mid-batch when the signal fires). Use this from `ServerCore`.+ pub fn spawn_with_shutdown(self, shutdown: Arc<Notify>) -> JoinHandle<()> {+ tokio::spawn(self.run(Some(shutdown)))+ }++ async fn run(self, shutdown: Option<Arc<Notify>>) {info!(redactor = self.redactor.name(),version = self.redactor.version(),@@ -126,33 +136,81 @@ impl Worker {s.running = true;}+ // Helper: race a future against the optional shutdown signal.+ // If shutdown fires, return None and the caller breaks out of the+ // loop. Without a shutdown signal, just awaits the future.+ async fn race<F: std::future::Future<Output = ()>>(+ fut: F,+ shutdown: Option<&Arc<Notify>>,+ ) -> Option<()> {+ match shutdown {+ Some(n) => tokio::select! {+ _ = fut => Some(()),+ _ = n.notified() => None,+ },+ None => {+ fut.await;+ Some(())+ }+ }+ }+loop {if self.paused.load(std::sync::atomic::Ordering::SeqCst) {self.set_paused(true).await;- time::sleep(self.cfg.poll_interval).await;+ if race(time::sleep(self.cfg.poll_interval), shutdown.as_ref())+ .await+ .is_none()+ {+ info!("redact worker: shutdown signal received, exiting");+ return;+ }continue;}self.set_paused(false).await;let mut any_work = false;for table in &self.cfg.tables {- match self.process_table(*table).await {- Ok(n) if n > 0 => any_work = true,- Ok(_) => {}- Err(e) => {+ // Race the table work against shutdown so a long redact batch+ // doesn't hold us through tokio teardown.+ let result = match shutdown.as_ref() {+ Some(n) => tokio::select! {+ r = self.process_table(*table) => Some(r),+ _ = n.notified() => None,+ },+ None => Some(self.process_table(*table).await),+ };+ match result {+ None => {+ info!("redact worker: shutdown signal received mid-batch, exiting");+ return;+ }+ Some(Ok(n)) if n > 0 => any_work = true,+ Some(Ok(_)) => {}+ Some(Err(e)) => {warn!(table = ?table, error = %e, "reconciliation error; will retry");let mut s = self.status.lock().await;s.last_error = Some(e.to_string());+ drop(s);// backoff on error- time::sleep(Duration::from_secs(2)).await;+ if race(time::sleep(Duration::from_secs(2)), shutdown.as_ref())+ .await+ .is_none()+ {+ return;+ }}}}- if any_work {- time::sleep(self.cfg.idle_between_batches).await;+ let nap = if any_work {+ self.cfg.idle_between_batches} else {- time::sleep(self.cfg.poll_interval).await;+ self.cfg.poll_interval+ };+ if race(time::sleep(nap), shutdown.as_ref()).await.is_none() {+ info!("redact worker: shutdown signal received, exiting");+ return;}}}