Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["agentflare-workspace-hack","crates/flare-code", "crates/agent-registry", "crates/skill-registry", "crates/gateway-registry", "crates/flare-output", "crates/agentflare-artifacts", "crates/agentflare-backend", "crates/agentflare-db-kit", "crates/flare-search-kit", "crates/agentflare-store", "crates/flare-proxy", "crates/agentflare-shim", "crates/flare-git-core", "crates/flare-git-shim", "crates/agentflare-jobs", "crates/flare-docs", "crates/flare-vault"]
members = ["agentflare-workspace-hack","crates/flare-code", "crates/agent-registry", "crates/skill-registry", "crates/gateway-registry", "crates/flare-output", "crates/agentflare-artifacts", "crates/agentflare-backend", "crates/agentflare-db-kit", "crates/flare-search-kit", "crates/agentflare-store", "crates/flare-proxy", "crates/agentflare-shim", "crates/flare-git-core", "crates/flare-git-shim", "crates/agentflare-jobs", "crates/flare-docs", "crates/flare-vault", "crates/agentflare-resource-gate"]
resolver = "2"

[package]
Expand Down Expand Up @@ -90,6 +90,7 @@ flare-proxy = { path = "crates/flare-proxy" }
flare-vault = { path = "crates/flare-vault" }
skill = { version = "0.8", default-features = false, features = ["network"] }
agentflare-jobs = { path = "crates/agentflare-jobs" }
agentflare-resource-gate = { path = "crates/agentflare-resource-gate" }
machine-uid = "0.6.0"
agentflare-workspace-hack = { version = "0.1", path = "agentflare-workspace-hack" }
dunce = "1"
Expand Down
19 changes: 19 additions & 0 deletions crates/agentflare-resource-gate/Cargo.toml
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"
78 changes: 78 additions & 0 deletions crates/agentflare-resource-gate/src/config.rs
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),
}
Comment thread
getappz marked this conversation as resolved.
Resolved
}
}

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
);
}
}
56 changes: 56 additions & 0 deletions crates/agentflare-resource-gate/src/gate.rs
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)
}
23 changes: 23 additions & 0 deletions crates/agentflare-resource-gate/src/lib.rs
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;
Loading
Loading