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(engine): make TriggerDropped count-only to dodge multi-monitor race

Louis Beaumonta1f4dcbb377e
diff --git a/crates/screenpipe-engine/src/frame_linker.rs b/crates/screenpipe-engine/src/frame_linker.rs
index 97f4f4f82..595b4c036 100644
--- a/crates/screenpipe-engine/src/frame_linker.rs
+++ b/crates/screenpipe-engine/src/frame_linker.rs
@@ -219,31 +219,6 @@ impl FrameLinker {
updates
}
- /// Called by the capture loop when it decides to drop a set of
- /// triggers (DRM gate, pause state, capture error, etc.). Removes
- /// the matching pending events without emitting an UPDATE and
- /// returns how many were actually pending. Idempotent: unknown
- /// correlation_ids are ignored. Empty input is valid (used by the
- /// Lagged path which only carries a count, not the ids).
- pub fn on_trigger_dropped(&mut self, correlation_ids: &[CorrelationId]) -> usize {
- let mut removed = 0;
- for corr_id in correlation_ids {
- if self.pending_events.remove(corr_id).is_some() {
- removed += 1;
- }
- // Also clear from any pending_frame's unmatched list — a
- // trigger that's been dropped will never get a row, so
- // future event_persisted calls for this corr_id won't
- // happen. Without this, a half-paired frame could sit in
- // pending_frames waiting for a row that's dead.
- for pf in self.pending_frames.iter_mut() {
- pf.unmatched.retain(|c| c != corr_id);
- }
- }
- self.compact_pending_frames();
- removed
- }
-
/// Drop half-paired entries older than `ttl`. Call periodically
/// from the host actor. Returns the number of entries evicted —
/// useful for metrics ("how many events never got a frame").
@@ -669,105 +644,6 @@ mod tests {
assert_eq!(linker.pending_len(), (1, 1));
}
- #[test]
- fn trigger_dropped_removes_pending_event() {
- let mut linker = FrameLinker::new(cfg());
- let t0 = Instant::now();
-
- linker.on_event_persisted(
- EventPersisted {
- correlation_id: 1,
- row_id: 100,
- },
- t0,
- );
- assert_eq!(linker.pending_len(), (1, 0));
-
- let removed = linker.on_trigger_dropped(&[1]);
- assert_eq!(removed, 1);
- assert_eq!(linker.pending_len(), (0, 0));
-
- // A late frame for the dropped corr id is a no-op (the row was
- // never going to be linked anyway).
- let updates = linker.on_frame_captured(
- FrameCaptured {
- frame_id: 999,
- correlation_ids: vec![1],
- },
- t0,
- );
- assert!(updates.is_empty());
- }
-
- #[test]
- fn trigger_dropped_unknown_id_is_noop() {
- let mut linker = FrameLinker::new(cfg());
- let removed = linker.on_trigger_dropped(&[42]);
- assert_eq!(removed, 0);
- assert_eq!(linker.pending_len(), (0, 0));
- }
-
- #[test]
- fn trigger_dropped_clears_unmatched_from_pending_frame() {
- let mut linker = FrameLinker::new(cfg());
- let t0 = Instant::now();
-
- // Frame arrives first with 3 unmatched ids.
- linker.on_frame_captured(
- FrameCaptured {
- frame_id: 999,
- correlation_ids: vec![1, 2, 3],
- },
- t0,
- );
- assert_eq!(linker.pending_len(), (0, 1));
-
- // Drop corr ids 2 and 3 — the frame should now only wait on 1.
- let removed = linker.on_trigger_dropped(&[2, 3]);
- assert_eq!(
- removed, 0,
- "no events were pending; only frame-side unmatched cleared"
- );
- // Pending frame still alive (unmatched=[1]).
- assert_eq!(linker.pending_len(), (0, 1));
-
- // Event 1 lands → pair, frame entry compacts away.
- let u = linker.on_event_persisted(
- EventPersisted {
- correlation_id: 1,
- row_id: 100,
- },
- t0,
- );
- assert_eq!(
- u,
- Some(LinkUpdate {
- row_id: 100,
- frame_id: 999
- })
- );
- assert_eq!(linker.pending_len(), (0, 0));
- }
-
- #[test]
- fn trigger_dropped_compacts_fully_cleared_frame() {
- let mut linker = FrameLinker::new(cfg());
- let t0 = Instant::now();
-
- linker.on_frame_captured(
- FrameCaptured {
- frame_id: 999,
- correlation_ids: vec![1, 2],
- },
- t0,
- );
- assert_eq!(linker.pending_len(), (0, 1));
-
- // Both unmatched ids dropped → frame entry should be compacted away.
- linker.on_trigger_dropped(&[1, 2]);
- assert_eq!(linker.pending_len(), (0, 0));
- }
-
#[test]
fn pending_frame_with_mixed_matched_and_unmatched_corr_ids() {
let mut linker = FrameLinker::new(cfg());
diff --git a/crates/screenpipe-engine/src/frame_linker_actor.rs b/crates/screenpipe-engine/src/frame_linker_actor.rs
index 0b1ea4a9b..41d29de62 100644
--- a/crates/screenpipe-engine/src/frame_linker_actor.rs
+++ b/crates/screenpipe-engine/src/frame_linker_actor.rs
@@ -197,18 +197,23 @@ pub fn spawn_frame_linker(
}
}
Some(LinkerMessage::TriggerDropped { correlation_ids, reason }) => {
+ // Count-only by design. The trigger broadcast fans
+ // out to N monitor capture loops; any per-monitor
+ // drop site (Cold state, capture-error, debounce
+ // without `last_frame_id`) reports the same
+ // corr_id another monitor may still be in the
+ // middle of capturing for. If we mutated state
+ // here we'd race-cancel valid pairings. TTL
+ // eviction (60s) handles the genuinely orphaned
+ // ones; the per-reason counter surfaced in the
+ // periodic WARN gives the diagnostic visibility
+ // that motivated this message in the first place.
let n_corr = correlation_ids.len();
- // Bump the per-reason counter regardless of whether
- // the corr_ids were pending — for `Lagged` the
- // capture side can't recover the ids, only the
- // count, and we still want visibility.
let bump = if n_corr == 0 { 1 } else { n_corr as u64 };
drop_reason_counter(reason).fetch_add(bump, Ordering::Relaxed);
- let removed = linker.on_trigger_dropped(&correlation_ids);
debug!(
?reason,
n_corr,
- removed,
"frame_linker: trigger(s) dropped by capture loop"
);
}
diff --git a/crates/screenpipe-engine/tests/frame_linker_actor_integration.rs b/crates/screenpipe-engine/tests/frame_linker_actor_integration.rs
index 7a15a165d..05068c3af 100644
--- a/crates/screenpipe-engine/tests/frame_linker_actor_integration.rs
+++ b/crates/screenpipe-engine/tests/frame_linker_actor_integration.rs
@@ -17,7 +17,7 @@ use std::time::Duration;
use chrono::Utc;
use screenpipe_db::{DatabaseManager, InsertUiEvent, UiEventType};
-use screenpipe_engine::frame_linker::{EventPersisted, FrameCaptured};
+use screenpipe_engine::frame_linker::{DropReason, EventPersisted, FrameCaptured};
use screenpipe_engine::frame_linker_actor::{
linker_channel, linker_metrics_snapshot, next_correlation_id, spawn_frame_linker, LinkerMessage,
};
@@ -251,6 +251,128 @@ async fn unmatched_event_stays_null_when_no_frame_arrives() {
stop.store(true, Ordering::Relaxed);
}
+/// Multi-monitor race guard: `TriggerDropped` is broadcast to N capture
+/// loops. Per-monitor drop sites (Cold state, capture-error, debounce
+/// without `last_frame_id`) can fire for a corr_id another monitor is
+/// still in the middle of capturing. If `TriggerDropped` mutated linker
+/// state, this ordering would silently un-pair a perfectly good capture:
+///
+/// T0 recorder broadcasts trigger corr=K
+/// T1 monitor A starts do_capture (~500ms)
+/// T2 recorder batch flush → EventPersisted{K, row}
+/// T3 monitor B (Cold) drains corr=K, sends TriggerDropped
+/// T4 monitor A finishes → FrameCaptured{K, frame}
+///
+/// The actor MUST treat TriggerDropped as a metrics signal only — TTL
+/// eviction is the only authoritative "give up" path.
+#[tokio::test]
+async fn trigger_dropped_does_not_unpair_a_racing_capture() {
+ let db = fresh_db().await;
+ let (linker_tx, linker_rx) = linker_channel();
+ let stop = Arc::new(AtomicBool::new(false));
+ let _actor = spawn_frame_linker(db.clone(), linker_rx, stop.clone());
+
+ let row_id = db.insert_ui_events_batch(&[click_event()]).await.unwrap()[0];
+ let frame_id = db
+ .insert_accessibility_text("TestApp", "Main", "ctx", None)
+ .await
+ .unwrap();
+ let corr_id = next_correlation_id();
+
+ // T2: event persists first (a Cold monitor's drain reaches the
+ // linker after the recorder's batch flush in some interleavings).
+ linker_tx
+ .send(LinkerMessage::EventPersisted(EventPersisted {
+ correlation_id: corr_id,
+ row_id,
+ }))
+ .await
+ .unwrap();
+
+ // T3: a Cold (or capture-erroring) monitor reports the same corr_id
+ // as dropped. This MUST NOT remove the pending event — another
+ // monitor (T4 below) may still pair it.
+ linker_tx
+ .send(LinkerMessage::TriggerDropped {
+ correlation_ids: vec![corr_id],
+ reason: DropReason::Other,
+ })
+ .await
+ .unwrap();
+
+ // T4: the Active monitor finishes its screenshot and reports it.
+ linker_tx
+ .send(LinkerMessage::FrameCaptured(FrameCaptured {
+ frame_id,
+ correlation_ids: vec![corr_id],
+ }))
+ .await
+ .unwrap();
+
+ let observed = wait_for_link(&db, row_id, Duration::from_secs(2)).await;
+ assert_eq!(
+ observed,
+ Some(frame_id),
+ "pending event must survive a racy TriggerDropped — the Active monitor's frame still pairs it"
+ );
+
+ stop.store(true, Ordering::Relaxed);
+}
+
+/// Same race in the reverse order on the frame side: a frame arrived
+/// first with `unmatched = [K]`, sitting in pending_frames. A
+/// TriggerDropped for K must not clear that unmatched slot — the
+/// recorder's batch flush is still in flight and will arrive next.
+#[tokio::test]
+async fn trigger_dropped_does_not_clear_pending_frame_waiters() {
+ let db = fresh_db().await;
+ let (linker_tx, linker_rx) = linker_channel();
+ let stop = Arc::new(AtomicBool::new(false));
+ let _actor = spawn_frame_linker(db.clone(), linker_rx, stop.clone());
+
+ let row_id = db.insert_ui_events_batch(&[click_event()]).await.unwrap()[0];
+ let frame_id = db
+ .insert_accessibility_text("TestApp", "Main", "ctx", None)
+ .await
+ .unwrap();
+ let corr_id = next_correlation_id();
+
+ // Frame first.
+ linker_tx
+ .send(LinkerMessage::FrameCaptured(FrameCaptured {
+ frame_id,
+ correlation_ids: vec![corr_id],
+ }))
+ .await
+ .unwrap();
+ // Per-monitor drop site (Cold drain, capture error, etc.) reports
+ // the same corr_id. Must NOT clear the unmatched slot.
+ linker_tx
+ .send(LinkerMessage::TriggerDropped {
+ correlation_ids: vec![corr_id],
+ reason: DropReason::CaptureError,
+ })
+ .await
+ .unwrap();
+ // Event row arrives last — should still pair.
+ linker_tx
+ .send(LinkerMessage::EventPersisted(EventPersisted {
+ correlation_id: corr_id,
+ row_id,
+ }))
+ .await
+ .unwrap();
+
+ let observed = wait_for_link(&db, row_id, Duration::from_secs(2)).await;
+ assert_eq!(
+ observed,
+ Some(frame_id),
+ "pending frame's unmatched slot must survive a racy TriggerDropped"
+ );
+
+ stop.store(true, Ordering::Relaxed);
+}
+
/// Metrics counters advance on the happy path. Pairs the assertion
/// with end-to-end DB linkage so a regression that breaks one but
/// not the other gets caught.