Skip to main content

rinne_loop/
pool.rs

1//! Pool profiling: tier whatever workers are actually present (`CONTEXT.md` §7).
2//!
3//! Tiers are computed, not hardcoded. The conductor takes the worker registry
4//! as input and tiers it at runtime: cheap / workhorse / frontier are ranks
5//! within the present pool, not fixed names. With only Claude Code the ladder is
6//! Haiku → Sonnet → Opus; add a DeepSeek key and the cheap rung gets cheaper and
7//! an open option appears; add Gemini and cross-family review returns.
8
9use std::collections::BTreeSet;
10
11use crate::priors::{self, family_of, family_of_worker, tier_ladder};
12use crate::worker::{AuthMode, WorkerDescriptor};
13
14/// The shape of the available worker pool, which selects the routing strategy.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum PoolShape {
17    /// One vendor family, subscription-backed (e.g. only Claude Code). Quota is
18    /// the binding constraint; cascade within the family.
19    SingleFamily,
20    /// One vendor family on a metered API key. Cost-aware cascade.
21    SingleApi,
22    /// Several families. Full cross-family routing, cross-family evaluators.
23    MultiVendor,
24    /// Subscription(s) plus API key(s). Prefer subscriptions for the bulk; spend
25    /// API only where a capability or independence is worth it.
26    Mixed,
27}
28
29impl PoolShape {
30    pub fn label(self) -> &'static str {
31        match self {
32            PoolShape::SingleFamily => "single-family (quota-aware)",
33            PoolShape::SingleApi => "single-api (cost-aware)",
34            PoolShape::MultiVendor => "multi-vendor (cross-family)",
35            PoolShape::Mixed => "mixed subscription + api",
36        }
37    }
38}
39
40/// A worker tiered into its cascade ladder.
41#[derive(Debug, Clone)]
42pub struct WorkerTiers {
43    pub worker: String,
44    pub family: String,
45    pub auth: AuthMode,
46    /// Models cheapest → strongest. Empty means a single fixed model.
47    pub ladder: Vec<String>,
48}
49
50/// The profiled pool.
51#[derive(Debug, Clone)]
52pub struct PoolProfile {
53    pub shape: PoolShape,
54    pub workers: Vec<WorkerTiers>,
55    /// Distinct vendor families present (excluding `unknown`).
56    pub families: Vec<String>,
57    /// A single-family pool loses evaluator independence; recommend a cheap
58    /// second-family key for the evaluator role.
59    pub recommend_eval_key: bool,
60}
61
62impl PoolProfile {
63    pub fn is_single_family(&self) -> bool {
64        matches!(self.shape, PoolShape::SingleFamily | PoolShape::SingleApi)
65    }
66
67    /// Map of worker name → cascade ladder, for the engine's escalation.
68    /// Includes single-model ladders (API pins like Cloudflare) so overview
69    /// and routing never collapse them to an opaque "default model" label.
70    pub fn ladders(&self) -> std::collections::HashMap<String, Vec<String>> {
71        self.workers
72            .iter()
73            .filter(|w| !w.ladder.is_empty())
74            .map(|w| (w.worker.clone(), w.ladder.clone()))
75            .collect()
76    }
77}
78
79/// Profile a set of worker descriptors into a pool profile.
80pub fn profile(descriptors: &[WorkerDescriptor]) -> PoolProfile {
81    let mut workers = Vec::new();
82    let mut families: BTreeSet<String> = BTreeSet::new();
83    let mut has_sub = false;
84    let mut has_api = false;
85
86    for d in descriptors {
87        // Family: prefer the model's family; fall back to the worker name.
88        let family = d
89            .models
90            .first()
91            .map(|m| family_of(m))
92            .filter(|f| *f != "unknown")
93            .unwrap_or_else(|| family_of_worker(&d.name))
94            .to_string();
95
96        if family != "unknown" {
97            families.insert(family.clone());
98        }
99        match d.auth_mode {
100            AuthMode::Subscription => has_sub = true,
101            AuthMode::ApiKey => has_api = true,
102            _ => {}
103        }
104
105        workers.push(WorkerTiers {
106            worker: d.name.clone(),
107            family,
108            auth: d.auth_mode,
109            ladder: tier_ladder(&d.models),
110        });
111    }
112
113    let distinct = families.len();
114    let shape = if distinct <= 1 {
115        if has_sub {
116            PoolShape::SingleFamily
117        } else {
118            PoolShape::SingleApi
119        }
120    } else if has_sub && has_api {
121        PoolShape::Mixed
122    } else {
123        PoolShape::MultiVendor
124    };
125
126    PoolProfile {
127        shape,
128        workers,
129        families: families.into_iter().collect(),
130        recommend_eval_key: distinct <= 1,
131    }
132}
133
134/// Whether the pool can field a cross-family evaluator: at least two families.
135pub fn has_cross_family(profile: &PoolProfile) -> bool {
136    profile.families.len() >= 2
137}
138
139/// A friendly one-line recommendation for a thin pool, or `None` if the pool is
140/// already cross-family. The single cheapest quality upgrade a single-family
141/// user can make (`CONTEXT.md` §7).
142pub fn eval_key_recommendation(profile: &PoolProfile) -> Option<String> {
143    if !profile.recommend_eval_key {
144        return None;
145    }
146    let fam = profile.families.first().map(String::as_str).unwrap_or("one family");
147    let _ = priors::CostClass::Cheap; // priors seed this recommendation
148    Some(format!(
149        "Single-family pool ({fam}). For blind-spot independence on the highest-leverage role, \
150         add a cheap second-family API key (e.g. DeepSeek or Gemini Flash) used only as the \
151         evaluator — pennies, and Rinne charges nothing either way."
152    ))
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158    use crate::worker::{Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily};
159
160    fn desc(name: &str, auth: AuthMode, models: &[&str]) -> WorkerDescriptor {
161        WorkerDescriptor {
162            name: name.into(),
163            family: WorkerFamily::Harness,
164            capabilities: vec![Capability::CodeEdit, Capability::Reasoning],
165            auth_mode: auth,
166            quota: QuotaModel::unlimited(),
167            latency: LatencyProfile::Medium,
168            transport: Transport::SubprocessJson,
169            models: models.iter().map(|s| s.to_string()).collect(),
170        }
171    }
172
173    #[test]
174    fn only_claude_is_single_family_with_a_ladder() {
175        // Models are declared cheap→strong; the ladder preserves that order.
176        let p = profile(&[desc("claude-code", AuthMode::Subscription, &["haiku", "sonnet", "opus"])]);
177        assert_eq!(p.shape, PoolShape::SingleFamily);
178        assert!(p.recommend_eval_key);
179        assert!(!has_cross_family(&p));
180        assert_eq!(p.workers[0].ladder, vec!["haiku", "sonnet", "opus"]);
181    }
182
183    #[test]
184    fn claude_plus_grok_is_multi_vendor() {
185        let p = profile(&[
186            desc("claude-code", AuthMode::Subscription, &["sonnet", "opus"]),
187            desc("grok", AuthMode::Subscription, &["grok-composer-2.5-fast", "grok-build"]),
188        ]);
189        assert_eq!(p.shape, PoolShape::MultiVendor);
190        assert!(!p.recommend_eval_key);
191        assert!(has_cross_family(&p));
192    }
193
194    #[test]
195    fn subscription_plus_api_is_mixed() {
196        let p = profile(&[
197            desc("claude-code", AuthMode::Subscription, &["sonnet"]),
198            desc("deepseek", AuthMode::ApiKey, &["deepseek-chat"]),
199        ]);
200        assert_eq!(p.shape, PoolShape::Mixed);
201    }
202
203    #[test]
204    fn single_api_pool() {
205        let p = profile(&[desc("openai", AuthMode::ApiKey, &["gpt-mini", "gpt-pro"])]);
206        assert_eq!(p.shape, PoolShape::SingleApi);
207        assert!(eval_key_recommendation(&p).is_some());
208    }
209}