Skip to content

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

feat(cron): add scheduler gate module with decide, signals, and throttle

Steven Enamakel808938c71ac6
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/decide.rs b/crates/openhuman-core/src/cron/scheduler_gate/decide.rs
new file mode 100644
index 0000000000..eb38455336
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/decide.rs
@@ -0,0 +1,97 @@
+//! Gate decision function — turn sampled host [`Signals`] plus the user's
+//! [`SchedulerGateConfig`] into a [`Policy`].
+//!
+//! Pure: no I/O, no clock, no globals. Sampling the signals (battery probe,
+//! CPU sampler, server-mode detection) stays in the host that owns the
+//! hardware; this module only owns the decision.
+
+use crate::config::schema::{PauseReason, Policy, SchedulerGateConfig, SchedulerGateMode};
+
+/// One snapshot of the host signals the gate decides on.
+#[derive(Debug, Clone, Copy)]
+pub struct Signals {
+ pub on_ac_power: bool,
+ /// 0.0..=1.0, or `None` when no battery sensor is present (most servers).
+ pub battery_charge: Option<f32>,
+ /// Recent global CPU usage, 0..100.
+ pub cpu_usage_pct: f32,
+ pub server_mode: bool,
+}
+
+/// Compute the current [`Policy`] from sampled signals + user config.
+///
+/// Order of evaluation matters — explicit user overrides win first, then
+/// deployment mode, then dynamic host signals.
+pub fn decide(signals: &Signals, cfg: &SchedulerGateConfig) -> Policy {
+ match cfg.mode {
+ SchedulerGateMode::Off => {
+ return Policy::Paused {
+ reason: PauseReason::UserDisabled,
+ }
+ }
+ SchedulerGateMode::AlwaysOn => return Policy::Aggressive,
+ SchedulerGateMode::Auto => {}
+ }
+
+ if signals.server_mode {
+ return Policy::Aggressive;
+ }
+
+ // Clamp config-supplied thresholds so a malformed config.toml (e.g.
+ // `battery_floor = 1.5` or a negative cpu threshold) can't silently
+ // disable / force throttling — the field is `f32` and serde won't
+ // reject out-of-domain values for us.
+ let battery_floor = cfg.battery_floor.clamp(0.0, 1.0);
+ let cpu_threshold = cfg.cpu_busy_threshold_pct.clamp(0.0, 100.0);
+ let cpu_severe = cfg.cpu_severe_pct.clamp(0.0, 100.0);
+
+ // ── Pause checks come BEFORE the throttle gate — these are the
+ // "stand down completely" signals. Hierarchy:
+ // 1. user policy (`require_ac_power` on battery)
+ // 2. host on fire (CPU severely pegged)
+
+ // (1) Power-aware stand-down. Only consult `on_ac_power` when the
+ // user explicitly opts in — many desktops report `false` here
+ // because they have no battery + no AC sensor, and we don't
+ // want to silently disable background work for them.
+ if cfg.require_ac_power && !signals.on_ac_power {
+ log::debug!(
+ "[scheduler_gate] policy decision: paused on_battery (require_ac_power=true, on_ac={})",
+ signals.on_ac_power
+ );
+ return Policy::Paused {
+ reason: PauseReason::OnBattery,
+ };
+ }
+
+ // (2) Hard CPU ceiling — at >= cpu_severe_pct the host is unusable;
+ // a Throttled 30s backoff is not enough, hold every job.
+ if signals.cpu_usage_pct >= cpu_severe {
+ log::debug!(
+ "[scheduler_gate] policy decision: paused cpu_pressure (cpu={:.1}% >= severe={:.1}%)",
+ signals.cpu_usage_pct,
+ cpu_severe,
+ );
+ return Policy::Paused {
+ reason: PauseReason::CpuPressure,
+ };
+ }
+
+ let battery_ok = signals.on_ac_power
+ || signals
+ .battery_charge
+ .map(|c| c >= battery_floor)
+ .unwrap_or(true); // no battery present == treat as plugged in
+
+ let cpu_ok = signals.cpu_usage_pct <= cpu_threshold;
+
+ if battery_ok && cpu_ok {
+ Policy::Normal
+ } else {
+ Policy::Throttled
+ }
+}
+
+#[cfg(test)]
+#[path = "scheduler_gate_decide_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/decide_tests.rs b/crates/openhuman-core/src/cron/scheduler_gate/decide_tests.rs
new file mode 100644
index 0000000000..97eb27c6a4
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/decide_tests.rs
@@ -0,0 +1,282 @@
+//! Tests for the gate decision function.
+
+use super::*;
+
+fn cfg(mode: SchedulerGateMode) -> SchedulerGateConfig {
+ SchedulerGateConfig {
+ mode,
+ battery_floor: 0.8,
+ cpu_busy_threshold_pct: 70.0,
+ throttled_backoff_ms: 30_000,
+ paused_poll_ms: 60_000,
+ cpu_severe_pct: 95.0,
+ require_ac_power: false,
+ }
+}
+
+fn signals(on_ac: bool, charge: Option<f32>, cpu: f32, server: bool) -> Signals {
+ Signals {
+ on_ac_power: on_ac,
+ battery_charge: charge,
+ cpu_usage_pct: cpu,
+ server_mode: server,
+ }
+}
+
+#[test]
+fn off_mode_pauses() {
+ let p = decide(
+ &signals(true, None, 5.0, true),
+ &cfg(SchedulerGateMode::Off),
+ );
+ assert_eq!(
+ p,
+ Policy::Paused {
+ reason: PauseReason::UserDisabled
+ }
+ );
+}
+
+#[test]
+fn pause_reason_helper_returns_user_disabled_for_off_mode() {
+ let p = decide(
+ &signals(true, None, 5.0, false),
+ &cfg(SchedulerGateMode::Off),
+ );
+ assert_eq!(p.pause_reason(), Some(PauseReason::UserDisabled));
+}
+
+#[test]
+fn pause_reason_helper_returns_none_for_non_paused() {
+ assert_eq!(Policy::Aggressive.pause_reason(), None);
+ assert_eq!(Policy::Normal.pause_reason(), None);
+ assert_eq!(Policy::Throttled.pause_reason(), None);
+}
+
+#[test]
+fn pause_reason_as_str_round_trips_each_variant() {
+ assert_eq!(PauseReason::UserDisabled.as_str(), "user_disabled");
+ assert_eq!(PauseReason::OnBattery.as_str(), "on_battery");
+ assert_eq!(PauseReason::CpuPressure.as_str(), "cpu_pressure");
+ assert_eq!(PauseReason::SignedOut.as_str(), "signed_out");
+ assert_eq!(PauseReason::Unknown.as_str(), "unknown");
+}
+
+#[test]
+fn always_on_overrides_signals() {
+ // discharging laptop at 10% with 99% CPU — still Aggressive.
+ let p = decide(
+ &signals(false, Some(0.10), 99.0, false),
+ &cfg(SchedulerGateMode::AlwaysOn),
+ );
+ assert_eq!(p, Policy::Aggressive);
+}
+
+#[test]
+fn server_mode_is_aggressive() {
+ let p = decide(
+ &signals(false, None, 50.0, true),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Aggressive);
+}
+
+#[test]
+fn plugged_in_idle_is_normal() {
+ let p = decide(
+ &signals(true, Some(0.45), 20.0, false),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Normal);
+}
+
+#[test]
+fn battery_above_floor_is_normal() {
+ let p = decide(
+ &signals(false, Some(0.85), 20.0, false),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Normal);
+}
+
+#[test]
+fn battery_below_floor_throttles() {
+ let p = decide(
+ &signals(false, Some(0.30), 20.0, false),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Throttled);
+}
+
+#[test]
+fn busy_cpu_throttles_even_when_plugged_in() {
+ let p = decide(
+ &signals(true, Some(0.95), 90.0, false),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Throttled);
+}
+
+#[test]
+fn out_of_range_battery_floor_is_clamped() {
+ // 1.5 clamped to 1.0 — with charge < 1.0 on battery, must throttle.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.battery_floor = 1.5;
+ let p = decide(&signals(false, Some(0.99), 10.0, false), &c);
+ assert_eq!(p, Policy::Throttled);
+ // -1.0 clamped to 0.0 — any non-zero charge passes the floor.
+ c.battery_floor = -1.0;
+ let p = decide(&signals(false, Some(0.05), 10.0, false), &c);
+ assert_eq!(p, Policy::Normal);
+}
+
+#[test]
+fn out_of_range_cpu_threshold_is_clamped() {
+ // 200.0 clamped to 100.0 — nothing above it, never throttles on CPU.
+ // Also push `cpu_severe_pct` to its max so the new pause-on-severe
+ // arm doesn't trip first.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.cpu_busy_threshold_pct = 200.0;
+ c.cpu_severe_pct = 100.0;
+ let p = decide(&signals(true, None, 99.0, false), &c);
+ assert_eq!(p, Policy::Normal);
+ // -10.0 clamped to 0.0 — any positive CPU usage throttles.
+ c.cpu_busy_threshold_pct = -10.0;
+ let p = decide(&signals(true, None, 5.0, false), &c);
+ assert_eq!(p, Policy::Throttled);
+}
+
+#[test]
+fn no_battery_treated_as_plugged_in() {
+ // Desktop / server with no battery sensor — treat as AC.
+ let p = decide(
+ &signals(false, None, 20.0, false),
+ &cfg(SchedulerGateMode::Auto),
+ );
+ assert_eq!(p, Policy::Normal);
+}
+
+// ── Power-aware require_ac_power gate (#1073) ─────────────────────
+
+#[test]
+fn require_ac_power_pauses_on_battery() {
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.require_ac_power = true;
+ // On battery, even with healthy charge + low CPU.
+ let p = decide(&signals(false, Some(0.95), 10.0, false), &c);
+ assert_eq!(
+ p,
+ Policy::Paused {
+ reason: PauseReason::OnBattery
+ }
+ );
+}
+
+#[test]
+fn require_ac_power_normal_when_plugged_in() {
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.require_ac_power = true;
+ // Plugged in with headroom — should still run.
+ let p = decide(&signals(true, Some(0.90), 10.0, false), &c);
+ assert_eq!(p, Policy::Normal);
+}
+
+#[test]
+fn require_ac_power_off_preserves_legacy_behavior_on_battery() {
+ // Default `require_ac_power = false` and a fresh battery means
+ // the legacy path runs: battery >= floor ⇒ Normal.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.require_ac_power = false;
+ let p = decide(&signals(false, Some(0.95), 10.0, false), &c);
+ assert_eq!(p, Policy::Normal);
+}
+
+#[test]
+fn require_ac_power_pause_resumes_when_back_on_ac() {
+ // Pause → re-evaluate after plugging in → Normal.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.require_ac_power = true;
+ let s_battery = signals(false, Some(0.40), 5.0, false);
+ let s_ac = signals(true, Some(0.45), 5.0, false);
+
+ let p1 = decide(&s_battery, &c);
+ assert!(matches!(
+ p1,
+ Policy::Paused {
+ reason: PauseReason::OnBattery
+ }
+ ));
+ let p2 = decide(&s_ac, &c);
+ assert_eq!(p2, Policy::Normal);
+}
+
+// ── Hard CPU ceiling (#1073) ──────────────────────────────────────
+
+#[test]
+fn cpu_severe_pauses_on_pressure() {
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.cpu_severe_pct = 90.0;
+ // CPU above severe ceiling, plugged in.
+ let p = decide(&signals(true, None, 96.0, false), &c);
+ assert_eq!(
+ p,
+ Policy::Paused {
+ reason: PauseReason::CpuPressure
+ }
+ );
+}
+
+#[test]
+fn cpu_just_below_severe_throttles_not_pauses() {
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.cpu_busy_threshold_pct = 70.0;
+ c.cpu_severe_pct = 95.0;
+ // CPU above busy but below severe → Throttled, not Paused.
+ let p = decide(&signals(true, None, 80.0, false), &c);
+ assert_eq!(p, Policy::Throttled);
+}
+
+#[test]
+fn cpu_severe_recovers_to_normal() {
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.cpu_severe_pct = 90.0;
+ let s_pegged = signals(true, None, 99.0, false);
+ let s_idle = signals(true, None, 5.0, false);
+ assert!(matches!(
+ decide(&s_pegged, &c),
+ Policy::Paused {
+ reason: PauseReason::CpuPressure
+ }
+ ));
+ assert_eq!(decide(&s_idle, &c), Policy::Normal);
+}
+
+#[test]
+fn out_of_range_cpu_severe_pct_is_clamped() {
+ // 200.0 clamped to 100.0 — only true 100% CPU triggers pause.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.cpu_severe_pct = 200.0;
+ let p = decide(&signals(true, None, 99.9, false), &c);
+ // 99.9 < 100.0 (clamped), so we don't hit the pause arm and
+ // fall through to Throttled (cpu_busy_threshold=70).
+ assert_eq!(p, Policy::Throttled);
+ // Negative clamps to 0.0 — any positive CPU usage pauses.
+ c.cpu_severe_pct = -10.0;
+ let p = decide(&signals(true, None, 0.5, false), &c);
+ assert_eq!(
+ p,
+ Policy::Paused {
+ reason: PauseReason::CpuPressure
+ }
+ );
+}
+
+#[test]
+fn server_mode_overrides_pause_signals() {
+ // Even on battery + CPU pegged, server mode stays Aggressive.
+ let mut c = cfg(SchedulerGateMode::Auto);
+ c.require_ac_power = true;
+ c.cpu_severe_pct = 50.0;
+ let p = decide(&signals(false, None, 99.0, true), &c);
+ assert_eq!(p, Policy::Aggressive);
+}
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/signals.rs b/crates/openhuman-core/src/cron/scheduler_gate/signals.rs
new file mode 100644
index 0000000000..02772d0a0d
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/signals.rs
@@ -0,0 +1,214 @@
+//! Host signals: power state, CPU pressure, deployment mode.
+//!
+//! Sampled on a 30s cadence by [`super::throttle::spawn_sampler`]; this file just
+//! captures one snapshot at a time.
+
+use std::path::Path;
+use std::time::Duration;
+
+use sysinfo::System;
+
+pub use super::decide::Signals;
+
+/// Names of the environment variables that override what the hardware says.
+///
+/// The names are the host's (they are user-facing configuration), so the host
+/// passes them in rather than this crate owning product-prefixed constants.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SignalEnv {
+ /// `1`/`true`/`yes` or `0`/`false`/`no`: force the AC-power reading.
+ pub on_ac_power: &'static str,
+ /// A float in `0.0..=1.0`: force the battery charge.
+ pub battery_charge: &'static str,
+ /// `server` or `desktop`/`laptop`: force the deployment mode.
+ pub deployment: &'static str,
+}
+
+/// Sample once. Cheap (~ms-scale) — safe to call from a 30s background task.
+pub fn sample(env: &SignalEnv) -> Signals {
+ let (on_ac, charge) = sample_power(env);
+ let cpu_usage_pct = sample_cpu();
+ let server_mode = detect_server_mode(env, charge.is_none());
+ Signals {
+ on_ac_power: on_ac,
+ battery_charge: charge,
+ cpu_usage_pct,
+ server_mode,
+ }
+}
+
+// ---- power ---------------------------------------------------------------
+
+fn sample_power(env: &SignalEnv) -> (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(env.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(env.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 `battery` 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 `battery` is compiled in.
+#[cfg(feature = "battery")]
+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!("[tinymemory_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 = "battery"))]
+fn battery_probe() -> Option<BatteryProbe> {
+ None
+}
+
+#[cfg(feature = "battery")]
+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 })
+}
+
+#[cfg(any(feature = "battery", test))]
+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(env: &SignalEnv, no_battery: bool) -> bool {
+ if let Ok(v) = std::env::var(env.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.rs
new file mode 100644
index 0000000000..cb2223cc9e
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/signals_tests.rs
@@ -0,0 +1,80 @@
+use super::*;
+
+/// Variables no host sets, so the real probe answers.
+const TEST_ENV: SignalEnv = SignalEnv {
+ on_ac_power: "OPENHUMAN_GATE_TEST_ON_AC_POWER",
+ battery_charge: "OPENHUMAN_GATE_TEST_BATTERY_CHARGE",
+ deployment: "OPENHUMAN_GATE_TEST_DEPLOYMENT",
+};
+
+/// `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(&TEST_ENV);
+ 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))
+ );
+}
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/throttle.rs b/crates/openhuman-core/src/cron/scheduler_gate/throttle.rs
new file mode 100644
index 0000000000..f7fe2db22c
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/throttle.rs
@@ -0,0 +1,258 @@
+//! The cached policy, the background sampler, and cooperative throttling.
+//!
+//! One sampler task refreshes [`Signals`] every [`SAMPLE_INTERVAL`] and
+//! recomputes the [`Policy`]. Workers call [`wait_for_capacity`] to
+//! cooperatively block until the host is ready.
+//!
+//! Nothing here is process-global: the host owns the [`SharedCore`], the
+//! semaphore and the signed-out flag, and hands them in. That is what lets it
+//! give every unit test its own.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use parking_lot::RwLock;
+use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+
+use super::decide::{decide, Signals};
+use super::signals::{self, SignalEnv};
+use crate::config::schema::{Policy, SchedulerGateConfig};
+
+/// 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 — backfills with multiple
+/// simultaneous Ollama requests have crashed a laptop twice.
+///
+/// Cloud-backend LLM calls bypass this semaphore at the worker layer 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.
+pub const LLM_SLOTS: usize = 1;
+
+/// How often the background sampler refreshes the signals.
+pub const SAMPLE_INTERVAL: Duration = Duration::from_secs(30);
+
+/// A fresh [`LLM_SLOTS`]-slot semaphore for [`wait_for_capacity`].
+pub fn new_llm_slots() -> Arc<Semaphore> {
+ Arc::new(Semaphore::new(LLM_SLOTS))
+}
+
+/// RAII guard returned by [`wait_for_capacity`] / [`acquire_llm_permit`].
+///
+/// While the caller holds an `LlmPermit`, no other LLM-bound caller sharing the
+/// semaphore can acquire one. 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");
+ }
+}
+
+/// The sampled signals, the user's config and the policy decided from them.
+#[derive(Debug)]
+pub struct GateCore {
+ cfg: SchedulerGateConfig,
+ signals: Signals,
+ policy: Policy,
+}
+
+/// A [`GateCore`] shared between the sampler task and its readers.
+pub type SharedCore = Arc<RwLock<GateCore>>;
+
+impl GateCore {
+ /// Decide the initial policy from `signals` under `cfg` and log it.
+ pub fn new(cfg: SchedulerGateConfig, signals: Signals) -> Self {
+ 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,
+ );
+ Self {
+ cfg,
+ signals,
+ policy,
+ }
+ }
+
+ /// The cached policy.
+ pub fn policy(&self) -> Policy {
+ self.policy
+ }
+
+ /// The most recent sampled signals.
+ pub fn signals(&self) -> Signals {
+ self.signals
+ }
+
+ /// The config the policy is decided under.
+ pub fn config(&self) -> &SchedulerGateConfig {
+ &self.cfg
+ }
+
+ /// Replace the config and recompute the policy.
+ ///
+ /// Returns `true` when this update moved the policy **out of** a paused
+ /// state, so the caller can wake parked background loops.
+ pub fn update_config(&mut self, cfg: SchedulerGateConfig) -> bool {
+ let was_paused = matches!(self.policy, Policy::Paused { .. });
+ self.cfg = cfg;
+ self.policy = decide(&self.signals, &self.cfg);
+ was_paused && !matches!(self.policy, Policy::Paused { .. })
+ }
+
+ /// Take a fresh sample, recompute the policy, and log a transition.
+ pub fn refresh(&mut self, signals: Signals) {
+ let next = decide(&signals, &self.cfg);
+ if next != self.policy {
+ log::info!(
+ "[scheduler_gate] policy {} -> {} (on_ac={} charge={:?} cpu={:.1}% server={})",
+ self.policy.as_str(),
+ next.as_str(),
+ signals.on_ac_power,
+ signals.battery_charge,
+ signals.cpu_usage_pct,
+ signals.server_mode,
+ );
+ }
+ self.signals = signals;
+ self.policy = next;
+ }
+}
+
+/// Spawn the background sampler on the current tokio runtime: every
+/// [`SAMPLE_INTERVAL`] it samples the host and [`GateCore::refresh`]es `core`.
+pub fn spawn_sampler(core: SharedCore, env: SignalEnv) {
+ 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(move || signals::sample(&env)).await {
+ Ok(s) => s,
+ Err(err) => {
+ log::warn!("[scheduler_gate] sampler join error: {err:#}");
+ continue;
+ }
+ };
+ core.write().refresh(signals);
+ }
+ });
+}
+
+/// Cooperatively block a caller until the host is ready for LLM-bound work,
+/// then hand back an [`LlmPermit`] that holds a slot in `slots`.
+///
+/// `core` is `None` when the host has not initialised a gate (unit tests, early
+/// bootstrap): there is no policy to consult, so the permit is acquired
+/// directly. `signed_out` is the host's override; it is only honoured once a
+/// core exists, because the override only has meaning when there are real
+/// background workers calling into the gate.
+///
+/// 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 slot; return 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.
+///
+/// Returns `None` only if the semaphore has been closed. Callers can safely
+/// treat `None` as "skip the gate" rather than propagating an error.
+pub async fn wait_for_capacity(
+ core: Option<&SharedCore>,
+ signed_out: impl Fn() -> bool,
+ slots: &Arc<Semaphore>,
+) -> 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.
+ if let Some(core) = core {
+ if signed_out() {
+ let paused_ms = core.read().cfg.paused_poll_ms;
+ 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 core {
+ Some(core) => {
+ let g = core.read();
+ (g.policy, g.cfg.throttled_backoff_ms, g.cfg.paused_poll_ms)
+ }
+ // Gate not initialised: acquire directly — no policy to consult.
+ None => return acquire_llm_permit(slots).await,
+ };
+ match policy {
+ Policy::Aggressive | Policy::Normal => return acquire_llm_permit(slots).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(slots).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.
+ }
+ }
+ }
+}
+
+/// Acquire a slot in `slots` without consulting any policy. Production callers
+/// should use [`wait_for_capacity`] so the policy backoff applies.
+pub async fn acquire_llm_permit(slots: &Arc<Semaphore>) -> Option<LlmPermit> {
+ match slots.clone().acquire_owned().await {
+ Ok(permit) => {
+ log::trace!("[scheduler_gate] llm permit acquired");
+ Some(LlmPermit { _permit: permit })
+ }
+ Err(_) => {
+ // Semaphore closed — should never happen since nothing closes 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
+ }
+ }
+}
+
+/// Try to grab a slot without waiting or consulting the policy. `None` if no
+/// slot is free.
+pub fn try_acquire_llm_permit(slots: &Arc<Semaphore>) -> Option<LlmPermit> {
+ slots
+ .clone()
+ .try_acquire_owned()
+ .ok()
+ .map(|p| LlmPermit { _permit: p })
+}
+
+#[cfg(test)]
+#[path = "throttle_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/cron/scheduler_gate/throttle_tests.rs b/crates/openhuman-core/src/cron/scheduler_gate/throttle_tests.rs
new file mode 100644
index 0000000000..5a851221e4
--- /dev/null
+++ b/crates/openhuman-core/src/cron/scheduler_gate/throttle_tests.rs
@@ -0,0 +1,168 @@
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use crate::config::schema::SchedulerGateMode;
+
+fn calm() -> Signals {
+ Signals {
+ on_ac_power: true,
+ battery_charge: None,
+ cpu_usage_pct: 5.0,
+ server_mode: false,
+ }
+}
+
+fn busy() -> Signals {
+ Signals {
+ cpu_usage_pct: 75.0,
+ ..calm()
+ }
+}
+
+fn cfg(mode: SchedulerGateMode) -> SchedulerGateConfig {
+ SchedulerGateConfig {
+ mode,
+ throttled_backoff_ms: 1_000,
+ paused_poll_ms: 500,
+ ..Default::default()
+ }
+}
+
+fn core(mode: SchedulerGateMode, signals: Signals) -> SharedCore {
+ Arc::new(RwLock::new(GateCore::new(cfg(mode), signals)))
+}
+
+fn never() -> bool {
+ false
+}
+
+#[tokio::test]
+async fn uninitialised_gate_hands_back_a_permit_and_releases_it_on_drop() {
+ let slots = new_llm_slots();
+ let permit = wait_for_capacity(None, never, &slots).await;
+ assert!(permit.is_some());
+ assert_eq!(
+ slots.available_permits(),
+ 0,
+ "permit occupies the only slot"
+ );
+ drop(permit);
+ assert_eq!(slots.available_permits(), LLM_SLOTS);
+}
+
+#[tokio::test]
+async fn signed_out_is_ignored_until_a_gate_exists() {
+ let slots = new_llm_slots();
+ let permit = tokio::time::timeout(
+ Duration::from_millis(500),
+ wait_for_capacity(None, || true, &slots),
+ )
+ .await
+ .expect("an uninitialised gate must not block on the signed-out flag");
+ assert!(permit.is_some());
+}
+
+#[tokio::test]
+async fn the_semaphore_holds_exactly_one_slot() {
+ let slots = new_llm_slots();
+ let first = wait_for_capacity(None, never, &slots).await.unwrap();
+ assert!(try_acquire_llm_permit(&slots).is_none());
+ drop(first);
+ assert!(try_acquire_llm_permit(&slots).is_some());
+}
+
+#[tokio::test(start_paused = true)]
+async fn a_second_waiter_blocks_until_the_first_drops() {
+ let slots = new_llm_slots();
+ let first = wait_for_capacity(None, never, &slots).await.unwrap();
+ let waiter = {
+ let slots = slots.clone();
+ tokio::spawn(async move { wait_for_capacity(None, never, &slots).await })
+ };
+ tokio::time::sleep(Duration::from_millis(40)).await;
+ assert!(!waiter.is_finished());
+ drop(first);
+ assert!(waiter.await.unwrap().is_some());
+}
+
+#[tokio::test(start_paused = true)]
+async fn normal_policy_does_not_sleep() {
+ let core = core(SchedulerGateMode::Auto, calm());
+ assert_eq!(core.read().policy(), Policy::Normal);
+ let slots = new_llm_slots();
+ let started = tokio::time::Instant::now();
+ let permit = wait_for_capacity(Some(&core), never, &slots).await;
+ assert!(permit.is_some());
+ assert_eq!(started.elapsed(), Duration::ZERO);
+}
+
+#[tokio::test(start_paused = true)]
+async fn throttled_policy_sleeps_the_backoff_before_acquiring() {
+ let core = core(SchedulerGateMode::Auto, busy());
+ assert_eq!(core.read().policy(), Policy::Throttled);
+ let slots = new_llm_slots();
+ let started = tokio::time::Instant::now();
+ let permit = wait_for_capacity(Some(&core), never, &slots).await;
+ assert!(permit.is_some());
+ assert_eq!(started.elapsed(), Duration::from_millis(1_000));
+}
+
+#[tokio::test(start_paused = true)]
+async fn paused_policy_polls_until_the_user_turns_the_gate_back_on() {
+ let core = core(SchedulerGateMode::Off, calm());
+ assert!(matches!(core.read().policy(), Policy::Paused { .. }));
+ let slots = new_llm_slots();
+ let waiter = {
+ let core = core.clone();
+ let slots = slots.clone();
+ tokio::spawn(async move { wait_for_capacity(Some(&core), never, &slots).await })
+ };
+ tokio::time::sleep(Duration::from_millis(1_200)).await;
+ assert!(!waiter.is_finished(), "still paused, so still waiting");
+ assert!(core.write().update_config(cfg(SchedulerGateMode::AlwaysOn)));
+ assert!(waiter.await.unwrap().is_some());
+}
+
+#[tokio::test(start_paused = true)]
+async fn the_signed_out_override_holds_callers_until_it_clears() {
+ let core = core(SchedulerGateMode::Auto, calm());
+ let slots = new_llm_slots();
+ let signed_out = Arc::new(AtomicBool::new(true));
+ let waiter = {
+ let core = core.clone();
+ let slots = slots.clone();
+ let flag = signed_out.clone();
+ tokio::spawn(async move {
+ wait_for_capacity(Some(&core), move || flag.load(Ordering::Acquire), &slots).await
+ })
+ };
+ tokio::time::sleep(Duration::from_millis(1_200)).await;
+ assert!(!waiter.is_finished());
+ signed_out.store(false, Ordering::Release);
+ assert!(waiter.await.unwrap().is_some());
+}
+
+#[test]
+fn update_config_reports_only_a_transition_out_of_paused() {
+ let mut core = GateCore::new(cfg(SchedulerGateMode::Off), calm());
+ assert!(
+ !core.update_config(cfg(SchedulerGateMode::Off)),
+ "paused to paused is not a resume"
+ );
+ assert!(core.update_config(cfg(SchedulerGateMode::AlwaysOn)));
+ assert!(
+ !core.update_config(cfg(SchedulerGateMode::AlwaysOn)),
+ "running to running is not a resume"
+ );
+ assert_eq!(core.config().mode, SchedulerGateMode::AlwaysOn);
+}
+
+#[test]
+fn refresh_recomputes_the_policy_from_new_signals() {
+ let mut core = GateCore::new(cfg(SchedulerGateMode::Auto), calm());
+ assert_eq!(core.policy(), Policy::Normal);
+ core.refresh(busy());
+ assert_eq!(core.policy(), Policy::Throttled);
+ assert_eq!(core.signals().cpu_usage_pct, 75.0);
+ core.refresh(calm());
+ assert_eq!(core.policy(), Policy::Normal);
+}