Skip to content

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

refactor(scheduler-gate): remove try_capacity_now and revert reaction to wait_for_capacity

Steven Enamakel24353349f40f
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/gate.rs b/crates/openhuman-core/src/cron/scheduler_gate/gate.rs
index 555fb2d574..7c41906eb4 100644
--- a/crates/openhuman-core/src/cron/scheduler_gate/gate.rs
+++ b/crates/openhuman-core/src/cron/scheduler_gate/gate.rs
@@ -463,45 +463,6 @@ pub async fn wait_for_capacity() -> Option<LlmPermit> {
}
}
-/// Non-blocking sibling of [`wait_for_capacity`] for **best-effort** work that
-/// sits on an interactive path and must never stall it.
-///
-/// Returns a permit only when the gate would admit work right now: the policy
-/// is `Aggressive`/`Normal` and the LLM slot is free. A `Throttled` or
-/// `Paused` gate, or a slot held by background work, answers `None` at once —
-/// the caller skips its optional step instead of queueing behind the gate.
-///
-/// `wait_for_capacity` is the wrong primitive for such callers: in `Paused`
-/// (the user turned background AI off, or the session is signed out) it polls
-/// until the policy changes, which can be never. The web channel's emoji
-/// reaction waited there and held back every reply's delivery (`chat_done`
-/// and the stored row) for as long as background AI stayed off.
-pub fn try_capacity_now() -> Option<LlmPermit> {
- try_capacity_for(current_policy())
-}
-
-fn try_capacity_for(policy: Policy) -> Option<LlmPermit> {
- match policy {
- Policy::Aggressive | Policy::Normal => {
- let permit = llm_permits()
- .try_acquire_owned()
- .ok()
- .map(|p| LlmPermit { _permit: p });
- if permit.is_none() {
- log::debug!("[scheduler_gate] try_capacity_now: llm slot busy — skipping");
- }
- permit
- }
- Policy::Throttled | Policy::Paused { .. } => {
- log::debug!(
- "[scheduler_gate] try_capacity_now: policy={} — skipping",
- policy.as_str()
- );
- None
- }
- }
-}
-
async fn acquire_llm_permit_inner() -> Option<LlmPermit> {
let sem = llm_permits();
match sem.acquire_owned().await {
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/gate_tests.rs b/crates/openhuman-core/src/cron/scheduler_gate/gate_tests.rs
index 9338b3ad75..cf9990a9c9 100644
--- a/crates/openhuman-core/src/cron/scheduler_gate/gate_tests.rs
+++ b/crates/openhuman-core/src/cron/scheduler_gate/gate_tests.rs
@@ -279,32 +279,3 @@ async fn resume_transitions_fire_the_notify() {
.expect("sign-in (signed_out true->false) must wake the resume waiter")
.expect("waiter task must not panic");
}
-
-/// A best-effort interactive caller must not queue behind a paused gate. The
-/// web channel's emoji reaction used `wait_for_capacity` here and, with
-/// background AI switched off, held back every reply's `chat_done` forever.
-#[test]
-fn try_capacity_skips_at_once_while_paused() {
- let _g = lock();
- for reason in [PauseReason::UserDisabled, PauseReason::SignedOut] {
- assert!(
- try_capacity_for(Policy::Paused { reason }).is_none(),
- "a paused gate must answer `no capacity`, not wait"
- );
- }
- assert!(try_capacity_for(Policy::Throttled).is_none());
- assert_eq!(available_llm_permits(), 1, "a skip must not take the slot");
-}
-
-#[test]
-fn try_capacity_takes_the_free_slot_when_admitting() {
- let _g = lock();
- let permit = try_capacity_for(Policy::Normal).expect("free slot under Normal");
- assert_eq!(available_llm_permits(), 0, "permit must occupy the slot");
- assert!(
- try_capacity_for(Policy::Aggressive).is_none(),
- "a held slot must be skipped, not waited on"
- );
- drop(permit);
- assert_eq!(available_llm_permits(), 1, "drop must release the slot");
-}
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/mod.rs b/crates/openhuman-core/src/cron/scheduler_gate/mod.rs
index 86c62286eb..8dd437fb23 100644
--- a/crates/openhuman-core/src/cron/scheduler_gate/mod.rs
+++ b/crates/openhuman-core/src/cron/scheduler_gate/mod.rs
@@ -25,8 +25,8 @@ pub mod gate;
pub mod signals;
pub use gate::{
- current_policy, current_signals, init_global, is_signed_out, set_signed_out, try_capacity_now,
- wait_for_capacity, LlmPermit,
+ current_policy, current_signals, init_global, is_signed_out, set_signed_out, wait_for_capacity,
+ LlmPermit,
};
pub use signals::Signals;
pub use tinymemory_api::host::{PauseReason, Policy};
diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/reactions.rs b/crates/openhuman-core/src/inference/host_runtime/ops/reactions.rs
index 8b03196d3c..cd353bd54f 100644
--- a/crates/openhuman-core/src/inference/host_runtime/ops/reactions.rs
+++ b/crates/openhuman-core/src/inference/host_runtime/ops/reactions.rs
@@ -62,18 +62,13 @@ pub async fn local_ai_should_react(
);
let runtime = crate::inference::local_runtime_config(config);
- // A reaction decorates a reply that is waiting to be delivered, so it may
- // only use the local model when the gate would admit it *now*. Waiting
- // here (`wait_for_capacity`) parks forever while background AI is paused
- // and, with it, the reply's `chat_done`.
- let Some(_permit) = crate::cron::scheduler_gate::try_capacity_now() else {
- tracing::debug!("[local_ai:should_react] scheduler gate has no capacity now, skipping");
+ let Some(_permit) = crate::cron::scheduler_gate::wait_for_capacity().await else {
return Ok(Outcome::single_log(
ReactionDecision {
should_react: false,
emoji: None,
},
- "local inference unavailable right now",
+ "local inference paused while signed out",
));
};
let output = service.prompt(&runtime, &prompt, Some(8), true).await;
diff --git a/crates/openhuman-core/src/web_chat/presentation.rs b/crates/openhuman-core/src/web_chat/presentation.rs
index 59107d7c52..c71fe2ab34 100644
--- a/crates/openhuman-core/src/web_chat/presentation.rs
+++ b/crates/openhuman-core/src/web_chat/presentation.rs
@@ -84,10 +84,8 @@ pub(crate) async fn deliver_response(
// but the interactive web surface must not cut or reformat model output.
let segments = [full_response.to_string()];
- // The reaction is decoration; the reply is not. Bound the wait so nothing
- // the reaction does (a cold local model, a paused scheduler gate) can hold
- // back storing and announcing the reply.
- let reaction_emoji = bounded_reaction(reaction_handle, REACTION_BUDGET, request_id).await;
+ // Await the reaction result (should already be done or nearly done).
+ let reaction_emoji = reaction_handle.await.unwrap_or(None);
if segments.len() <= 1 {
// Store the answer before announcing it. Ordering is the whole point:
@@ -357,34 +355,6 @@ fn publish_chat_done(
// ── Reactions ────────────────────────────────────────────────────────────────
-/// Longest a reply waits for its emoji reaction before it is delivered without
-/// one. Delivery used to await the reaction unbounded, and a reaction parked
-/// on a paused scheduler gate left every reply undelivered: no `chat_done`, no
-/// stored row, and a "Thinking..." indicator that never cleared.
-const REACTION_BUDGET: std::time::Duration = std::time::Duration::from_secs(2);
-
-/// Await the spawned reaction for at most `budget`, aborting it on expiry.
-///
-/// Returns the emoji when the reaction finished in time, `None` when it
-/// declined, failed, panicked or ran out of time.
-async fn bounded_reaction(
- mut handle: tokio::task::JoinHandle<Option<String>>,
- budget: std::time::Duration,
- request_id: &str,
-) -> Option<String> {
- match tokio::time::timeout(budget, &mut handle).await {
- Ok(joined) => joined.unwrap_or(None),
- Err(_) => {
- handle.abort();
- log::warn!(
- "[web-channel] reaction did not finish within {}ms; delivering without it request_id={request_id}",
- budget.as_millis()
- );
- None
- }
- }
-}
-
/// Ask the local model for an emoji reaction to the user's message.
/// Returns `None` if the local model is unavailable or decides no reaction.
async fn try_reaction(user_message: &str) -> Option<String> {
diff --git a/crates/openhuman-core/src/web_chat/presentation_tests.rs b/crates/openhuman-core/src/web_chat/presentation_tests.rs
index 9f93c56f1d..89743bffa4 100644
--- a/crates/openhuman-core/src/web_chat/presentation_tests.rs
+++ b/crates/openhuman-core/src/web_chat/presentation_tests.rs
@@ -228,56 +228,3 @@ async fn delivery_without_a_workspace_persists_nothing() {
)
.await;
}
-
-/// Sets its flag when dropped — i.e. when the task holding it is aborted.
-struct DropFlag(std::sync::Arc<std::sync::atomic::AtomicBool>);
-
-impl Drop for DropFlag {
- fn drop(&mut self) {
- self.0.store(true, std::sync::atomic::Ordering::SeqCst);
- }
-}
-
-/// The reply must not wait on its reaction. A reaction parked on a paused
-/// scheduler gate used to stall `deliver_response` before it stored or
-/// announced anything, so the UI sat on "Thinking..." indefinitely.
-#[tokio::test]
-async fn a_reaction_that_never_finishes_does_not_hold_back_delivery() {
- let dropped = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- let flag = DropFlag(dropped.clone());
- let stuck = tokio::spawn(async move {
- let _flag = flag;
- std::future::pending::<Option<String>>().await
- });
-
- let started = std::time::Instant::now();
- let emoji = bounded_reaction(stuck, std::time::Duration::from_millis(50), "req-stuck").await;
-
- assert_eq!(emoji, None, "an unfinished reaction delivers without an emoji");
- assert!(
- started.elapsed() < std::time::Duration::from_secs(2),
- "delivery must not wait past the reaction budget (took {:?})",
- started.elapsed()
- );
- // Let the aborted task unwind, then confirm it was torn down rather than
- // left running against the local model.
- tokio::time::sleep(std::time::Duration::from_millis(20)).await;
- assert!(
- dropped.load(std::sync::atomic::Ordering::SeqCst),
- "the timed-out reaction task must be aborted"
- );
-}
-
-#[tokio::test]
-async fn a_reaction_that_finishes_in_time_is_kept() {
- let ready = tokio::spawn(async { Some("🎉".to_string()) });
- let emoji = bounded_reaction(ready, REACTION_BUDGET, "req-ready").await;
- assert_eq!(emoji.as_deref(), Some("🎉"));
-}
-
-#[tokio::test]
-async fn a_panicked_reaction_delivers_without_an_emoji() {
- let panicked = tokio::spawn(async { panic!("reaction blew up") });
- let emoji = bounded_reaction(panicked, REACTION_BUDGET, "req-panic").await;
- assert_eq!(emoji, None);
-}