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(pipes): run fallback preset when the main model times out or errors (#3914) (#3951)

Louis Beaumont53d1b8872ed1
diff --git a/crates/screenpipe-core/src/pipes/mod.rs b/crates/screenpipe-core/src/pipes/mod.rs
index 37b6dcde6..9682ba12d 100644
--- a/crates/screenpipe-core/src/pipes/mod.rs
+++ b/crates/screenpipe-core/src/pipes/mod.rs
@@ -2320,11 +2320,15 @@ impl PipeManager {
run_api_key,
preset_prompt,
active_preset_id,
+ active_preset_idx,
) = if !config.preset.is_empty() {
- // Pick the best available preset using circuit breaker
- let (preset_id, _idx) = self
+ // Pick the best available preset using the circuit breaker, but
+ // start at `retry_depth` so an in-run fallback retry advances to
+ // the next preset even when the failed one's breaker never
+ // tripped (timeouts/crashes don't trip it) — see #3914.
+ let (preset_id, idx) = self
.fallback_registry
- .pick_preset(&config.preset)
+ .pick_preset_with_floor(&config.preset, retry_depth)
.ok_or_else(|| anyhow!("pipe '{}': no presets configured", name))?;
match resolve_preset(&self.pipes_dir, preset_id) {
@@ -2335,8 +2339,8 @@ impl PipeManager {
preset_id,
resolved.model,
resolved.provider,
- if _idx > 0 {
- format!(" (fallback #{})", _idx)
+ if idx > 0 {
+ format!(" (fallback #{})", idx)
} else {
String::new()
}
@@ -2348,6 +2352,7 @@ impl PipeManager {
resolved.api_key,
resolved.prompt,
Some(preset_id.to_string()),
+ Some(idx),
)
}
None => {
@@ -2386,6 +2391,7 @@ impl PipeManager {
resolved.api_key,
resolved.prompt,
None,
+ None,
)
}
None => {
@@ -2397,6 +2403,7 @@ impl PipeManager {
None,
None,
None,
+ None,
)
}
}
@@ -2687,29 +2694,36 @@ impl PipeManager {
cleanup_pipe_token(token, self.token_registry.as_ref());
}
- // Immediate fallback retry: if the pipe failed with a retryable error
- // and there are fallback presets available, retry now instead of waiting
- // for the next scheduled run.
- if !log.success && config.preset.len() > 1 && retry_depth < config.preset.len() - 1 {
- // Check if the circuit breaker picked a different preset for retry
- if let Some((next_preset_id, _)) =
- self.fallback_registry.pick_preset(&config.preset)
- {
- let should_retry = match &active_preset_id {
- Some(current_id) => next_preset_id != current_id.as_str(),
- None => false,
- };
- if should_retry {
+ // Immediate fallback retry: if the run failed and there is another
+ // fallback preset we haven't tried this run, retry now with the next
+ // one instead of waiting for the next scheduled run.
+ //
+ // Advancement is driven by the failed preset's position in the list
+ // (`active_preset_idx`), NOT by its circuit breaker tripping. The
+ // breaker only opens for a narrow set of text-matched provider errors
+ // (`record_failure_from_output`) and never for timeouts or executor
+ // crashes — so gating fallback on it meant the next model silently
+ // never ran when the main one timed out or errored (#3914).
+ let max_attempts = config.preset.len().min(preset_fallback::MAX_FALLBACK_DEPTH);
+ if let (false, Some(cur_idx)) = (log.success, active_preset_idx) {
+ let next_idx = cur_idx + 1;
+ if next_idx < max_attempts {
+ if let Some(next_preset_id) = config.preset.get(next_idx) {
info!(
- "pipe '{}': primary preset failed, immediately retrying with fallback '{}'",
- name, next_preset_id
- );
- // Save log of the failed attempt
+ "pipe '{}': preset '{}' failed, immediately retrying with fallback preset '{}' (attempt {}/{})",
+ name,
+ active_preset_id.as_deref().unwrap_or("?"),
+ next_preset_id,
+ next_idx + 1,
+ max_attempts
+ );
+ // Save the log of the failed attempt before retrying.
self.append_log(name, &log).await;
let _ = self.write_log_to_disk(name, &log);
- // Retry with next preset
+ // Re-enter with the selection floor advanced past the
+ // preset that just failed.
return self
- .run_pipe_with_trigger_inner(name, trigger, retry_depth + 1)
+ .run_pipe_with_trigger_inner(name, trigger, next_idx)
.await;
}
}
diff --git a/crates/screenpipe-core/src/pipes/preset_fallback.rs b/crates/screenpipe-core/src/pipes/preset_fallback.rs
index b63c9e202..204b5430a 100644
--- a/crates/screenpipe-core/src/pipes/preset_fallback.rs
+++ b/crates/screenpipe-core/src/pipes/preset_fallback.rs
@@ -31,7 +31,7 @@ const NON_RETRYABLE_ERROR_TYPES: &[&str] = &[
];
/// Maximum number of presets to try per request.
-const MAX_FALLBACK_DEPTH: usize = 4;
+pub const MAX_FALLBACK_DEPTH: usize = 4;
// ---------------------------------------------------------------------------
// Circuit breaker state
@@ -213,10 +213,38 @@ impl PresetFallbackRegistry {
/// Pick the best preset from the list, respecting circuit breakers.
/// Returns the preset ID and its index in the list.
pub fn pick_preset<'a>(&self, presets: &'a [String]) -> Option<(&'a str, usize)> {
+ self.pick_preset_with_floor(presets, 0)
+ }
+
+ /// Like [`pick_preset`], but only considers presets at or after `floor`.
+ ///
+ /// Drives in-run fallback: after the preset at index `floor - 1` failed this
+ /// run, selection starts at `floor` so the retry advances to the next preset
+ /// **regardless of whether the failed preset's circuit breaker tripped**.
+ /// Timeouts and process crashes never trip the breaker, so a breaker-gated
+ /// selector would re-pick the same failing preset forever (#3914). `floor`
+ /// is clamped to the last index, so callers can pass an ever-incrementing
+ /// retry depth safely.
+ pub fn pick_preset_with_floor<'a>(
+ &self,
+ presets: &'a [String],
+ floor: usize,
+ ) -> Option<(&'a str, usize)> {
+ if presets.is_empty() {
+ return None;
+ }
+ let floor = floor.min(presets.len() - 1);
let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
let mut changed = false;
- for (i, preset_id) in presets.iter().enumerate().take(MAX_FALLBACK_DEPTH) {
+ // `take` before `skip` keeps the "only the first MAX_FALLBACK_DEPTH
+ // presets are ever eligible" cap measured from the start of the list.
+ for (i, preset_id) in presets
+ .iter()
+ .enumerate()
+ .take(MAX_FALLBACK_DEPTH)
+ .skip(floor)
+ {
let breaker = state.presets.entry(preset_id.clone()).or_default();
// Check if cooldown expired → HALF_OPEN
@@ -236,8 +264,9 @@ impl PresetFallbackRegistry {
self.persist(&state);
}
- // All presets are in cooldown — use the first one anyway (best effort)
- presets.first().map(|id| (id.as_str(), 0))
+ // Everything from `floor` is in cooldown — use the floor preset anyway
+ // (best effort) so the run still attempts the next, untried slot.
+ presets.get(floor).map(|id| (id.as_str(), floor))
}
/// Record a successful execution for a preset.
@@ -491,4 +520,59 @@ mod tests {
let registry = PresetFallbackRegistry::new(Path::new("/tmp"));
assert!(registry.record_failure("test", Some("rate_limited")));
}
+
+ /// Hermetic registry in a unique temp dir so persisted state can't leak
+ /// between tests (or between repeated runs).
+ fn fresh_registry(tag: &str) -> PresetFallbackRegistry {
+ let dir = std::env::temp_dir().join(format!("sp_preset_fallback_{}", tag));
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ PresetFallbackRegistry::new(&dir)
+ }
+
+ #[test]
+ fn test_pick_preset_with_floor_advances_without_breaker() {
+ // The core #3914 fix: with NO breaker tripped, raising the floor must
+ // still advance to the next preset (timeouts/crashes never trip it).
+ let registry = fresh_registry("advance");
+ let presets = vec![
+ "primary".to_string(),
+ "fallback".to_string(),
+ "third".to_string(),
+ ];
+
+ assert_eq!(registry.pick_preset_with_floor(&presets, 0), Some(("primary", 0)));
+ assert_eq!(registry.pick_preset_with_floor(&presets, 1), Some(("fallback", 1)));
+ assert_eq!(registry.pick_preset_with_floor(&presets, 2), Some(("third", 2)));
+ }
+
+ #[test]
+ fn test_pick_preset_with_floor_clamps_past_end() {
+ let registry = fresh_registry("clamp");
+ let presets = vec!["primary".to_string(), "fallback".to_string()];
+ // Floor beyond the last index clamps to the last preset rather than
+ // returning None / panicking.
+ assert_eq!(registry.pick_preset_with_floor(&presets, 9), Some(("fallback", 1)));
+ }
+
+ #[test]
+ fn test_pick_preset_with_floor_skips_open_breaker() {
+ let registry = fresh_registry("skip_open");
+ let presets = vec![
+ "primary".to_string(),
+ "fallback".to_string(),
+ "third".to_string(),
+ ];
+ // Trip the fallback's breaker; from floor 1 it should be skipped to
+ // "third", while floor 0 still returns the (closed) primary.
+ registry.record_failure("fallback", Some("rate_limited"));
+ assert_eq!(registry.pick_preset_with_floor(&presets, 0), Some(("primary", 0)));
+ assert_eq!(registry.pick_preset_with_floor(&presets, 1), Some(("third", 2)));
+ }
+
+ #[test]
+ fn test_pick_preset_with_floor_empty() {
+ let registry = fresh_registry("empty");
+ assert_eq!(registry.pick_preset_with_floor(&[], 0), None);
+ }
}