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(redact,image): don't break the product when frames.name is an mp4 chunk or when the JPG write races with a reader

Louis Beaumont52aab830adf0
diff --git a/crates/screenpipe-redact/src/image/frame_redactor.rs b/crates/screenpipe-redact/src/image/frame_redactor.rs
index e14d1fb14..d9c1cdd1d 100644
--- a/crates/screenpipe-redact/src/image/frame_redactor.rs
+++ b/crates/screenpipe-redact/src/image/frame_redactor.rs
@@ -23,7 +23,7 @@
use std::path::{Path, PathBuf};
-use image::{DynamicImage, Rgb};
+use image::{DynamicImage, ImageFormat, Rgb};
use crate::image::{ImageRedactionPolicy, ImageRegion};
use crate::RedactError;
@@ -93,9 +93,58 @@ pub fn redact_frame(
} else {
redacted_sibling(image_path)
};
+ // Atomic write: encode to a sibling tempfile, then rename over
+ // the destination. Concurrent readers (mp4 encoder, video API
+ // serving frames over HTTP) see either the old full file or the
+ // new full file, never a half-written one. Critical in destructive
+ // mode where the destination IS the only copy.
+ //
+ // We must keep the original extension on the tempfile too — `image`
+ // infers format from the path. So `frame.jpg` → `frame.jpg.redact-tmp`
+ // would fail to encode. Instead, use `<stem>.redact-tmp.<ext>`
+ // (e.g. `frame.redact-tmp.jpg`) so the format-inference path keeps
+ // working, then rename to the final destination.
+ let format = ImageFormat::from_path(&output_path).map_err(|e| {
+ RedactError::Runtime(format!(
+ "unrecognized image format for {}: {e}",
+ output_path.display()
+ ))
+ })?;
+ let stem = output_path
+ .file_stem()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "frame".into());
+ let ext = output_path
+ .extension()
+ .map(|s| s.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "jpg".into());
+ let tmp_path = output_path.with_file_name(format!("{stem}.redact-tmp.{ext}"));
+ let tmp_file = std::fs::File::create(&tmp_path)
+ .map_err(|e| RedactError::Runtime(format!("create {}: {e}", tmp_path.display())))?;
+ let mut tmp_writer = std::io::BufWriter::new(tmp_file);
DynamicImage::ImageRgb8(buf)
- .save(&output_path)
- .map_err(|e| RedactError::Runtime(format!("save {}: {e}", output_path.display())))?;
+ .write_to(&mut tmp_writer, format)
+ .map_err(|e| RedactError::Runtime(format!("encode {}: {e}", tmp_path.display())))?;
+ // Make sure bytes hit disk before rename — otherwise a crash between
+ // rename and fsync could leave a zero-length file.
+ use std::io::Write;
+ tmp_writer
+ .flush()
+ .map_err(|e| RedactError::Runtime(format!("flush {}: {e}", tmp_path.display())))?;
+ tmp_writer
+ .into_inner()
+ .map_err(|e| RedactError::Runtime(format!("close {}: {e}", tmp_path.display())))?
+ .sync_all()
+ .map_err(|e| RedactError::Runtime(format!("fsync {}: {e}", tmp_path.display())))?;
+ std::fs::rename(&tmp_path, &output_path).map_err(|e| {
+ // On rename failure, try to clean up the tempfile — best effort.
+ let _ = std::fs::remove_file(&tmp_path);
+ RedactError::Runtime(format!(
+ "rename {} → {}: {e}",
+ tmp_path.display(),
+ output_path.display()
+ ))
+ })?;
Ok(FrameRedactionOutcome {
regions_redacted: redacted,
diff --git a/crates/screenpipe-redact/src/image/worker.rs b/crates/screenpipe-redact/src/image/worker.rs
index fbde63611..084dc1b85 100644
--- a/crates/screenpipe-redact/src/image/worker.rs
+++ b/crates/screenpipe-redact/src/image/worker.rs
@@ -194,6 +194,34 @@ impl ImageWorker {
return Ok(Some(FrameRedactionOutcome::default()));
}
+ // `frames.name` can hold either a snapshot JPG path (the
+ // common event-driven path) OR an mp4 chunk path (the legacy
+ // path: db.rs `insert_frame` binds `video_chunks.file_path`
+ // into `frames.name`, see #legacy-mp4-frames). Detection +
+ // redaction expect a still image. If the file is an mp4 (or
+ // anything else our image stack can't decode), `detect` /
+ // `redact_frame` return a Runtime error. Without this branch
+ // we'd retry the row forever and spam logs every poll.
+ // We mark it redacted-zero to skip — the mp4 itself is left
+ // untouched. Per Louis: not handling mp4 redaction yet, just
+ // making sure the worker doesn't break the product.
+ let is_image_path = matches!(
+ path.extension().and_then(|e| e.to_str()),
+ Some(ext) if matches!(
+ ext.to_ascii_lowercase().as_str(),
+ "jpg" | "jpeg" | "png" | "webp" | "bmp"
+ )
+ );
+ if !is_image_path {
+ debug!(
+ frame = id,
+ path = %path.display(),
+ "frames.name is not a still-image path (likely mp4 chunk) — marking redacted to skip"
+ );
+ self.mark_redacted(id, target_version, 0).await?;
+ return Ok(Some(FrameRedactionOutcome::default()));
+ }
+
let regions = self.redactor.detect(path).await?;
let outcome = redact_frame(path, &regions, &self.cfg.policy, self.cfg.destructive)
.map_err(anyhow::Error::from)?;
@@ -324,4 +352,42 @@ mod tests {
assert!(when.is_some());
assert_eq!(v, Some(1));
}
+
+ /// `frames.name` can hold an mp4 chunk path on the legacy capture
+ /// path (db.rs `insert_frame` binds `video_chunks.file_path` →
+ /// `frames.name`). Worker must skip those instead of dying on
+ /// `image::open`. Regression guard for product-stability path —
+ /// without this the worker infinite-retries every poll.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn marks_mp4_path_redacted_so_it_isnt_re_polled() {
+ let pool = setup().await;
+ // Use a temp .mp4 that actually exists on disk so we hit the
+ // extension-check path (not the missing-file early-out).
+ let dir = tempfile::tempdir().unwrap();
+ let mp4_path = dir.path().join("chunk_001.mp4");
+ std::fs::write(&mp4_path, b"\x00\x00\x00\x18ftypmp42").unwrap();
+ sqlx::query("INSERT INTO frames (timestamp, name) VALUES (datetime('now', '-1 hour'), ?1)")
+ .bind(mp4_path.to_string_lossy().into_owned())
+ .execute(&pool)
+ .await
+ .unwrap();
+ let cfg = ImageWorkerConfig::default();
+ let w = ImageWorker::new(pool.clone(), Arc::new(StubRedactor), cfg);
+ let outcome = w.process_one().await.unwrap();
+ assert!(outcome.is_some(), "mp4 row should be marked, not errored");
+ // mp4 must NOT have been touched.
+ assert!(
+ mp4_path.exists(),
+ "mp4 chunk file should be untouched by the redact worker"
+ );
+ let row =
+ sqlx::query("SELECT image_redacted_at, image_redaction_regions FROM frames LIMIT 1")
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+ let when: Option<i64> = row.get(0);
+ let regions: Option<i64> = row.get(1);
+ assert!(when.is_some(), "must mark redacted_at to skip");
+ assert_eq!(regions, Some(0), "must record zero regions for mp4 skip");
+ }
}