From 7a1d3752dd176fc91792026ef64671f676c4c32b Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 3 Oct 2026 10:23:33 -0500 Subject: [PATCH 1/2] Add aien-switchboard crate: types, rule table, deterministic router, fake runner Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Drake Stapleton --- Cargo.toml | 1 + crates/aien-switchboard/Cargo.toml | 18 ++ crates/aien-switchboard/src/account.rs | 83 +++++++ crates/aien-switchboard/src/dispatch.rs | 76 +++++++ crates/aien-switchboard/src/gauge.rs | 80 +++++++ crates/aien-switchboard/src/job.rs | 54 +++++ crates/aien-switchboard/src/lib.rs | 30 +++ crates/aien-switchboard/src/router.rs | 103 +++++++++ crates/aien-switchboard/src/rules.rs | 287 ++++++++++++++++++++++++ crates/aien-switchboard/src/runner.rs | 49 ++++ crates/aien-switchboard/tests/router.rs | 240 ++++++++++++++++++++ 11 files changed, 1021 insertions(+) create mode 100644 crates/aien-switchboard/Cargo.toml create mode 100644 crates/aien-switchboard/src/account.rs create mode 100644 crates/aien-switchboard/src/dispatch.rs create mode 100644 crates/aien-switchboard/src/gauge.rs create mode 100644 crates/aien-switchboard/src/job.rs create mode 100644 crates/aien-switchboard/src/lib.rs create mode 100644 crates/aien-switchboard/src/router.rs create mode 100644 crates/aien-switchboard/src/rules.rs create mode 100644 crates/aien-switchboard/src/runner.rs create mode 100644 crates/aien-switchboard/tests/router.rs diff --git a/Cargo.toml b/Cargo.toml index 9040371d..c33d0dcf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,7 @@ members = [ "crates/aien-proof", "crates/crumbs", "crates/aien-closure", + "crates/aien-switchboard", "tools/aien-test", ] diff --git a/crates/aien-switchboard/Cargo.toml b/crates/aien-switchboard/Cargo.toml new file mode 100644 index 00000000..6f373521 --- /dev/null +++ b/crates/aien-switchboard/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "aien-switchboard" +description = "Switchboard core: accounts, jobs, usage gauges, operator rule table and one deterministic routing decision over our own AI accounts" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +repository.workspace = true + +# Pure by rule (ADR 0030): no network, no process spawning, no secrets in this +# crate. Real program adapters arrive in a later cut behind the Runner trait. +[dependencies] +serde = { version = "1", features = ["derive"] } +toml = "0.8" + +[lib] +name = "aien_switchboard" +path = "src/lib.rs" diff --git a/crates/aien-switchboard/src/account.rs b/crates/aien-switchboard/src/account.rs new file mode 100644 index 00000000..2612830b --- /dev/null +++ b/crates/aien-switchboard/src/account.rs @@ -0,0 +1,83 @@ +//! Accounts. An account names where its program keeps its own login, never +//! the login itself. + +use serde::Deserialize; +use std::fmt; +use std::path::PathBuf; + +/// Short operator-chosen name such as `anthropic-1`. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(transparent)] +pub struct AccountId(pub String); + +impl AccountId { + pub fn new(s: impl Into) -> Self { + AccountId(s.into()) + } + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl fmt::Display for AccountId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Provider { + Anthropic, + #[serde(rename = "openai")] + OpenAI, + Google, + Xai, + #[serde(rename = "openrouter")] + OpenRouter, + Local, +} + +impl Provider { + pub fn as_str(self) -> &'static str { + match self { + Provider::Anthropic => "anthropic", + Provider::OpenAI => "openai", + Provider::Google => "google", + Provider::Xai => "xai", + Provider::OpenRouter => "openrouter", + Provider::Local => "local", + } + } +} + +/// How an account proves who it is. Both variants hold a pointer, never a +/// secret value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Credential { + /// The company's own program keeps its login in this settings folder + /// (one folder per account). The router never opens it. + SettingsFolder(PathBuf), + /// Name of a key held in the vault (for example an OpenRouter key). The + /// value is resolved elsewhere, in process memory only. + KeyRef(String), + /// Nothing needed (the local model). + None, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Account { + pub id: AccountId, + pub provider: Provider, + /// Name of the program that serves this account, such as `claude`. + /// UNKNOWN for `agy` and `grok`: how a second login is kept side by side + /// is not confirmed (see ADR 0030, open UNKNOWNs). + pub program: String, + pub credential: Credential, +} + +impl Account { + pub fn is_local(&self) -> bool { + self.provider == Provider::Local + } +} diff --git a/crates/aien-switchboard/src/dispatch.rs b/crates/aien-switchboard/src/dispatch.rs new file mode 100644 index 00000000..783f46f3 --- /dev/null +++ b/crates/aien-switchboard/src/dispatch.rs @@ -0,0 +1,76 @@ +//! Route, run, and fail over on a limit hit. + +use crate::account::AccountId; +use crate::gauge::Gauges; +use crate::job::Job; +use crate::router::route; +use crate::rules::RuleTable; +use crate::runner::{RunResult, Runner}; +use std::fmt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Completed { + pub account: AccountId, + pub output: String, + /// Every account tried, in order, ending with `account`. + pub tried: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DispatchError { + /// Even the local account reported a limit hit. + Exhausted { tried: Vec }, +} + +impl fmt::Display for DispatchError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + DispatchError::Exhausted { tried } => { + let t: Vec<&str> = tried.iter().map(|i| i.as_str()).collect(); + write!(f, "every account is out of room (tried: {})", t.join(", ")) + } + } + } +} + +impl std::error::Error for DispatchError {} + +/// Run `job` on the best account; on a limit hit, cool that account down and +/// route again. Each account is tried at most once, so this always ends. +pub fn run_job( + job: &Job, + prompt: &str, + rules: &RuleTable, + gauges: &mut Gauges, + runner: &mut dyn Runner, + now: u64, +) -> Result { + let mut tried: Vec = Vec::new(); + loop { + let d = route(job, rules, gauges, now); + if tried.contains(&d.account) { + return Err(DispatchError::Exhausted { tried }); + } + tried.push(d.account.clone()); + // `route` only returns ids from the rule table. + let account = match rules.account(&d.account) { + Some(a) => a, + None => return Err(DispatchError::Exhausted { tried }), + }; + match runner.run(account, job, prompt) { + RunResult::Output(output) => { + return Ok(Completed { + account: d.account, + output, + tried, + }) + } + RunResult::LimitHit { resets_at } => { + gauges.on_limit_hit(&d.account, resets_at, now, rules.default_backoff_secs()); + if d.account == *rules.local() { + return Err(DispatchError::Exhausted { tried }); + } + } + } + } +} diff --git a/crates/aien-switchboard/src/gauge.rs b/crates/aien-switchboard/src/gauge.rs new file mode 100644 index 00000000..5a8191e6 --- /dev/null +++ b/crates/aien-switchboard/src/gauge.rs @@ -0,0 +1,80 @@ +//! Usage gauges: how much room an account has, as far as we know. + +use crate::account::AccountId; +use std::collections::BTreeMap; + +/// One usage window, for example a five-hour or seven-day window. +#[derive(Debug, Clone, PartialEq)] +pub struct Window { + pub name: String, + /// 0.0 to 100.0. + pub used_percent: f64, + /// Unix seconds when the window refills, when known. + pub resets_at: Option, +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Gauge { + pub windows: Vec, + /// The account is treated as full until this Unix second. + pub cooled_until: Option, +} + +impl Gauge { + pub fn is_cooled(&self, now: u64) -> bool { + matches!(self.cooled_until, Some(t) if t > now) + } + + /// The first window at or over `ceiling_percent` that has not refilled + /// yet, if any. A window whose reset time has passed is stale and counts + /// as empty. + pub fn full_window(&self, ceiling_percent: f64, now: u64) -> Option<&Window> { + self.windows.iter().find(|w| { + let refilled = matches!(w.resets_at, Some(t) if t <= now); + !refilled && w.used_percent >= ceiling_percent + }) + } +} + +/// All known gauges. An account with no entry has an empty gauge, which means +/// "no information, assume room" (programs that report nothing rely on the +/// limit-hit signal instead). +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Gauges { + map: BTreeMap, +} + +impl Gauges { + pub fn new() -> Self { + Gauges::default() + } + + pub fn get(&self, id: &AccountId) -> Option<&Gauge> { + self.map.get(id) + } + + pub fn set_windows(&mut self, id: &AccountId, windows: Vec) { + self.map.entry(id.clone()).or_default().windows = windows; + } + + /// Record that `id` hit its limit. The cooldown lasts until `resets_at` + /// when that is in the future, otherwise `default_backoff_secs` from + /// `now`. An existing longer cooldown is kept. Returns the new + /// cooled-until second. + pub fn on_limit_hit( + &mut self, + id: &AccountId, + resets_at: Option, + now: u64, + default_backoff_secs: u64, + ) -> u64 { + let until = match resets_at { + Some(t) if t > now => t, + _ => now.saturating_add(default_backoff_secs), + }; + let g = self.map.entry(id.clone()).or_default(); + let until = g.cooled_until.map_or(until, |old| old.max(until)); + g.cooled_until = Some(until); + until + } +} diff --git a/crates/aien-switchboard/src/job.rs b/crates/aien-switchboard/src/job.rs new file mode 100644 index 00000000..7bef39a0 --- /dev/null +++ b/crates/aien-switchboard/src/job.rs @@ -0,0 +1,54 @@ +//! Jobs: what the operator wants done. + +use serde::Deserialize; +use std::fmt; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum JobKind { + Code, + Review, + Research, +} + +impl JobKind { + pub const ALL: [JobKind; 3] = [JobKind::Code, JobKind::Review, JobKind::Research]; + + pub fn as_str(self) -> &'static str { + match self { + JobKind::Code => "code", + JobKind::Review => "review", + JobKind::Research => "research", + } + } +} + +impl fmt::Display for JobKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +/// Rough size of the job. v1 routing does not use it yet; it is carried so +/// the type is stable when size-aware rules arrive. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum JobSize { + Small, + Medium, + Large, +} + +/// `needs` (what a job requires of an account) is deliberately absent: no +/// first-party source on this machine says what each program can or cannot +/// do, so adding it now would be a guess. UNKNOWN, tracked for a later cut. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Job { + pub kind: JobKind, + pub size: JobSize, +} + +impl Job { + pub fn new(kind: JobKind, size: JobSize) -> Self { + Job { kind, size } + } +} diff --git a/crates/aien-switchboard/src/lib.rs b/crates/aien-switchboard/src/lib.rs new file mode 100644 index 00000000..a575599c --- /dev/null +++ b/crates/aien-switchboard/src/lib.rs @@ -0,0 +1,30 @@ +//! Switchboard core (ADR 0030): one typed, deterministic router over our own +//! AI accounts. +//! +//! What lives here: the account list, the job description, a usage gauge per +//! account, the rule table the operator edits as a plain TOML file, the pure +//! routing decision, and the `Runner` trait with a scripted `FakeRunner`. +//! +//! What does not live here: login tokens (the crate never reads, copies or +//! stores any; an account only names a settings folder or a key reference +//! name), network calls, or process spawning. Real program adapters are a +//! later cut. +//! +//! All times are Unix seconds passed in by the caller, so every decision is a +//! pure function of its inputs. + +pub mod account; +pub mod dispatch; +pub mod gauge; +pub mod job; +pub mod router; +pub mod rules; +pub mod runner; + +pub use account::{Account, AccountId, Provider}; +pub use dispatch::{run_job, Completed, DispatchError}; +pub use gauge::{Gauge, Gauges, Window}; +pub use job::{Job, JobKind, JobSize}; +pub use router::{route, Decision}; +pub use rules::{RuleTable, RulesError}; +pub use runner::{FakeRunner, RunResult, Runner}; diff --git a/crates/aien-switchboard/src/router.rs b/crates/aien-switchboard/src/router.rs new file mode 100644 index 00000000..27b2bfa6 --- /dev/null +++ b/crates/aien-switchboard/src/router.rs @@ -0,0 +1,103 @@ +//! The routing decision: pure, deterministic, no clock reads, no I/O. + +use crate::account::AccountId; +use crate::gauge::Gauges; +use crate::job::Job; +use crate::rules::RuleTable; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Decision { + pub account: AccountId, + /// Plain-words explanation, safe to show the operator. + pub reason: String, + /// Later accounts in the same route that also have room, in order. The + /// local account is always the last entry unless it was chosen. + pub alternates: Vec, +} + +/// Why an account has no room right now, or `None` if it has room. +fn no_room( + id: &AccountId, + rules: &RuleTable, + gauges: &Gauges, + now: u64, +) -> Option { + let g = gauges.get(id)?; + if let Some(t) = g.cooled_until.filter(|t| *t > now) { + return Some(format!( + "{id} is cooling down after hitting its limit (back in {} s)", + t - now + )); + } + g.full_window(rules.ceiling_percent(), now).map(|w| { + format!( + "{id} is {:.0}% used in its {} window (ceiling {:.0}%)", + w.used_percent, + w.name, + rules.ceiling_percent() + ) + }) +} + +/// Pick the first account in the job's route that has room. The local +/// account is the last entry of every route and is never skipped, so a +/// decision always exists and AIEN works offline. +pub fn route(job: &Job, rules: &RuleTable, gauges: &Gauges, now: u64) -> Decision { + let order = rules.route_for(job.kind); + let mut skipped: Vec = Vec::new(); + let mut chosen: Option<(usize, bool)> = None; // (index, had room) + + for (i, id) in order.iter().enumerate() { + if id == rules.local() { + chosen = Some((i, false)); + break; + } + match no_room(id, rules, gauges, now) { + Some(why) => skipped.push(why), + None => { + chosen = Some((i, true)); + break; + } + } + } + // The route always ends with local, so `chosen` is always set. + let (idx, _) = chosen.unwrap_or((order.len() - 1, false)); + let account = order[idx].clone(); + + let mut reason = String::new(); + if account == *rules.local() { + if skipped.is_empty() { + reason.push_str(&format!( + "{account} is the first choice for {} jobs.", + job.kind + )); + } else { + reason.push_str(&format!( + "No outside account has room for this {} job, so it stays on the local model {account}. ", + job.kind + )); + reason.push_str(&format!("Skipped: {}.", skipped.join("; "))); + } + } else { + reason.push_str(&format!( + "{account} is the first account in the {} route with room.", + job.kind + )); + if !skipped.is_empty() { + reason.push_str(&format!(" Skipped: {}.", skipped.join("; "))); + } + } + + let mut alternates = Vec::new(); + for id in &order[idx + 1..] { + if id == rules.local() || no_room(id, rules, gauges, now).is_none() { + alternates.push(id.clone()); + } + } + + Decision { + account, + reason, + alternates, + } +} diff --git a/crates/aien-switchboard/src/rules.rs b/crates/aien-switchboard/src/rules.rs new file mode 100644 index 00000000..83708b24 --- /dev/null +++ b/crates/aien-switchboard/src/rules.rs @@ -0,0 +1,287 @@ +//! The rule table: one plain TOML file the operator edits. +//! +//! ```toml +//! [settings] +//! ceiling_percent = 90 # an account at or over this is treated as full +//! default_backoff_secs = 1800 # cooldown when a limit hit gives no reset time +//! +//! [[accounts]] +//! id = "anthropic-1" +//! provider = "anthropic" # anthropic openai google xai openrouter local +//! program = "claude" +//! settings_dir = "/home/me/.switchboard/anthropic-1" +//! +//! [[accounts]] +//! id = "openrouter-1" +//! provider = "openrouter" +//! program = "http" +//! key_ref = "openrouter-key" # a NAME in the vault, never the key itself +//! +//! [[accounts]] +//! id = "local" +//! provider = "local" +//! program = "aien" +//! +//! [routes] +//! code = ["anthropic-1", "openrouter-1"] +//! default = ["anthropic-1"] +//! ``` +//! +//! `local` is always the last fallback of every route so AIEN works offline. +//! If the file lists it earlier it is moved to the end; if the file omits it +//! it is added. + +use crate::account::{Account, AccountId, Credential, Provider}; +use crate::job::JobKind; +use serde::Deserialize; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt; +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RulesError { + Read(String), + /// Syntax or shape error, with the parser's own line and column text. + Parse(String), + /// The file parsed but breaks a rule; the text says which and how to fix. + Invalid(String), +} + +impl fmt::Display for RulesError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RulesError::Read(m) => write!(f, "cannot read rule file: {m}"), + RulesError::Parse(m) => write!(f, "rule file is not valid: {m}"), + RulesError::Invalid(m) => write!(f, "rule file has a mistake: {m}"), + } + } +} + +impl std::error::Error for RulesError {} + +fn bad(m: impl Into) -> Result { + Err(RulesError::Invalid(m.into())) +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawFile { + #[serde(default)] + settings: RawSettings, + #[serde(default)] + accounts: Vec, + routes: RawRoutes, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawSettings { + #[serde(default = "default_ceiling")] + ceiling_percent: f64, + #[serde(default = "default_backoff")] + default_backoff_secs: u64, +} + +fn default_ceiling() -> f64 { + 90.0 +} +fn default_backoff() -> u64 { + 1800 +} + +impl Default for RawSettings { + fn default() -> Self { + RawSettings { + ceiling_percent: default_ceiling(), + default_backoff_secs: default_backoff(), + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawAccount { + id: String, + provider: Provider, + program: String, + settings_dir: Option, + key_ref: Option, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawRoutes { + code: Option>, + review: Option>, + research: Option>, + default: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct RuleTable { + accounts: Vec, + ceiling_percent: f64, + default_backoff_secs: u64, + routes: BTreeMap>, + default_route: Vec, + local: AccountId, +} + +fn valid_name(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.') +} + +impl RuleTable { + pub fn from_path(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| RulesError::Read(format!("{}: {e}", path.display())))?; + Self::from_toml_str(&text) + } + + pub fn from_toml_str(text: &str) -> Result { + let raw: RawFile = + toml::from_str(text).map_err(|e| RulesError::Parse(e.to_string()))?; + + let c = raw.settings.ceiling_percent; + if !(c > 0.0 && c <= 100.0) { + return bad(format!( + "ceiling_percent must be above 0 and at most 100, got {c}" + )); + } + + let mut accounts = Vec::new(); + let mut seen = BTreeSet::new(); + let mut local: Option = None; + for a in raw.accounts { + if !valid_name(&a.id) { + return bad(format!( + "account id {:?} must be 1 to 64 letters, digits, '-', '_' or '.'", + a.id + )); + } + if !seen.insert(a.id.clone()) { + return bad(format!("account id {:?} is listed twice", a.id)); + } + if a.program.trim().is_empty() { + return bad(format!("account {:?} has an empty program name", a.id)); + } + let credential = match (a.settings_dir, a.key_ref) { + (Some(_), Some(_)) => { + return bad(format!( + "account {:?} sets both settings_dir and key_ref; pick one", + a.id + )) + } + (Some(p), None) => Credential::SettingsFolder(p), + (None, Some(k)) => { + if !valid_name(&k) { + return bad(format!( + "account {:?}: key_ref must be a key NAME (letters, digits, '-', '_', '.'), never the key itself", + a.id + )); + } + Credential::KeyRef(k) + } + (None, None) => Credential::None, + }; + if a.provider == Provider::Local { + if credential != Credential::None { + return bad(format!( + "account {:?} is local and must not set settings_dir or key_ref", + a.id + )); + } + if local.is_some() { + return bad("more than one local account; exactly one is allowed"); + } + local = Some(AccountId::new(a.id.clone())); + } + accounts.push(Account { + id: AccountId::new(a.id), + provider: a.provider, + program: a.program, + credential, + }); + } + let local = match local { + Some(l) => l, + None => { + return bad( + "no account with provider = \"local\"; AIEN must always have the local model as the last fallback", + ) + } + }; + + let resolve = |label: &str, ids: Vec| -> Result, RulesError> { + if ids.is_empty() { + return bad(format!("route {label:?} is an empty list")); + } + let mut out: Vec = Vec::new(); + for id in ids { + if !seen.contains(&id) { + return bad(format!( + "route {label:?} names account {id:?}, which is not in [[accounts]]" + )); + } + let id = AccountId::new(id); + if out.contains(&id) { + return bad(format!("route {label:?} lists {id} twice")); + } + out.push(id); + } + // Local is always last, exactly once. + out.retain(|i| *i != local); + out.push(local.clone()); + Ok(out) + }; + + let default_route = resolve("default", raw.routes.default)?; + let mut routes = BTreeMap::new(); + for (kind, list) in [ + (JobKind::Code, raw.routes.code), + (JobKind::Review, raw.routes.review), + (JobKind::Research, raw.routes.research), + ] { + if let Some(ids) = list { + routes.insert(kind, resolve(kind.as_str(), ids)?); + } + } + + Ok(RuleTable { + accounts, + ceiling_percent: c, + default_backoff_secs: raw.settings.default_backoff_secs, + routes, + default_route, + local, + }) + } + + pub fn ceiling_percent(&self) -> f64 { + self.ceiling_percent + } + + pub fn default_backoff_secs(&self) -> u64 { + self.default_backoff_secs + } + + pub fn local(&self) -> &AccountId { + &self.local + } + + pub fn accounts(&self) -> &[Account] { + &self.accounts + } + + pub fn account(&self, id: &AccountId) -> Option<&Account> { + self.accounts.iter().find(|a| a.id == *id) + } + + /// Ordered account ids for this kind of job; the last one is always local. + pub fn route_for(&self, kind: JobKind) -> &[AccountId] { + self.routes.get(&kind).unwrap_or(&self.default_route) + } +} diff --git a/crates/aien-switchboard/src/runner.rs b/crates/aien-switchboard/src/runner.rs new file mode 100644 index 00000000..5658c7e0 --- /dev/null +++ b/crates/aien-switchboard/src/runner.rs @@ -0,0 +1,49 @@ +//! Runners start one job on one account. This cut ships only the scripted +//! fake; adapters for the real programs come later and must keep this shape. + +use crate::account::{Account, AccountId}; +use crate::job::Job; +use std::collections::{BTreeMap, VecDeque}; + +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum RunResult { + Output(String), + /// The account hit its usage limit. `resets_at` is Unix seconds when the + /// program said when it refills, else `None`. + LimitHit { resets_at: Option }, +} + +pub trait Runner { + fn run(&mut self, account: &Account, job: &Job, prompt: &str) -> RunResult; +} + +/// Scripted runner for tests: answers per account from a queue, then falls +/// back to a canned output. Records every call. +#[derive(Debug, Default)] +pub struct FakeRunner { + scripts: BTreeMap>, + pub calls: Vec, +} + +impl FakeRunner { + pub fn new() -> Self { + FakeRunner::default() + } + + /// Queue the next answer for `id`. + pub fn push(&mut self, id: &AccountId, result: RunResult) -> &mut Self { + self.scripts.entry(id.clone()).or_default().push_back(result); + self + } +} + +impl Runner for FakeRunner { + fn run(&mut self, account: &Account, _job: &Job, prompt: &str) -> RunResult { + self.calls.push(account.id.clone()); + match self.scripts.get_mut(&account.id).and_then(|q| q.pop_front()) { + Some(r) => r, + None => RunResult::Output(format!("fake output from {}: {prompt}", account.id)), + } + } +} diff --git a/crates/aien-switchboard/tests/router.rs b/crates/aien-switchboard/tests/router.rs new file mode 100644 index 00000000..bada244f --- /dev/null +++ b/crates/aien-switchboard/tests/router.rs @@ -0,0 +1,240 @@ +use aien_switchboard::*; + +const RULES: &str = r#" +[settings] +ceiling_percent = 90 +default_backoff_secs = 600 + +[[accounts]] +id = "anthropic-1" +provider = "anthropic" +program = "claude" +settings_dir = "/tmp/sb/anthropic-1" + +[[accounts]] +id = "anthropic-2" +provider = "anthropic" +program = "claude" +settings_dir = "/tmp/sb/anthropic-2" + +[[accounts]] +id = "openrouter-1" +provider = "openrouter" +program = "http" +key_ref = "openrouter-key" + +[[accounts]] +id = "local" +provider = "local" +program = "aien" + +[routes] +code = ["anthropic-1", "anthropic-2", "openrouter-1", "local"] +review = ["anthropic-2", "anthropic-1"] +default = ["openrouter-1"] +"#; + +fn rules() -> RuleTable { + RuleTable::from_toml_str(RULES).unwrap() +} +fn id(s: &str) -> AccountId { + AccountId::new(s) +} +fn code() -> Job { + Job::new(JobKind::Code, JobSize::Small) +} +fn win(pct: f64, resets_at: Option) -> Vec { + vec![Window { + name: "five_hour".into(), + used_percent: pct, + resets_at, + }] +} + +#[test] +fn rule_order_is_respected() { + let r = rules(); + let d = route(&code(), &r, &Gauges::new(), 1000); + assert_eq!(d.account, id("anthropic-1")); + assert_eq!( + d.alternates, + vec![id("anthropic-2"), id("openrouter-1"), id("local")] + ); + let d = route(&Job::new(JobKind::Review, JobSize::Small), &r, &Gauges::new(), 1000); + assert_eq!(d.account, id("anthropic-2")); +} + +#[test] +fn unlisted_kind_uses_default_and_local_is_appended() { + let r = rules(); + assert_eq!( + r.route_for(JobKind::Research), + &[id("openrouter-1"), id("local")] + ); + assert_eq!( + r.route_for(JobKind::Review), + &[id("anthropic-2"), id("anthropic-1"), id("local")] + ); +} + +#[test] +fn cooled_down_account_is_skipped_with_a_plain_reason() { + let r = rules(); + let mut g = Gauges::new(); + g.on_limit_hit(&id("anthropic-1"), Some(5000), 1000, 600); + let d = route(&code(), &r, &g, 1000); + assert_eq!(d.account, id("anthropic-2")); + assert!(d.reason.contains("anthropic-1 is cooling down"), "{}", d.reason); +} + +#[test] +fn account_over_the_ceiling_is_skipped_and_stale_window_is_not() { + let r = rules(); + let mut g = Gauges::new(); + g.set_windows(&id("anthropic-1"), win(95.0, Some(5000))); + let d = route(&code(), &r, &g, 1000); + assert_eq!(d.account, id("anthropic-2")); + assert!(d.reason.contains("95% used"), "{}", d.reason); + // Once the window's reset time has passed, the account has room again. + let d = route(&code(), &r, &g, 5000); + assert_eq!(d.account, id("anthropic-1")); + // Exactly under the ceiling is fine. + g.set_windows(&id("anthropic-1"), win(89.9, None)); + assert_eq!(route(&code(), &r, &g, 1000).account, id("anthropic-1")); +} + +#[test] +fn everything_exhausted_goes_to_local() { + let r = rules(); + let mut g = Gauges::new(); + for a in ["anthropic-1", "anthropic-2", "openrouter-1"] { + g.on_limit_hit(&id(a), None, 1000, 600); + } + let d = route(&code(), &r, &g, 1000); + assert_eq!(d.account, id("local")); + assert!(d.alternates.is_empty()); + assert!(d.reason.contains("stays on the local model"), "{}", d.reason); +} + +#[test] +fn cooldown_expires() { + let r = rules(); + let mut g = Gauges::new(); + let until = g.on_limit_hit(&id("anthropic-1"), None, 1000, 600); + assert_eq!(until, 1600); + assert_eq!(route(&code(), &r, &g, 1599).account, id("anthropic-2")); + assert_eq!(route(&code(), &r, &g, 1600).account, id("anthropic-1")); +} + +#[test] +fn reset_time_in_the_past_falls_back_to_default_backoff_and_longer_cooldown_is_kept() { + let mut g = Gauges::new(); + assert_eq!(g.on_limit_hit(&id("a"), Some(500), 1000, 600), 1600); + assert_eq!(g.on_limit_hit(&id("a"), Some(9000), 1000, 600), 9000); + assert_eq!(g.on_limit_hit(&id("a"), None, 1000, 600), 9000); +} + +#[test] +fn failover_on_limit_hit_then_cooldown_sticks() { + let r = rules(); + let mut g = Gauges::new(); + let mut run = FakeRunner::new(); + run.push(&id("anthropic-1"), RunResult::LimitHit { resets_at: Some(4000) }); + let done = run_job(&code(), "hi", &r, &mut g, &mut run, 1000).unwrap(); + assert_eq!(done.account, id("anthropic-2")); + assert_eq!(done.tried, vec![id("anthropic-1"), id("anthropic-2")]); + assert!(done.output.contains("anthropic-2")); + // The next job skips the cooled account without trying it. + let done = run_job(&code(), "again", &r, &mut g, &mut run, 1001).unwrap(); + assert_eq!(done.tried, vec![id("anthropic-2")]); +} + +#[test] +fn all_outside_accounts_hit_limits_then_local_answers() { + let r = rules(); + let mut g = Gauges::new(); + let mut run = FakeRunner::new(); + for a in ["anthropic-1", "anthropic-2", "openrouter-1"] { + run.push(&id(a), RunResult::LimitHit { resets_at: None }); + } + let done = run_job(&code(), "x", &r, &mut g, &mut run, 1000).unwrap(); + assert_eq!(done.account, id("local")); + assert_eq!(done.tried.len(), 4); +} + +#[test] +fn local_limit_hit_is_a_clear_error_not_a_loop() { + let r = rules(); + let mut g = Gauges::new(); + let mut run = FakeRunner::new(); + run.push(&id("local"), RunResult::LimitHit { resets_at: None }); + let only_local = RuleTable::from_toml_str( + "[[accounts]]\nid=\"local\"\nprovider=\"local\"\nprogram=\"aien\"\n[routes]\ndefault=[\"local\"]\n", + ) + .unwrap(); + let e = run_job(&code(), "x", &only_local, &mut g, &mut run, 1000).unwrap_err(); + assert!(e.to_string().contains("out of room"), "{e}"); + let _ = r; +} + +#[test] +fn local_listed_early_is_moved_last() { + let r = RuleTable::from_toml_str( + "[[accounts]]\nid=\"local\"\nprovider=\"local\"\nprogram=\"aien\"\n\ + [[accounts]]\nid=\"g1\"\nprovider=\"google\"\nprogram=\"agy\"\n\ + [routes]\ndefault=[\"local\",\"g1\"]\n", + ) + .unwrap(); + assert_eq!(r.route_for(JobKind::Code), &[id("g1"), id("local")]); +} + +fn parse_err(text: &str) -> String { + RuleTable::from_toml_str(text).unwrap_err().to_string() +} + +#[test] +fn parse_errors_are_clear() { + // Not TOML at all: parser reports line and column. + let e = parse_err("[routes\ndefault = ["); + assert!(e.starts_with("rule file is not valid:"), "{e}"); + assert!(e.contains("line 1"), "{e}"); + // Missing the required default route. + assert!(parse_err("[routes]\n").contains("default")); + // Misspelled key. + assert!(parse_err("[routes]\ndefalt = []\n").contains("defalt")); + // Unknown provider. + let e = parse_err("[[accounts]]\nid=\"a\"\nprovider=\"bing\"\nprogram=\"x\"\n[routes]\ndefault=[\"a\"]\n"); + assert!(e.contains("bing"), "{e}"); +} + +#[test] +fn rule_mistakes_name_the_problem() { + let local = "[[accounts]]\nid=\"local\"\nprovider=\"local\"\nprogram=\"aien\"\n"; + let g1 = "[[accounts]]\nid=\"g1\"\nprovider=\"google\"\nprogram=\"agy\"\n"; + assert!(parse_err(&format!("{g1}[routes]\ndefault=[\"g1\"]\n")).contains("no account with provider = \"local\"")); + assert!(parse_err(&format!("{local}[routes]\ndefault=[\"nope\"]\n")).contains("\"nope\", which is not in [[accounts]]")); + assert!(parse_err(&format!("{local}[routes]\ndefault=[]\n")).contains("empty list")); + assert!(parse_err(&format!("{local}{local}[routes]\ndefault=[\"local\"]\n")).contains("listed twice")); + assert!(parse_err(&format!("{local}{g1}[routes]\ndefault=[\"g1\",\"g1\"]\n")).contains("lists g1 twice")); + assert!(parse_err(&format!("[settings]\nceiling_percent=150\n{local}[routes]\ndefault=[\"local\"]\n")).contains("ceiling_percent")); + let both = "[[accounts]]\nid=\"x\"\nprovider=\"xai\"\nprogram=\"grok\"\nsettings_dir=\"/a\"\nkey_ref=\"k\"\n"; + assert!(parse_err(&format!("{local}{both}[routes]\ndefault=[\"x\"]\n")).contains("pick one")); + let secret = "[[accounts]]\nid=\"o\"\nprovider=\"openrouter\"\nprogram=\"http\"\nkey_ref=\"sk-or v1 abc def\"\n"; + assert!(parse_err(&format!("{local}{secret}[routes]\ndefault=[\"o\"]\n")).contains("never the key itself")); +} + +#[test] +fn missing_file_is_a_read_error() { + let e = RuleTable::from_path(std::path::Path::new("/nonexistent/switchboard.toml")).unwrap_err(); + assert!(e.to_string().starts_with("cannot read rule file:"), "{e}"); +} + +#[test] +fn routing_is_deterministic() { + let r = rules(); + let mut g = Gauges::new(); + g.set_windows(&id("anthropic-1"), win(91.0, None)); + let a = route(&code(), &r, &g, 1000); + let b = route(&code(), &r, &g, 1000); + assert_eq!(a, b); +} From 3d751eaca2267bdb0c347fe2617db2494a739d78 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Sat, 3 Oct 2026 11:34:58 -0500 Subject: [PATCH 2/2] fmt: rustfmt aien-switchboard Co-Authored-By: Drake Stapleton Co-Authored-By: Claude Fable 5.1 --- Cargo.lock | 8 ++++ crates/aien-switchboard/src/router.rs | 7 +-- crates/aien-switchboard/src/rules.rs | 3 +- crates/aien-switchboard/src/runner.rs | 15 +++++-- crates/aien-switchboard/tests/router.rs | 59 ++++++++++++++++++++----- 5 files changed, 69 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f611b9de..4ba94454 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -295,6 +295,14 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aien-switchboard" +version = "0.1.0" +dependencies = [ + "serde", + "toml", +] + [[package]] name = "aien-test" version = "0.1.0" diff --git a/crates/aien-switchboard/src/router.rs b/crates/aien-switchboard/src/router.rs index 27b2bfa6..19e5d99a 100644 --- a/crates/aien-switchboard/src/router.rs +++ b/crates/aien-switchboard/src/router.rs @@ -16,12 +16,7 @@ pub struct Decision { } /// Why an account has no room right now, or `None` if it has room. -fn no_room( - id: &AccountId, - rules: &RuleTable, - gauges: &Gauges, - now: u64, -) -> Option { +fn no_room(id: &AccountId, rules: &RuleTable, gauges: &Gauges, now: u64) -> Option { let g = gauges.get(id)?; if let Some(t) = g.cooled_until.filter(|t| *t > now) { return Some(format!( diff --git a/crates/aien-switchboard/src/rules.rs b/crates/aien-switchboard/src/rules.rs index 83708b24..e3f17df8 100644 --- a/crates/aien-switchboard/src/rules.rs +++ b/crates/aien-switchboard/src/rules.rs @@ -142,8 +142,7 @@ impl RuleTable { } pub fn from_toml_str(text: &str) -> Result { - let raw: RawFile = - toml::from_str(text).map_err(|e| RulesError::Parse(e.to_string()))?; + let raw: RawFile = toml::from_str(text).map_err(|e| RulesError::Parse(e.to_string()))?; let c = raw.settings.ceiling_percent; if !(c > 0.0 && c <= 100.0) { diff --git a/crates/aien-switchboard/src/runner.rs b/crates/aien-switchboard/src/runner.rs index 5658c7e0..b2816aee 100644 --- a/crates/aien-switchboard/src/runner.rs +++ b/crates/aien-switchboard/src/runner.rs @@ -11,7 +11,9 @@ pub enum RunResult { Output(String), /// The account hit its usage limit. `resets_at` is Unix seconds when the /// program said when it refills, else `None`. - LimitHit { resets_at: Option }, + LimitHit { + resets_at: Option, + }, } pub trait Runner { @@ -33,7 +35,10 @@ impl FakeRunner { /// Queue the next answer for `id`. pub fn push(&mut self, id: &AccountId, result: RunResult) -> &mut Self { - self.scripts.entry(id.clone()).or_default().push_back(result); + self.scripts + .entry(id.clone()) + .or_default() + .push_back(result); self } } @@ -41,7 +46,11 @@ impl FakeRunner { impl Runner for FakeRunner { fn run(&mut self, account: &Account, _job: &Job, prompt: &str) -> RunResult { self.calls.push(account.id.clone()); - match self.scripts.get_mut(&account.id).and_then(|q| q.pop_front()) { + match self + .scripts + .get_mut(&account.id) + .and_then(|q| q.pop_front()) + { Some(r) => r, None => RunResult::Output(format!("fake output from {}: {prompt}", account.id)), } diff --git a/crates/aien-switchboard/tests/router.rs b/crates/aien-switchboard/tests/router.rs index bada244f..14759211 100644 --- a/crates/aien-switchboard/tests/router.rs +++ b/crates/aien-switchboard/tests/router.rs @@ -60,7 +60,12 @@ fn rule_order_is_respected() { d.alternates, vec![id("anthropic-2"), id("openrouter-1"), id("local")] ); - let d = route(&Job::new(JobKind::Review, JobSize::Small), &r, &Gauges::new(), 1000); + let d = route( + &Job::new(JobKind::Review, JobSize::Small), + &r, + &Gauges::new(), + 1000, + ); assert_eq!(d.account, id("anthropic-2")); } @@ -84,7 +89,11 @@ fn cooled_down_account_is_skipped_with_a_plain_reason() { g.on_limit_hit(&id("anthropic-1"), Some(5000), 1000, 600); let d = route(&code(), &r, &g, 1000); assert_eq!(d.account, id("anthropic-2")); - assert!(d.reason.contains("anthropic-1 is cooling down"), "{}", d.reason); + assert!( + d.reason.contains("anthropic-1 is cooling down"), + "{}", + d.reason + ); } #[test] @@ -113,7 +122,11 @@ fn everything_exhausted_goes_to_local() { let d = route(&code(), &r, &g, 1000); assert_eq!(d.account, id("local")); assert!(d.alternates.is_empty()); - assert!(d.reason.contains("stays on the local model"), "{}", d.reason); + assert!( + d.reason.contains("stays on the local model"), + "{}", + d.reason + ); } #[test] @@ -139,7 +152,12 @@ fn failover_on_limit_hit_then_cooldown_sticks() { let r = rules(); let mut g = Gauges::new(); let mut run = FakeRunner::new(); - run.push(&id("anthropic-1"), RunResult::LimitHit { resets_at: Some(4000) }); + run.push( + &id("anthropic-1"), + RunResult::LimitHit { + resets_at: Some(4000), + }, + ); let done = run_job(&code(), "hi", &r, &mut g, &mut run, 1000).unwrap(); assert_eq!(done.account, id("anthropic-2")); assert_eq!(done.tried, vec![id("anthropic-1"), id("anthropic-2")]); @@ -203,7 +221,9 @@ fn parse_errors_are_clear() { // Misspelled key. assert!(parse_err("[routes]\ndefalt = []\n").contains("defalt")); // Unknown provider. - let e = parse_err("[[accounts]]\nid=\"a\"\nprovider=\"bing\"\nprogram=\"x\"\n[routes]\ndefault=[\"a\"]\n"); + let e = parse_err( + "[[accounts]]\nid=\"a\"\nprovider=\"bing\"\nprogram=\"x\"\n[routes]\ndefault=[\"a\"]\n", + ); assert!(e.contains("bing"), "{e}"); } @@ -211,21 +231,36 @@ fn parse_errors_are_clear() { fn rule_mistakes_name_the_problem() { let local = "[[accounts]]\nid=\"local\"\nprovider=\"local\"\nprogram=\"aien\"\n"; let g1 = "[[accounts]]\nid=\"g1\"\nprovider=\"google\"\nprogram=\"agy\"\n"; - assert!(parse_err(&format!("{g1}[routes]\ndefault=[\"g1\"]\n")).contains("no account with provider = \"local\"")); - assert!(parse_err(&format!("{local}[routes]\ndefault=[\"nope\"]\n")).contains("\"nope\", which is not in [[accounts]]")); + assert!(parse_err(&format!("{g1}[routes]\ndefault=[\"g1\"]\n")) + .contains("no account with provider = \"local\"")); + assert!(parse_err(&format!("{local}[routes]\ndefault=[\"nope\"]\n")) + .contains("\"nope\", which is not in [[accounts]]")); assert!(parse_err(&format!("{local}[routes]\ndefault=[]\n")).contains("empty list")); - assert!(parse_err(&format!("{local}{local}[routes]\ndefault=[\"local\"]\n")).contains("listed twice")); - assert!(parse_err(&format!("{local}{g1}[routes]\ndefault=[\"g1\",\"g1\"]\n")).contains("lists g1 twice")); - assert!(parse_err(&format!("[settings]\nceiling_percent=150\n{local}[routes]\ndefault=[\"local\"]\n")).contains("ceiling_percent")); + assert!( + parse_err(&format!("{local}{local}[routes]\ndefault=[\"local\"]\n")) + .contains("listed twice") + ); + assert!( + parse_err(&format!("{local}{g1}[routes]\ndefault=[\"g1\",\"g1\"]\n")) + .contains("lists g1 twice") + ); + assert!(parse_err(&format!( + "[settings]\nceiling_percent=150\n{local}[routes]\ndefault=[\"local\"]\n" + )) + .contains("ceiling_percent")); let both = "[[accounts]]\nid=\"x\"\nprovider=\"xai\"\nprogram=\"grok\"\nsettings_dir=\"/a\"\nkey_ref=\"k\"\n"; assert!(parse_err(&format!("{local}{both}[routes]\ndefault=[\"x\"]\n")).contains("pick one")); let secret = "[[accounts]]\nid=\"o\"\nprovider=\"openrouter\"\nprogram=\"http\"\nkey_ref=\"sk-or v1 abc def\"\n"; - assert!(parse_err(&format!("{local}{secret}[routes]\ndefault=[\"o\"]\n")).contains("never the key itself")); + assert!( + parse_err(&format!("{local}{secret}[routes]\ndefault=[\"o\"]\n")) + .contains("never the key itself") + ); } #[test] fn missing_file_is_a_read_error() { - let e = RuleTable::from_path(std::path::Path::new("/nonexistent/switchboard.toml")).unwrap_err(); + let e = + RuleTable::from_path(std::path::Path::new("/nonexistent/switchboard.toml")).unwrap_err(); assert!(e.to_string().starts_with("cannot read rule file:"), "{e}"); }