Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(orchestration): prevent stale busy sessions and lost retries

Steven Enamakel37375bd12102
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions.rs b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
index dcb7bd1455..0599141b89 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions.rs
@@ -142,8 +142,18 @@ fn entry_for(workspace_dir: &Path) -> Arc<Entry> {
/// Replace a workspace's failing durable store with an in-memory one that starts
/// from the same records, so delivery keeps working in this process. The log on
/// disk is left as it is and replays on the next boot.
-fn degrade_to_memory(workspace_dir: &Path) -> Arc<Entry> {
+///
+/// Serialized per process: when two records hit the failure together, the second
+/// finds the first's fallback already installed and uses it, rather than
+/// installing a second one the delivery loop would never see. `failed` is the
+/// router the caller just saw fail.
+fn degrade_to_memory(workspace_dir: &Path, failed: &Arc<CompletionRouter>) -> Arc<Entry> {
+ static DEGRADE_LOCK: Mutex<()> = Mutex::new(());
+ let _serial = DEGRADE_LOCK.lock().unwrap_or_else(|p| p.into_inner());
let old = entry_for(workspace_dir);
+ if !Arc::ptr_eq(&old.router, failed) {
+ return old;
+ }
let store = Arc::new(InMemoryCompletionStore::new());
for record in old.store.list(None) {
if let Err(error) = store.put(&record) {
@@ -338,7 +348,10 @@ pub(crate) async fn record_outcome(
"[background_completions] store write failed after retries; continuing in memory \
task_id={task_id} thread_id={thread_id} error={error}"
);
- outcome_of_record = degrade_to_memory(workspace_dir).router.record(record).await;
+ outcome_of_record = degrade_to_memory(workspace_dir, &router)
+ .router
+ .record(record)
+ .await;
}
match outcome_of_record {
Ok(RecordOutcome::Recorded { .. }) => log::debug!(
diff --git a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
index b616574855..d68c5c4a75 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_completions_tests.rs
@@ -722,3 +722,21 @@ async fn a_store_that_keeps_failing_degrades_to_memory_instead_of_losing_the_res
assert_eq!(pending.len(), 1, "the result is held in memory");
assert_eq!(pending[0].result.text, "must not be lost");
}
+
+#[tokio::test]
+async fn concurrent_degradation_installs_one_fallback() {
+ let _guard = crate::config::TEST_ENV_LOCK.lock().await;
+ let ws = workspace();
+ let w = ws.path();
+ let failing = router_for_workspace(w);
+
+ // Two records saw the same failing router; both ask to degrade.
+ let first = degrade_to_memory(w, &failing);
+ let second = degrade_to_memory(w, &failing);
+
+ assert!(
+ Arc::ptr_eq(&first.router, &second.router),
+ "the second caller reuses the fallback the first installed"
+ );
+ assert!(Arc::ptr_eq(&entry_for(w).router, &first.router));
+}
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
index 482277dfff..65b1e201b6 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery.rs
@@ -75,6 +75,25 @@ fn is_busy(thread_id: &str) -> bool {
})
}
+/// Forget every in-flight turn on `thread_id`. A turn that is cancelled
+/// cooperatively (Stop) can end without `AgentTurnCompleted` or `AgentError`, and
+/// its session would otherwise stay "busy" and defer this thread's deliveries
+/// until restart. Returns how many sessions were cleared.
+pub(crate) fn clear_busy_for_thread(thread_id: &str) -> usize {
+ let mut busy = busy().lock().expect("background_delivery busy poisoned");
+ let before = busy.len();
+ busy.retain(|session| {
+ background_completions::thread_for_session(session).as_deref() != Some(thread_id)
+ });
+ let cleared = before - busy.len();
+ if cleared > 0 {
+ log::debug!(
+ "[background_delivery] cleared {cleared} stale busy session(s) thread_id={thread_id}"
+ );
+ }
+ cleared
+}
+
struct BackgroundDeliveryHandler;
#[async_trait]
@@ -382,6 +401,19 @@ where
router.release(&task_ids);
}
}
+ // A batch can mix records at different attempt counts: some gave
+ // up above, the rest are still pending. Nothing else would wake a
+ // quiet thread for them, so ask for a retry.
+ if retry_after.is_none() {
+ if let Some(attempts) = router
+ .pending_for(&thread_id)
+ .iter()
+ .map(|r| r.attempts)
+ .max()
+ {
+ retry_after = Some(retry_backoff(attempts));
+ }
+ }
}
}
}
diff --git a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
index acaef81409..dfc5e83646 100644
--- a/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
+++ b/crates/openhuman-core/src/agent/orchestration/background_delivery_tests.rs
@@ -686,3 +686,59 @@ async fn boot_recovery_schedules_a_delivery_for_every_thread_with_undelivered_re
"a workspace is scanned once per process"
);
}
+
+#[tokio::test]
+async fn a_cancelled_turn_does_not_leave_the_thread_busy() {
+ // A cooperatively cancelled turn publishes no terminal event; Stop clears it.
+ let _g = test_guard().await;
+ let session = r#"{"client_id":"c","thread_id":"bd-stale-thread"}"#;
+ let other = r#"{"client_id":"c","thread_id":"bd-other-thread"}"#;
+ mark_busy(session);
+ mark_busy(other);
+ assert!(is_busy("bd-stale-thread"));
+
+ assert_eq!(clear_busy_for_thread("bd-stale-thread"), 1);
+
+ assert!(!is_busy("bd-stale-thread"));
+ assert!(is_busy("bd-other-thread"), "other threads are untouched");
+ clear_busy(other);
+}
+
+#[tokio::test]
+async fn a_mixed_batch_that_partly_gives_up_still_retries_the_rest() {
+ let _g = test_guard().await;
+ let ws = workspace();
+ let w = ws.path();
+ record(w, "bd-mixed", "sub-old", "old", "thread-mixed").await;
+ let router = router_for_workspace(w);
+ for _ in 0..(DEFAULT_MAX_ATTEMPTS - 1) {
+ try_deliver_with(
+ "thread-mixed".into(),
+ router.clone(),
+ |_t, _n| async move { Err::<String, String>("checkout failed".to_string()) },
+ |_t, _n| async move { unreachable!("below the ceiling") },
+ )
+ .await;
+ }
+ // A newer result joins the old one, which is on its last attempt.
+ record(w, "bd-mixed", "sub-new", "new", "thread-mixed").await;
+
+ let gave_up = Arc::new(Mutex::new(String::new()));
+ let sink = Arc::clone(&gave_up);
+ let retry = try_deliver_with(
+ "thread-mixed".into(),
+ router,
+ |_t, _n| async move { Err::<String, String>("checkout failed".to_string()) },
+ move |_t, notice| async move {
+ *sink.lock().expect("sink") = notice;
+ },
+ )
+ .await;
+
+ assert!(gave_up.lock().expect("sink").contains("sub-old"));
+ assert!(
+ retry.is_some(),
+ "the newer record must still be rescheduled"
+ );
+ assert_eq!(pending_ids(w, "thread-mixed"), ["sub-new"]);
+}
diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
index 461fc79cca..a0d221dd97 100644
--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs
@@ -114,6 +114,12 @@ async fn cancel_chat_inner(
// system turn on the thread, which reads as "Stop did nothing". Abort them
// first, then drop anything already queued for delivery, so no result lands
// in the gap. A scoped cancel names one turn and leaves the rest alone.
+ // A turn cancelled cooperatively may never publish a terminal event, which
+ // would leave its session marked busy and defer this thread's background
+ // deliveries until restart.
+ if removed_request_id.is_some() || request_id.is_none() {
+ crate::agent::orchestration::background_delivery::clear_busy_for_thread(thread_id);
+ }
let subagents_cancelled = if request_id.is_none() {
// Gate completion recording before aborting: Tokio abort is
// cooperative, so a child already finishing can otherwise enqueue in