The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(cron): handle scheduler gate signals correctly
Steven Enamakel113c517e3d7a
diff --git a/crates/openhuman-core/src/core/runtime/subscribers.rs b/crates/openhuman-core/src/core/runtime/subscribers.rsindex df0bb73913..152483639b 100644--- a/crates/openhuman-core/src/core/runtime/subscribers.rs+++ b/crates/openhuman-core/src/core/runtime/subscribers.rs@@ -190,7 +190,7 @@ pub(super) fn register_domain_subscribers(// so they observe a real policy on their first iteration (otherwise they// fall back to `Policy::Normal` and miss the initial throttle decision on// battery-powered hosts).- crate::cron::scheduler_gate::init_global(&config);+ crate::cron::scheduler_gate::init_global(config.scheduler_gate.clone());// A headless host (Docker / VPS / CI) has no interactive login; it// hands the core a credential through the environment instead. Thediff --git a/crates/openhuman-core/src/cron/scheduler_gate/gate.rs b/crates/openhuman-core/src/cron/scheduler_gate/gate.rsindex 7c41906eb4..bba5a2efd3 100644--- a/crates/openhuman-core/src/cron/scheduler_gate/gate.rs+++ b/crates/openhuman-core/src/cron/scheduler_gate/gate.rs@@ -1,34 +1,32 @@//! Process-wide singleton: cached policy + cooperative throttling.//!-//! One sampler task refreshes [`Signals`] every 30s and recomputes the-//! [`Policy`]. Workers call [`current_policy`] for cheap reads or-//! [`wait_for_capacity`] to cooperatively block until the host is ready.+//! The machinery (sampling, the cached [`GateCore`], the sampler task and the+//! cooperative wait) is `tinymemory-gate`'s. This file is the host's wiring of+//! it: the process-wide state, the signed-out override, the resume+//! notification, and the per-runtime state that keeps unit tests from sharing+//! any of it.#[cfg(not(test))]use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, OnceLock};-use std::time::Duration;use parking_lot::RwLock;-use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore};+use tokio::sync::{Notify, Semaphore};-use crate::config::{Config, SchedulerGateConfig};-use crate::cron::scheduler_gate::signals::{self, Signals};-use tinymemory_api::host::{decide, PauseReason, Policy};+use crate::config::SchedulerGateConfig;+use tinymemory_gate::{GateCore, SharedCore, SignalEnv, LLM_SLOTS};-/// Process-wide ceiling on concurrent LLM-bound work.-///-/// Held at 1 to keep concurrent local-Ollama / bge-m3 calls (8K context,-/// ~1.3 GB resident each) from saturating local RAM. See-/// `feedback_local_llm_load.md` — backfills with multiple-/// simultaneous Ollama requests have crashed the user's laptop twice.-///-/// Cloud-backend LLM calls bypass this semaphore at the worker layer-/// (see `memory_queue::worker::run_once`) because they're-/// bandwidth-bound, not RAM-bound, and the worker pool itself bounds-/// concurrency upstream. Keeping this at 1 preserves the laptop-RAM-/// contract regardless of backend.-const LLM_SLOTS: usize = 1;+pub use tinymemory_gate::LlmPermit;+pub use tinymemory_gate::{PauseReason, Policy, Signals};++/// The environment variables that override what the hardware reports. The names+/// are user-facing configuration, so they stay the host's; the gate crate only+/// reads whichever names it is handed.+const SIGNAL_ENV: SignalEnv = SignalEnv {+ on_ac_power: "OPENHUMAN_ON_AC_POWER",+ battery_charge: "OPENHUMAN_BATTERY_CHARGE",+ deployment: "OPENHUMAN_DEPLOYMENT",+};#[cfg(not(test))]static LLM_PERMITS: OnceLock<Arc<Semaphore>> = OnceLock::new();@@ -89,33 +87,7 @@ fn llm_permits() -> Arc<Semaphore> {}}-/// RAII guard returned by [`wait_for_capacity`] / [`acquire_llm_permit`].-///-/// While the caller holds an `LlmPermit`, no other LLM-bound caller in-/// the process can acquire one (the global semaphore has a single slot).-/// Drop the permit as soon as the LLM request returns — holding it past-/// post-processing serialises unrelated work for no reason.-///-/// This type is intentionally opaque: callers can't reach into the-/// underlying [`OwnedSemaphorePermit`] and risk forgetting to release it.-#[must_use = "drop the LlmPermit only after the LLM call returns"]-pub struct LlmPermit {- _permit: OwnedSemaphorePermit,-}--impl Drop for LlmPermit {- fn drop(&mut self) {- log::trace!("[scheduler_gate] llm permit released");- }-}--struct State {- cfg: SchedulerGateConfig,- signals: Signals,- policy: Policy,-}--static STATE: OnceLock<Arc<RwLock<State>>> = OnceLock::new();+static STATE: OnceLock<SharedCore> = OnceLock::new();static STARTED: std::sync::Once = std::sync::Once::new();/// Process-wide "session is signed out" override. When `true`, every gate@@ -131,62 +103,16 @@ static STARTED: std::sync::Once = std::sync::Once::new();#[cfg(not(test))]static SIGNED_OUT: AtomicBool = AtomicBool::new(false);-const SAMPLE_INTERVAL: Duration = Duration::from_secs(30);-/// Initialise the gate and spawn the background sampler.////// Idempotent — repeat calls during bootstrap are no-ops. Subsequent config/// reloads should call [`update_config`] instead.-pub fn init_global(config: &Config) {- let cfg = config.scheduler_gate.clone();+pub fn init_global(cfg: SchedulerGateConfig) {STARTED.call_once(|| {- let signals = signals::sample();- let policy = decide(&signals, &cfg);- log::info!(- "[scheduler_gate] startup policy={} mode={} on_ac={} charge={:?} cpu={:.1}% server={}",- policy.as_str(),- cfg.mode.as_str(),- signals.on_ac_power,- signals.battery_charge,- signals.cpu_usage_pct,- signals.server_mode,- );- let state = Arc::new(RwLock::new(State {- cfg,- signals,- policy,- }));+ let signals = tinymemory_gate::sample(&SIGNAL_ENV);+ let state: SharedCore = Arc::new(RwLock::new(GateCore::new(cfg, signals)));let _ = STATE.set(state.clone());-- tokio::spawn(async move {- loop {- tokio::time::sleep(SAMPLE_INTERVAL).await;- // Sampling does a brief blocking sleep + sysinfo refresh —- // push it off the async runtime.- let signals = match tokio::task::spawn_blocking(signals::sample).await {- Ok(s) => s,- Err(err) => {- log::warn!("[scheduler_gate] sampler join error: {err:#}");- continue;- }- };- let mut guard = state.write();- let next = decide(&signals, &guard.cfg);- if next != guard.policy {- log::info!(- "[scheduler_gate] policy {} -> {} (on_ac={} charge={:?} cpu={:.1}% server={})",- guard.policy.as_str(),- next.as_str(),- signals.on_ac_power,- signals.battery_charge,- signals.cpu_usage_pct,- signals.server_mode,- );- }- guard.signals = signals;- guard.policy = next;- }- });+ tinymemory_gate::spawn_sampler(state, SIGNAL_ENV);});}@@ -225,13 +151,7 @@ pub fn update_config(cfg: SchedulerGateConfig) {let Some(state) = STATE.get() else {return;};- let resumed = {- let mut guard = state.write();- let was_paused = matches!(guard.policy, Policy::Paused { .. });- guard.cfg = cfg;- guard.policy = decide(&guard.signals, &guard.cfg);- was_paused && !matches!(guard.policy, Policy::Paused { .. })- };+ let resumed = state.write().update_config(cfg);if resumed {resume_notify().notify_one();}@@ -257,7 +177,7 @@ pub fn current_policy() -> Policy {}STATE.get()- .map(|s| s.read().policy)+ .map(|s| s.read().policy()).unwrap_or(Policy::Normal)}@@ -372,7 +292,7 @@ impl Drop for SignedOutTestGuard {/// Most recent sampled signals, or a neutral default if the sampler hasn't run.pub fn current_signals() -> Signals {- STATE.get().map(|s| s.read().signals).unwrap_or(Signals {+ STATE.get().map(|s| s.read().signals()).unwrap_or(Signals {on_ac_power: true,battery_charge: None,cpu_usage_pct: 0.0,@@ -384,102 +304,19 @@ pub fn current_signals() -> Signals {/// work, then hand back an [`LlmPermit`] that holds a slot in the global/// LLM semaphore.///-/// Policy-driven backoff happens **before** semaphore acquisition so a-/// `Paused` mode doesn't pile up tasks queued for the slot — they sit-/// in the pause-poll loop, not in the semaphore wait queue.-///-/// * **Aggressive / Normal** — wait for the global slot; return immediately-/// once granted.-/// * **Throttled** — sleep `throttled_backoff_ms` first so concurrent-/// workers serialise themselves, then acquire the slot.-/// * **Paused** — poll every `paused_poll_ms` until the policy changes,-/// then acquire the slot.-///-/// Drop the returned [`LlmPermit`] as soon as the LLM call returns.+/// See [`tinymemory_gate::wait_for_capacity`] for the per-policy behaviour. The+/// signed-out override is only honoured once the gate has been initialised by+/// [`init_global`]: in unit tests where it never was, there is no+/// background-worker pool to stand down, but the per-runtime `signed_out` flag+/// can still be `true` from an earlier test that exercised the credentials / 401+/// paths, and honouring it would make every later caller poll forever (the+/// `openhuman::agent::triage::evaluator::tests::*` hangs reported after #1516).////// Returns `None` only if the global LLM semaphore has been closed-/// (never happens in production — the semaphore lives for the lifetime-/// of the process). Callers can safely treat `None` as "skip the+/// (never happens in production). Callers can safely treat `None` as "skip the/// gate" rather than propagating an error.pub async fn wait_for_capacity() -> Option<LlmPermit> {- loop {- // Signed-out override is checked first and uses the same paused-poll- // cadence as the rest of the Paused arm. Holding here (rather than- // returning) means workers naturally resume the instant the user- // signs back in — no respawn dance, no missed wakeups.- //- // We gate on `STATE.get().is_some()` so the override only fires once- // the gate has been initialised by `init_global`. In unit tests- // where `init_global` was never called there is no background-worker- // pool to stand down, but the per-runtime `signed_out` flag can- // still be `true` from an earlier test that exercised the credentials- // / 401 paths (`clear_session`, RPC 401 dispatch, or- // `SessionExpiredSubscriber.handle()`). Without the gate, every- // subsequent caller of `wait_for_capacity` polls forever on the- // 60-second fallback cadence — manifest as the- // `openhuman::agent::triage::evaluator::tests::*` hangs reported- // after #1516.- if STATE.get().is_some() && is_signed_out() {- let paused_ms = STATE- .get()- .map(|s| s.read().cfg.paused_poll_ms)- .unwrap_or(60_000);- log::trace!("[scheduler_gate] paused (signed_out); polling every {paused_ms}ms");- tokio::time::sleep(Duration::from_millis(paused_ms)).await;- continue;- }-- let (policy, throttled_ms, paused_ms) = match STATE.get() {- Some(state) => {- let g = state.read();- (g.policy, g.cfg.throttled_backoff_ms, g.cfg.paused_poll_ms)- }- None => {- // Gate not initialised (unit tests, early bootstrap).- // Acquire directly — no policy to consult.- return acquire_llm_permit_inner().await;- }- };- match policy {- Policy::Aggressive | Policy::Normal => {- return acquire_llm_permit_inner().await;- }- Policy::Throttled => {- log::trace!(- "[scheduler_gate] throttled — sleeping {throttled_ms}ms before permit acquire"- );- tokio::time::sleep(Duration::from_millis(throttled_ms)).await;- return acquire_llm_permit_inner().await;- }- Policy::Paused { reason } => {- log::debug!(- "[scheduler_gate] paused ({}); polling every {paused_ms}ms",- reason.as_str()- );- tokio::time::sleep(Duration::from_millis(paused_ms)).await;- // re-evaluate; user may have toggled the gate back on.- }- }- }-}--async fn acquire_llm_permit_inner() -> Option<LlmPermit> {- let sem = llm_permits();- match sem.acquire_owned().await {- Ok(permit) => {- log::trace!("[scheduler_gate] llm permit acquired");- Some(LlmPermit { _permit: permit })- }- Err(_) => {- // Semaphore closed — should never happen since we never- // close it. Log loudly and let the caller proceed without- // a permit so the pipeline doesn't deadlock.- log::warn!(- "[scheduler_gate] llm semaphore closed unexpectedly — proceeding without a permit"- );- None- }- }+ tinymemory_gate::wait_for_capacity(STATE.get(), is_signed_out, &llm_permits()).await}/// Test/diagnostic hook: try to grab a permit without consulting the@@ -488,10 +325,7 @@ async fn acquire_llm_permit_inner() -> Option<LlmPermit> {/// [`wait_for_capacity`] so the policy backoff applies.#[cfg(test)]pub fn try_acquire_llm_permit() -> Option<LlmPermit> {- let sem = llm_permits();- sem.try_acquire_owned()- .ok()- .map(|p| LlmPermit { _permit: p })+ tinymemory_gate::try_acquire_llm_permit(&llm_permits())}/// Number of permits currently available. Test-only diagnostic.diff --git a/crates/openhuman-core/src/cron/scheduler_gate/mod.rs b/crates/openhuman-core/src/cron/scheduler_gate/mod.rsindex 8dd437fb23..9d1e0d9366 100644--- a/crates/openhuman-core/src/cron/scheduler_gate/mod.rs+++ b/crates/openhuman-core/src/cron/scheduler_gate/mod.rs@@ -22,14 +22,12 @@//! caller resumes the moment the user toggles the gate back on.pub mod gate;-pub mod signals;pub use gate::{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};+pub use gate::{PauseReason, Policy, Signals};#[cfg(test)]pub(crate) use gate::SignedOutTestGuard;diff --git a/crates/openhuman-core/src/cron/scheduler_gate/signals.rs b/crates/openhuman-core/src/cron/scheduler_gate/signals.rsdeleted file mode 100644index 335285e40e..0000000000--- a/crates/openhuman-core/src/cron/scheduler_gate/signals.rs+++ /dev/null@@ -1,200 +0,0 @@-//! Host signals: power state, CPU pressure, deployment mode.-//!-//! Sampled on a 30s cadence by [`crate::cron::scheduler_gate::gate`]; this-//! file just captures one snapshot at a time.--use std::path::Path;-use std::time::Duration;--use sysinfo::System;--/// The snapshot type and the pure decision over it live in the memory-/// contract crate; this file only samples the host hardware.-pub use tinymemory_api::host::Signals;--/// Sample once. Cheap (~ms-scale) — safe to call from a 30s background task.-pub fn sample() -> Signals {- let (on_ac, charge) = sample_power();- let cpu_usage_pct = sample_cpu();- let server_mode = detect_server_mode(charge.is_none());- Signals {- on_ac_power: on_ac,- battery_charge: charge,- cpu_usage_pct,- server_mode,- }-}--// ---- power -----------------------------------------------------------------fn sample_power() -> (bool, Option<f32>) {- // Env overrides win — useful for CI, container hosts that misreport,- // and manual debugging of the throttle path on a desktop. Only- // explicit truthy/falsy tokens count: garbage values yield None so- // the real probe still gets to answer (vs. silently coercing to- // "on battery" and triggering throttling on every misconfigured host).- let env_on_ac = std::env::var("OPENHUMAN_ON_AC_POWER").ok().and_then(|v| {- match v.to_ascii_lowercase().as_str() {- "1" | "true" | "yes" => Some(true),- "0" | "false" | "no" => Some(false),- _ => None,- }- });- let env_charge = std::env::var("OPENHUMAN_BATTERY_CHARGE")- .ok()- .and_then(|v| v.parse::<f32>().ok())- .map(|v| v.clamp(0.0, 1.0));- if let (Some(ac), Some(c)) = (env_on_ac, env_charge) {- return (ac, Some(c));- }-- resolve_power(env_on_ac, env_charge, battery_probe())-}--fn resolve_power(- env_on_ac: Option<bool>,- env_charge: Option<f32>,- probe: Option<BatteryProbe>,-) -> (bool, Option<f32>) {- match probe {- Some(probe) => (- env_on_ac.unwrap_or(probe.on_ac),- env_charge.or(probe.charge),- ),- // No probe answer — either it failed, or the `scheduler-gate` feature is- // compiled out. Treat as "plugged in, no battery", which yields- // Normal/Aggressive rather than Throttled. Erring the other way would- // throttle every server and container, where a battery probe never- // succeeds anyway.- None => (env_on_ac.unwrap_or(true), env_charge),- }-}--/// The two facts the scheduler cares about. Both primitives, deliberately: the-/// type stays ungated so `sample_power` needs no `#[cfg]` around its `match`.-struct BatteryProbe {- on_ac: bool,- charge: Option<f32>,-}--/// The real probe, when `scheduler-gate` is compiled in.-#[cfg(feature = "scheduler-gate")]-fn battery_probe() -> Option<BatteryProbe> {- match probe_battery() {- Ok(probe) => Some(probe),- Err(err) => {- // Probe failure on Linux often just means no /sys/class/power_supply- // entries (server, container). Log once at debug because this fires- // every 30s on the sampler tick.- log::debug!("[scheduler_gate] battery probe failed: {err:#}");- None- }- }-}--/// Off-state: no hardware probe at all.-///-/// Deliberately the same answer the real probe gives on a machine with no-/// battery, so the throttle path behaves identically to running on a server —-/// a configuration this code already handles — rather than down a new branch.-/// The visible consequence is that `require_ac_power` and `battery_floor` stop-/// being enforced; CPU throttling and server-mode detection are unaffected.-#[cfg(not(feature = "scheduler-gate"))]-fn battery_probe() -> Option<BatteryProbe> {- None-}--#[cfg(feature = "scheduler-gate")]-fn probe_battery() -> Result<BatteryProbe, starship_battery::Error> {- let manager = starship_battery::Manager::new()?;- let mut any = false;- let mut on_ac = true; // if all batteries report Charging/Full, we're on AC.- let mut total: f32 = 0.0;- let mut count: f32 = 0.0;- for maybe in manager.batteries()? {- let battery = maybe?;- any = true;- // Discharging is the only state that conclusively means "on battery".- // Unknown / Empty / Full / Charging all imply the AC adapter is- // present (or at minimum that the OS isn't draining the pack).- if matches!(battery.state(), starship_battery::State::Discharging) {- on_ac = false;- }- include_charge_sample(&mut total, &mut count, battery.state_of_charge().value);- }- let charge = if any && count > 0.0 {- Some((total / count).clamp(0.0, 1.0))- } else {- None- };- Ok(BatteryProbe { on_ac, charge })-}--fn include_charge_sample(total: &mut f32, count: &mut f32, charge: f32) {- if charge.is_finite() {- *total += charge;- *count += 1.0;- }-}--// ---- cpu -------------------------------------------------------------------fn sample_cpu() -> f32 {- // Build a *fresh* `System` every sample instead of reusing a long-lived- // one. sysinfo 0.33's Linux CPU refresh builds a per-core Vec on its first- // refresh (sized to the `cpuN` lines in /proc/stat) and then, on every- // later refresh, indexes that Vec by line position. If the visible core- // count later grows — CPU hotplug, or a Proxmox / cloud host re-balancing- // vCPUs at runtime — the next refresh indexes past the Vec and panics- // ("index out of bounds: the len is N but the index is N"). A process-wide- // System captured the boot-time core count, so on such hosts *every* 30s- // tick panicked thereafter (Sentry CORE-RUST-ED). Building per call means- // both refreshes below always see the current core count, so the index- // stays in bounds.- //- // Two refreshes spaced ~MINIMUM_CPU_UPDATE_INTERVAL apart give sysinfo a- // real delta to compute usage from; we only read the global aggregate, so- // not retaining per-core state across calls costs us nothing. The interval- // is small enough to run on the 30s sampler tick without noticeable cost.- let mut sys = System::new();- sys.refresh_cpu_usage();- std::thread::sleep(Duration::from_millis(- sysinfo::MINIMUM_CPU_UPDATE_INTERVAL.as_millis() as u64 + 50,- ));- sys.refresh_cpu_usage();- sys.global_cpu_usage()-}--// ---- deployment mode -------------------------------------------------------fn detect_server_mode(no_battery: bool) -> bool {- if let Ok(v) = std::env::var("OPENHUMAN_DEPLOYMENT") {- if v.eq_ignore_ascii_case("server") {- return true;- }- if matches!(v.to_ascii_lowercase().as_str(), "desktop" | "laptop") {- return false;- }- }- if std::env::var("KUBERNETES_SERVICE_HOST").is_ok() {- return true;- }- if Path::new("/.dockerenv").exists() {- return true;- }- // Heuristic of last resort: a Linux box with no battery and no display- // server set is almost certainly a server. We *don't* infer server-mode- // from "no battery" alone — desktops have no battery either.- if cfg!(target_os = "linux")- && no_battery- && std::env::var("DISPLAY").is_err()- && std::env::var("WAYLAND_DISPLAY").is_err()- {- return true;- }- false-}--#[cfg(test)]-#[path = "signals_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/cron/scheduler_gate/signals_tests.rs b/crates/openhuman-core/src/cron/scheduler_gate/signals_tests.rsdeleted file mode 100644index 77dc56534e..0000000000--- a/crates/openhuman-core/src/cron/scheduler_gate/signals_tests.rs+++ /dev/null@@ -1,73 +0,0 @@-use super::*;--/// `sample_cpu` must always yield a finite percentage in `0..=100`, and-/// must not panic — the regression guard for Sentry CORE-RUST-ED, where a-/// long-lived `System` panicked with an out-of-bounds index after the-/// host's visible core count grew. A fresh `System` per call keeps the-/// per-core Vec sized to the current core count.-#[test]-fn sample_cpu_is_finite_and_bounded() {- let pct = sample_cpu();- assert!(pct.is_finite(), "cpu usage should be finite, got {pct}");- assert!(- (0.0..=100.0).contains(&pct),- "cpu usage out of range: {pct}"- );-}--/// Successive samples each build their own `System`; neither call shares-/// state with the other, so both must stay finite and in range.-#[test]-fn sample_cpu_repeatable() {- for _ in 0..2 {- let pct = sample_cpu();- assert!(pct.is_finite() && (0.0..=100.0).contains(&pct), "{pct}");- }-}--/// Full snapshot smoke: `sample()` returns well-formed values and-/// never panics through the CPU path.-#[test]-fn signals_sample_smoke() {- let s = sample();- assert!(s.cpu_usage_pct.is_finite());- assert!((0.0..=100.0).contains(&s.cpu_usage_pct));- if let Some(charge) = s.battery_charge {- assert!((0.0..=1.0).contains(&charge));- }-}--#[test]-fn missing_battery_probe_falls_back_to_ac_without_charge() {- assert_eq!(resolve_power(None, None, None), (true, None));-}--#[test]-fn non_finite_battery_readings_are_ignored() {- let mut total = 0.0;- let mut count = 0.0;- include_charge_sample(&mut total, &mut count, f32::NAN);- include_charge_sample(&mut total, &mut count, f32::INFINITY);- include_charge_sample(&mut total, &mut count, 0.75);- assert_eq!((total, count), (0.75, 1.0));-}--#[test]-fn power_env_overrides_apply_independently() {- let probe = || BatteryProbe {- on_ac: false,- charge: Some(0.25),- };- assert_eq!(- resolve_power(Some(true), None, Some(probe())),- (true, Some(0.25))- );- assert_eq!(- resolve_power(None, Some(0.8), Some(probe())),- (false, Some(0.8))- );- assert_eq!(- resolve_power(Some(false), Some(0.4), None),- (false, Some(0.4))- );-}