Repository navigation
feat(supervisor): host resource gate throttles autonomous dispatch on CPU pressure #459
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b8b0a28
wip: agentflare-resource-gate crate + supervisor/dashboard integratio…
getappz 4dfa840
wip: merge rescued agentflare-resource-gate WIP into task/435, split …
getappz b5fc226
## Host resource gate for autonomous dispatch (item #435)
getappz fce79fd
fix(supervisor): resolve host-gate test module on Linux, guard invert…
getappz 8ff6ff3
refactor(resource-gate): normalize thresholds at the env boundary too…
getappz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| [package] | ||
| name = "agentflare-resource-gate" | ||
| version = "0.1.0" | ||
| edition = "2024" | ||
| rust-version = "1.91" | ||
| description = "Host resource awareness for autonomous dispatch — CPU/memory pool sizing plus a live CPU-pressure gate (Aggressive/Normal/Throttled/Paused)." | ||
| license = "Apache-2.0" | ||
| publish = false | ||
|
|
||
| [dependencies] | ||
| sysinfo = { version = "0.34", default-features = false, features = ["system"] } | ||
| agentflare-workspace-hack = { version = "0.1", path = "../../agentflare-workspace-hack" } | ||
|
|
||
| [lints.rust] | ||
| unsafe_code = "warn" | ||
|
|
||
| [lints.clippy] | ||
| all = "warn" | ||
| pedantic = "warn" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| //! Gate configuration — env-var overrides today, a `[dispatch_gate]` block | ||
| //! in `~/.agentflare/config.toml` once epic #331's loader exists (don't | ||
| //! block this on that epic landing first). | ||
|
|
||
| #[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| pub enum GateMode { | ||
| /// Sample signals and decide a tier dynamically (the default). | ||
| Auto, | ||
| /// Bypass every throttle — always `Policy::Aggressive`. | ||
| AlwaysOn, | ||
| /// Never let host-gated work through — always `Policy::Paused(UserDisabled)`. | ||
| Off, | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Copy)] | ||
| pub struct GateConfig { | ||
| pub mode: GateMode, | ||
| /// CPU usage at/above this throttles (0..100). | ||
| pub cpu_busy_threshold_pct: f32, | ||
| /// CPU usage at/above this pauses outright — the host is unusable, a | ||
| /// throttled backoff isn't enough (0..100). | ||
| pub cpu_severe_pct: f32, | ||
| } | ||
|
|
||
| impl GateConfig { | ||
| pub fn from_env() -> Self { | ||
| Self { | ||
| mode: parse_mode( | ||
| std::env::var("AGENTFLARE_DISPATCH_GATE_MODE") | ||
| .ok() | ||
| .as_deref(), | ||
| ), | ||
| cpu_busy_threshold_pct: parse_f32_env("AGENTFLARE_DISPATCH_GATE_CPU_BUSY_PCT", 80.0), | ||
| cpu_severe_pct: parse_f32_env("AGENTFLARE_DISPATCH_GATE_CPU_SEVERE_PCT", 95.0), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn parse_mode(raw: Option<&str>) -> GateMode { | ||
| match raw.map(str::to_ascii_lowercase).as_deref() { | ||
| Some("always_on") | Some("always-on") | Some("on") => GateMode::AlwaysOn, | ||
| Some("off") => GateMode::Off, | ||
| _ => GateMode::Auto, | ||
| } | ||
| } | ||
|
|
||
| fn parse_f32_env(name: &str, default: f32) -> f32 { | ||
| std::env::var(name) | ||
| .ok() | ||
| .and_then(|v| v.parse::<f32>().ok()) | ||
| .unwrap_or(default) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn parse_mode_defaults_to_auto_on_garbage_or_absent() { | ||
| assert_eq!(parse_mode(None), GateMode::Auto); | ||
| assert_eq!(parse_mode(Some("garbage")), GateMode::Auto); | ||
| } | ||
|
|
||
| #[test] | ||
| fn parse_mode_recognizes_both_spellings_of_always_on() { | ||
| assert_eq!(parse_mode(Some("always_on")), GateMode::AlwaysOn); | ||
| assert_eq!(parse_mode(Some("ALWAYS-ON")), GateMode::AlwaysOn); | ||
| assert_eq!(parse_mode(Some("off")), GateMode::Off); | ||
| } | ||
|
|
||
| #[test] | ||
| fn parse_f32_env_falls_back_on_missing_or_unparseable() { | ||
| assert_eq!( | ||
| parse_f32_env("AGENTFLARE_TEST_DOES_NOT_EXIST_XYZ", 42.0), | ||
| 42.0 | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| //! Process-wide cached policy — a background thread samples signals on a | ||
| //! fixed cadence and stores the decision; callers get a cheap read instead | ||
| //! of paying the CPU-sample cost (which sleeps ~ms) on every dispatch | ||
| //! decision. | ||
|
|
||
| use std::sync::{OnceLock, RwLock}; | ||
| use std::time::Duration; | ||
|
|
||
| use crate::config::GateConfig; | ||
| use crate::policy::{self, Policy}; | ||
| use crate::signals::Signals; | ||
|
|
||
| const SAMPLE_INTERVAL: Duration = Duration::from_secs(30); | ||
|
|
||
| static STATE: OnceLock<RwLock<Policy>> = OnceLock::new(); | ||
|
|
||
| /// Starts the background sampler thread. Idempotent — safe to call more | ||
| /// than once (e.g. from multiple test setups in the same process); only | ||
| /// the first call spawns a thread. Does a synchronous first sample before | ||
| /// returning, so `current_policy()` is meaningful immediately rather than | ||
| /// defaulting to a guess for the first `SAMPLE_INTERVAL`. | ||
| pub fn init_global() { | ||
| if STATE.get().is_some() { | ||
| return; | ||
| } | ||
| let cfg = GateConfig::from_env(); | ||
| let initial = policy::decide(&Signals::sample(), &cfg); | ||
| if STATE.set(RwLock::new(initial)).is_err() { | ||
| // Lost an initialization race with another thread — that thread's | ||
| // sampler is already running, nothing more to do. | ||
| return; | ||
| } | ||
| std::thread::Builder::new() | ||
| .name("agentflare-resource-gate-sampler".into()) | ||
| .spawn(move || { | ||
| loop { | ||
| std::thread::sleep(SAMPLE_INTERVAL); | ||
| let decision = policy::decide(&Signals::sample(), &cfg); | ||
| if let Some(lock) = STATE.get() { | ||
| *lock.write().unwrap_or_else(|e| e.into_inner()) = decision; | ||
| } | ||
| } | ||
| }) | ||
| .expect("failed to spawn agentflare-resource-gate sampler thread"); | ||
| } | ||
|
|
||
| /// Cheap read of the last-sampled policy. Returns `Policy::Normal` if | ||
| /// `init_global()` was never called — callers that skip initialization get | ||
| /// the least-surprising default (dispatch proceeds) rather than a silent | ||
| /// permanent throttle. | ||
| pub fn current_policy() -> Policy { | ||
| STATE | ||
| .get() | ||
| .map(|lock| *lock.read().unwrap_or_else(|e| e.into_inner())) | ||
| .unwrap_or(Policy::Normal) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| //! Host resource awareness for autonomous dispatch. | ||
| //! | ||
| //! Two related but independent concerns live here, both answering "how much | ||
| //! can this host handle right now": | ||
| //! * [`pool_size`] — one-shot CPU+memory sizing for a worker pool at | ||
| //! startup (`work_max_concurrency`). | ||
| //! * [`gate`] — a live, continuously-sampled CPU-pressure tier | ||
| //! ([`Policy`]) that dispatch loops consult on every tick. | ||
| //! | ||
| //! This is deliberately separate from `auth_db`'s per-agent rate-limit | ||
| //! cooldown, which is a different domain (agent identity, not host | ||
| //! pressure) — a caller gates dispatch on both independently. | ||
|
|
||
| pub mod config; | ||
| pub mod gate; | ||
| pub mod policy; | ||
| pub mod pool_size; | ||
| pub mod signals; | ||
|
|
||
| pub use config::{GateConfig, GateMode}; | ||
| pub use gate::{current_policy, init_global}; | ||
| pub use policy::{PauseReason, Policy}; | ||
| pub use signals::Signals; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.