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    pub fn ladders(&self) -> std::collections::HashMap<String, Vec<String>> {
69        self.workers
70            .iter()
71            .filter(|w| w.ladder.len() > 1)
72            .map(|w| (w.worker.clone(), w.ladder.clone()))
73            .collect()
74    }
75}
76
77/// Profile a set of worker descriptors into a pool profile.
78pub fn profile(descriptors: &[WorkerDescriptor]) -> PoolProfile {
79    let mut workers = Vec::new();
80    let mut families: BTreeSet<String> = BTreeSet::new();
81    let mut has_sub = false;
82    let mut has_api = false;
83
84    for d in descriptors {
85        // Family: prefer the model's family; fall back to the worker name.
86        let family = d
87            .models
88            .first()
89            .map(|m| family_of(m))
90            .filter(|f| *f != "unknown")
91            .unwrap_or_else(|| family_of_worker(&d.name))
92            .to_string();
93
94        if family != "unknown" {
95            families.insert(family.clone());
96        }
97        match d.auth_mode {
98            AuthMode::Subscription => has_sub = true,
99            AuthMode::ApiKey => has_api = true,
100            _ => {}
101        }
102
103        workers.push(WorkerTiers {
104            worker: d.name.clone(),
105            family,
106            auth: d.auth_mode,
107            ladder: tier_ladder(&d.models),
108        });
109    }
110
111    let distinct = families.len();
112    let shape = if distinct <= 1 {
113        if has_sub {
114            PoolShape::SingleFamily
115        } else {
116            PoolShape::SingleApi
117        }
118    } else if has_sub && has_api {
119        PoolShape::Mixed
120    } else {
121        PoolShape::MultiVendor
122    };
123
124    PoolProfile {
125        shape,
126        workers,
127        families: families.into_iter().collect(),
128        recommend_eval_key: distinct <= 1,
129    }
130}
131
132/// Whether the pool can field a cross-family evaluator: at least two families.
133pub fn has_cross_family(profile: &PoolProfile) -> bool {
134    profile.families.len() >= 2
135}
136
137/// A friendly one-line recommendation for a thin pool, or `None` if the pool is
138/// already cross-family. The single cheapest quality upgrade a single-family
139/// user can make (`CONTEXT.md` §7).
140pub fn eval_key_recommendation(profile: &PoolProfile) -> Option<String> {
141    if !profile.recommend_eval_key {
142        return None;
143    }
144    let fam = profile.families.first().map(String::as_str).unwrap_or("one family");
145    let _ = priors::CostClass::Cheap; // priors seed this recommendation
146    Some(format!(
147        "Single-family pool ({fam}). For blind-spot independence on the highest-leverage role, \
148         add a cheap second-family API key (e.g. DeepSeek or Gemini Flash) used only as the \
149         evaluator — pennies, and Rinne charges nothing either way."
150    ))
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use crate::worker::{Capability, LatencyProfile, QuotaModel, Transport, WorkerFamily};
157
158    fn desc(name: &str, auth: AuthMode, models: &[&str]) -> WorkerDescriptor {
159        WorkerDescriptor {
160            name: name.into(),
161            family: WorkerFamily::Harness,
162            capabilities: vec![Capability::CodeEdit, Capability::Reasoning],
163            auth_mode: auth,
164            quota: QuotaModel::unlimited(),
165            latency: LatencyProfile::Medium,
166            transport: Transport::SubprocessJson,
167            models: models.iter().map(|s| s.to_string()).collect(),
168        }
169    }
170
171    #[test]
172    fn only_claude_is_single_family_with_a_ladder() {
173        // Models are declared cheap→strong; the ladder preserves that order.
174        let p = profile(&[desc("claude-code", AuthMode::Subscription, &["haiku", "sonnet", "opus"])]);
175        assert_eq!(p.shape, PoolShape::SingleFamily);
176        assert!(p.recommend_eval_key);
177        assert!(!has_cross_family(&p));
178        assert_eq!(p.workers[0].ladder, vec!["haiku", "sonnet", "opus"]);
179    }
180
181    #[test]
182    fn claude_plus_grok_is_multi_vendor() {
183        let p = profile(&[
184            desc("claude-code", AuthMode::Subscription, &["sonnet", "opus"]),
185            desc("grok", AuthMode::Subscription, &["grok-composer-2.5-fast", "grok-build"]),
186        ]);
187        assert_eq!(p.shape, PoolShape::MultiVendor);
188        assert!(!p.recommend_eval_key);
189        assert!(has_cross_family(&p));
190    }
191
192    #[test]
193    fn subscription_plus_api_is_mixed() {
194        let p = profile(&[
195            desc("claude-code", AuthMode::Subscription, &["sonnet"]),
196            desc("deepseek", AuthMode::ApiKey, &["deepseek-chat"]),
197        ]);
198        assert_eq!(p.shape, PoolShape::Mixed);
199    }
200
201    #[test]
202    fn single_api_pool() {
203        let p = profile(&[desc("openai", AuthMode::ApiKey, &["gpt-mini", "gpt-pro"])]);
204        assert_eq!(p.shape, PoolShape::SingleApi);
205        assert!(eval_key_recommendation(&p).is_some());
206    }
207}