| 1 | use std::collections::{BTreeMap, BTreeSet}; |
| 2 | use std::io::{self, Read as _}; |
| 3 | use std::path::{Path, PathBuf}; |
| 4 | |
| 5 | use anyhow::{Context, Result, bail, ensure}; |
| 6 | use codewhale_config::catalog::CatalogStatus; |
| 7 | use codewhale_runtime::config::{Config, ProviderIdentity}; |
| 8 | use codewhale_util::files::WorkspaceFile; |
| 9 | use serde::{Deserialize, Serialize}; |
| 10 | |
| 11 | use crate::model_inventory::{ExactRouteInventory, ExactRouteModel, InventoryEvidence}; |
| 12 | use crate::provider_readiness::{ProviderReadinessSnapshot, ResolvedProviderReadiness}; |
| 13 | |
| 14 | const MAX_MODELS: usize = 512; |
| 15 | const MAX_POOL_BYTES: u64 = 512 * 1024; |
| 16 | |
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 18 | #[serde(rename_all = "snake_case")] |
| 19 | pub enum WorkerPoolMode { |
| 20 | All, |
| 21 | Selected, |
| 22 | None, |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 26 | pub struct WorkerPoolView { |
| 27 | pub mode: WorkerPoolMode, |
| 28 | pub models: BTreeSet<String>, |
| 29 | pub revision: u64, |
| 30 | pub needs_reselection: bool, |
| 31 | } |
| 32 | |
| 33 | #[derive(Debug, Deserialize)] |
| 34 | #[serde(deny_unknown_fields)] |
| 35 | pub struct SetWorkerPool { |
| 36 | pub mode: WorkerPoolMode, |
| 37 | #[serde(default)] |
| 38 | pub models: BTreeSet<String>, |
| 39 | pub expected_revision: u64, |
| 40 | pub binding_id: String, |
| 41 | } |
| 42 | |
| 43 | #[derive(Debug, PartialEq, Eq, thiserror::Error)] |
| 44 | pub enum WorkerPoolConflict { |
| 45 | #[error("Worker model pool changed; reload before applying")] |
| 46 | Revision, |
| 47 | #[error("Provider binding changed; refresh before applying")] |
| 48 | Binding, |
| 49 | #[error("Provider inventory changed; refresh before applying")] |
| 50 | Inventory, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Serialize, Deserialize)] |
| 54 | struct StoredPool { |
| 55 | mode: WorkerPoolMode, |
| 56 | models: BTreeSet<String>, |
| 57 | revision: u64, |
| 58 | connection: String, |
| 59 | #[serde(default)] |
| 60 | verified_chat_models: BTreeSet<String>, |
| 61 | } |
| 62 | |
| 63 | struct PoolFiles { |
| 64 | home: PathBuf, |
| 65 | slot: PathBuf, |
| 66 | scope: String, |
| 67 | } |
| 68 | |
| 69 | impl PoolFiles { |
| 70 | fn for_connection(config: &Config, identity: &ProviderIdentity) -> Result<Self> { |
| 71 | config |
| 72 | .verify_provider_identity(identity) |
| 73 | .map_err(anyhow::Error::msg)?; |
| 74 | let home = codewhale_paths::codewhale_home()?.context("Codewhale home is unavailable")?; |
| 75 | let scope = serde_json::to_string(&( |
| 76 | config.account_profile.as_deref(), |
| 77 | identity.persisted_kind(), |
| 78 | identity.persisted_id(), |
| 79 | identity.key.as_str(), |
| 80 | ))?; |
| 81 | let slot = Path::new("worker-model-pool").join(format!( |
| 82 | "{}.json", |
| 83 | codewhale_runtime::hashing::sha256_hex(scope.as_bytes()) |
| 84 | )); |
| 85 | Ok(Self { home, slot, scope }) |
| 86 | } |
| 87 | |
| 88 | fn read(&self) -> Result<Option<StoredPool>> { |
| 89 | let file = WorkspaceFile::open_resolved_root(&self.home, &self.slot, false) |
| 90 | .and_then(|file| file.open_file_shared()); |
| 91 | let file = match file { |
| 92 | Ok(file) => file, |
| 93 | Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), |
| 94 | Err(error) => return Err(error.into()), |
| 95 | }; |
| 96 | let mut data = Vec::new(); |
| 97 | file.take(MAX_POOL_BYTES + 1).read_to_end(&mut data)?; |
| 98 | ensure!( |
| 99 | data.len() as u64 <= MAX_POOL_BYTES, |
| 100 | "Worker model pool is too large" |
| 101 | ); |
| 102 | Ok(Some(serde_json::from_slice(&data)?)) |
| 103 | } |
| 104 | |
| 105 | fn credential( |
| 106 | &self, |
| 107 | config: &Config, |
| 108 | identity: &ProviderIdentity, |
| 109 | create: bool, |
| 110 | ) -> Result<String> { |
| 111 | let credential = config |
| 112 | .readonly_health_credential_generation(identity) |
| 113 | .context("The current connection identity cannot be proved")?; |
| 114 | let key = crate::session_manager::SessionManager::exec_route_binding_key( |
| 115 | &self.home.join("worker-model-pool"), |
| 116 | create, |
| 117 | )?; |
| 118 | let provider = config.provider_config_for(identity); |
| 119 | let global_headers: BTreeMap<_, _> = config.http_headers.iter().flatten().collect(); |
| 120 | let provider_headers: BTreeMap<_, _> = provider |
| 121 | .and_then(|entry| entry.http_headers.as_ref()) |
| 122 | .into_iter() |
| 123 | .flatten() |
| 124 | .collect(); |
| 125 | let connection = serde_json::to_string(&( |
| 126 | &self.scope, |
| 127 | global_headers, |
| 128 | provider_headers, |
| 129 | provider.and_then(|entry| entry.path_suffix.as_deref()), |
| 130 | ))?; |
| 131 | Ok(credential.seal_for_worker_pool(&key, &connection)) |
| 132 | } |
| 133 | |
| 134 | fn view( |
| 135 | &self, |
| 136 | config: &Config, |
| 137 | identity: &ProviderIdentity, |
| 138 | stored: StoredPool, |
| 139 | ) -> WorkerPoolView { |
| 140 | let needs_reselection = stored.mode != WorkerPoolMode::None |
| 141 | && self.credential(config, identity, false).ok().as_deref() |
| 142 | != Some(stored.connection.as_str()); |
| 143 | WorkerPoolView { |
| 144 | mode: stored.mode, |
| 145 | models: stored.models, |
| 146 | revision: stored.revision, |
| 147 | needs_reselection, |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | pub fn read(config: &Config, identity: &ProviderIdentity) -> Result<Option<WorkerPoolView>> { |
| 153 | let files = PoolFiles::for_connection(config, identity)?; |
| 154 | Ok(files |
| 155 | .read()? |
| 156 | .map(|stored| files.view(config, identity, stored))) |
| 157 | } |
| 158 | |
| 159 | fn eligible(row: &ExactRouteModel, inventory: &ExactRouteInventory, verified_chat: bool) -> bool { |
| 160 | let evidence = (matches!(inventory.status, CatalogStatus::Fresh) |
| 161 | && row.evidence == InventoryEvidence::Advertised) |
| 162 | || (!inventory.discovery_supported |
| 163 | && row.evidence == InventoryEvidence::ConfiguredUnverified); |
| 164 | evidence |
| 165 | && row |
| 166 | .model_type |
| 167 | .as_deref() |
| 168 | .map_or(verified_chat, |kind| kind == "chat") |
| 169 | && row.tools_supported == Some(true) |
| 170 | && matches!( |
| 171 | row.readiness, |
| 172 | ResolvedProviderReadiness::Ready |
| 173 | | ResolvedProviderReadiness::SavedUnchecked |
| 174 | | ResolvedProviderReadiness::ConnectionCheckedModelUnchecked |
| 175 | | ResolvedProviderReadiness::LocalUnchecked |
| 176 | | ResolvedProviderReadiness::NoAuthUnchecked |
| 177 | | ResolvedProviderReadiness::ImportedTokenUnchecked |
| 178 | ) |
| 179 | } |
| 180 | |
| 181 | pub fn update( |
| 182 | config: &Config, |
| 183 | identity: &ProviderIdentity, |
| 184 | update: SetWorkerPool, |
| 185 | health: &ProviderReadinessSnapshot, |
| 186 | ) -> Result<WorkerPoolView> { |
| 187 | ensure!( |
| 188 | update.models.len() <= MAX_MODELS, |
| 189 | "Too many selected worker models" |
| 190 | ); |
| 191 | ensure!( |
| 192 | (update.mode == WorkerPoolMode::Selected) != update.models.is_empty(), |
| 193 | "Only Selected mode accepts model IDs, and it requires at least one model" |
| 194 | ); |
| 195 | ensure!( |
| 196 | update |
| 197 | .models |
| 198 | .iter() |
| 199 | .all(|model| codewhale_runtime::catalog_cache::valid_catalog_model_id(model)), |
| 200 | "Invalid worker model ID" |
| 201 | ); |
| 202 | let files = PoolFiles::for_connection(config, identity)?; |
| 203 | let file = WorkspaceFile::open_resolved_root(&files.home, &files.slot, true)?; |
| 204 | let lock_name = format!( |
| 205 | "{}.lock", |
| 206 | files |
| 207 | .slot |
| 208 | .file_name() |
| 209 | .expect("pool slot name") |
| 210 | .to_string_lossy() |
| 211 | ); |
| 212 | let lock_file = file.sibling(&lock_name)?; |
| 213 | let mut lock = fd_lock::RwLock::new(lock_file.open_update(true, false)?); |
| 214 | let _write = lock.write()?; |
| 215 | let revision = files.read()?.map_or(0, |current| current.revision); |
| 216 | ensure!( |
| 217 | update.expected_revision == revision, |
| 218 | WorkerPoolConflict::Revision |
| 219 | ); |
| 220 | let (binding, _) = crate::provider_catalog_live::inventory_scope(config, identity) |
| 221 | .map_err(anyhow::Error::msg)?; |
| 222 | ensure!(binding == update.binding_id, WorkerPoolConflict::Binding); |
| 223 | let (connection, verified_chat_models) = if update.mode == WorkerPoolMode::None { |
| 224 | (String::new(), BTreeSet::new()) |
| 225 | } else { |
| 226 | let inventory = |
| 227 | crate::model_inventory::exact_route_inventory(config, identity, health, &[]) |
| 228 | .map_err(anyhow::Error::msg)?; |
| 229 | ensure!( |
| 230 | update.models.iter().all(|model| inventory |
| 231 | .models |
| 232 | .iter() |
| 233 | .any(|row| &row.model == model && eligible(row, &inventory, false))), |
| 234 | "A selected model does not have current chat and tool support" |
| 235 | ); |
| 236 | let verified_chat_models = inventory |
| 237 | .models |
| 238 | .iter() |
| 239 | .filter(|row| eligible(row, &inventory, false)) |
| 240 | .filter(|row| row.readiness == ResolvedProviderReadiness::Ready) |
| 241 | .filter(|row| codewhale_runtime::catalog_cache::valid_catalog_model_id(&row.model)) |
| 242 | .filter(|row| update.mode == WorkerPoolMode::All || update.models.contains(&row.model)) |
| 243 | .take(MAX_MODELS) |
| 244 | .map(|row| row.model.clone()) |
| 245 | .collect(); |
| 246 | let connection = files.credential(config, identity, true)?; |
| 247 | let (current_binding, _) = crate::provider_catalog_live::inventory_scope(config, identity) |
| 248 | .map_err(anyhow::Error::msg)?; |
| 249 | ensure!( |
| 250 | binding == current_binding && inventory.is_current(config, identity), |
| 251 | WorkerPoolConflict::Inventory |
| 252 | ); |
| 253 | (connection, verified_chat_models) |
| 254 | }; |
| 255 | let stored = StoredPool { |
| 256 | mode: update.mode, |
| 257 | models: update.models, |
| 258 | revision: revision |
| 259 | .checked_add(1) |
| 260 | .context("Worker model pool revision exhausted")?, |
| 261 | connection, |
| 262 | verified_chat_models, |
| 263 | }; |
| 264 | let encoded = serde_json::to_vec(&stored)?; |
| 265 | ensure!( |
| 266 | encoded.len() as u64 <= MAX_POOL_BYTES, |
| 267 | "Worker model pool is too large" |
| 268 | ); |
| 269 | file.replace(&encoded)?; |
| 270 | Ok(files.view(config, identity, stored)) |
| 271 | } |
| 272 | |
| 273 | pub fn requires_inventory(config: &Config, identity: &ProviderIdentity) -> Result<bool> { |
| 274 | let base = config.base_url_for_route(identity); |
| 275 | Ok(read(config, identity)?.is_some_and(|pool| { |
| 276 | pool.mode != WorkerPoolMode::None |
| 277 | && !crate::client::model_listing_unavailable(identity.provider, &base) |
| 278 | && !crate::provider_lake::live_catalog_unavailable(config, identity) |
| 279 | && !matches!( |
| 280 | crate::provider_catalog_live::status_for_route( |
| 281 | identity.provider, |
| 282 | identity.key.as_str(), |
| 283 | &base |
| 284 | ), |
| 285 | CatalogStatus::Failed { |
| 286 | reason: codewhale_config::catalog::CatalogRefreshError::NotFound |
| 287 | } |
| 288 | ) |
| 289 | })) |
| 290 | } |
| 291 | |
| 292 | pub fn require_worker( |
| 293 | config: &Config, |
| 294 | identity: &ProviderIdentity, |
| 295 | wire_model: &str, |
| 296 | ) -> Result<()> { |
| 297 | require_worker_with_health(config, identity, wire_model, &Default::default()) |
| 298 | } |
| 299 | |
| 300 | pub(crate) fn require_worker_with_health( |
| 301 | config: &Config, |
| 302 | identity: &ProviderIdentity, |
| 303 | wire_model: &str, |
| 304 | health: &ProviderReadinessSnapshot, |
| 305 | ) -> Result<()> { |
| 306 | admit_worker_with_health(config, identity, wire_model, health).map(|_| ()) |
| 307 | } |
| 308 | |
| 309 | pub(crate) fn admit_worker_with_health( |
| 310 | config: &Config, |
| 311 | identity: &ProviderIdentity, |
| 312 | wire_model: &str, |
| 313 | health: &ProviderReadinessSnapshot, |
| 314 | ) -> Result<Option<WorkerPoolView>> { |
| 315 | let files = PoolFiles::for_connection(config, identity)?; |
| 316 | let Some(stored) = files.read()? else { |
| 317 | return Ok(None); |
| 318 | }; |
| 319 | let verified_chat = stored.verified_chat_models.contains(wire_model); |
| 320 | let pool = files.view(config, identity, stored); |
| 321 | if pool.mode == WorkerPoolMode::None |
| 322 | || (pool.mode == WorkerPoolMode::Selected && !pool.models.contains(wire_model)) |
| 323 | { |
| 324 | bail!( |
| 325 | "This model is outside the selected worker pool for {}", |
| 326 | identity.key |
| 327 | ); |
| 328 | } |
| 329 | ensure!( |
| 330 | !pool.needs_reselection, |
| 331 | "The worker pool connection changed; reselect its models" |
| 332 | ); |
| 333 | let inventory = crate::model_inventory::exact_route_inventory( |
| 334 | config, |
| 335 | identity, |
| 336 | health, |
| 337 | &[wire_model.to_owned()], |
| 338 | ) |
| 339 | .map_err(anyhow::Error::msg)?; |
| 340 | ensure!( |
| 341 | inventory |
| 342 | .models |
| 343 | .iter() |
| 344 | .any(|row| row.model == wire_model && eligible(row, &inventory, verified_chat)) |
| 345 | && inventory.is_current(config, identity), |
| 346 | "This worker route lacks current chat and tool evidence" |
| 347 | ); |
| 348 | Ok(Some(pool)) |
| 349 | } |
| 350 | |
| 351 | #[cfg(test)] |
| 352 | mod tests { |
| 353 | use super::*; |
| 354 | use codewhale_config::catalog::{ |
| 355 | CatalogOffering, ProviderCatalogDelta, base_url_fingerprint, now_unix, |
| 356 | }; |
| 357 | |
| 358 | #[test] |
| 359 | fn pool_cas_and_exact_credentials_do_not_cross_named_connections() { |
| 360 | let _home = crate::test_support::SealedHome::new(); |
| 361 | let _catalog = crate::provider_lake::lock_live_snapshot(); |
| 362 | crate::provider_catalog_live::reset_cache_for_test(); |
| 363 | let mut config: Config = toml::from_str( |
| 364 | r#" |
| 365 | [providers.primary] |
| 366 | kind = "openai-compatible" |
| 367 | base_url = "http://127.0.0.1:18091/v1" |
| 368 | api_key = "fixture-primary-key" |
| 369 | [providers.secondary] |
| 370 | kind = "openai-compatible" |
| 371 | base_url = "http://127.0.0.1:18091/v1" |
| 372 | api_key = "fixture-secondary-key" |
| 373 | "#, |
| 374 | ) |
| 375 | .unwrap(); |
| 376 | let primary = config.resolve_provider_pin_identity("primary").unwrap(); |
| 377 | let secondary = config.resolve_provider_pin_identity("secondary").unwrap(); |
| 378 | let (binding, _) = |
| 379 | crate::provider_catalog_live::inventory_scope(&config, &primary).unwrap(); |
| 380 | let base = config.base_url_for_route(&primary); |
| 381 | let fingerprint = base_url_fingerprint(&base); |
| 382 | let ticket = crate::provider_catalog_live::begin_refresh_for_identity( |
| 383 | primary.provider, |
| 384 | primary.key.as_str(), |
| 385 | &base, |
| 386 | ); |
| 387 | crate::provider_catalog_live::record_success_if_current( |
| 388 | &ticket, |
| 389 | ProviderCatalogDelta { |
| 390 | provider: primary.key.to_string(), |
| 391 | base_url_fingerprint: fingerprint, |
| 392 | fetched_at: now_unix(), |
| 393 | offerings: vec![CatalogOffering { |
| 394 | provider: primary.key.to_string(), |
| 395 | wire_model_id: "same-model".into(), |
| 396 | endpoint_key: "chat".into(), |
| 397 | tool_call: Some(true), |
| 398 | model_type: Some("chat".into()), |
| 399 | ..Default::default() |
| 400 | }], |
| 401 | }, |
| 402 | ) |
| 403 | .unwrap(); |
| 404 | let write = |expected_revision| SetWorkerPool { |
| 405 | mode: WorkerPoolMode::Selected, |
| 406 | models: BTreeSet::from(["same-model".to_string()]), |
| 407 | expected_revision, |
| 408 | binding_id: binding.clone(), |
| 409 | }; |
| 410 | let selected = update(&config, &primary, write(0), &Default::default()).unwrap(); |
| 411 | assert_eq!(selected.revision, 1); |
| 412 | assert!(!selected.needs_reselection); |
| 413 | assert_eq!( |
| 414 | update(&config, &primary, write(0), &Default::default()) |
| 415 | .unwrap_err() |
| 416 | .downcast_ref::<WorkerPoolConflict>(), |
| 417 | Some(&WorkerPoolConflict::Revision) |
| 418 | ); |
| 419 | let mut stale_binding = write(1); |
| 420 | stale_binding.binding_id.push('x'); |
| 421 | assert_eq!( |
| 422 | update(&config, &primary, stale_binding, &Default::default()) |
| 423 | .unwrap_err() |
| 424 | .downcast_ref::<WorkerPoolConflict>(), |
| 425 | Some(&WorkerPoolConflict::Binding) |
| 426 | ); |
| 427 | assert!(read(&config, &secondary).unwrap().is_none()); |
| 428 | assert!(require_worker(&config, &primary, "same-model").is_ok()); |
| 429 | assert!(require_worker(&config, &primary, "different-model").is_err()); |
| 430 | let stored = PoolFiles::for_connection(&config, &primary) |
| 431 | .unwrap() |
| 432 | .read() |
| 433 | .unwrap() |
| 434 | .unwrap(); |
| 435 | assert!(stored.verified_chat_models.is_empty()); |
| 436 | let mut checked = ProviderReadinessSnapshot::default(); |
| 437 | checked.record_models_probe_success( |
| 438 | &config, |
| 439 | &primary, |
| 440 | "same-model", |
| 441 | config |
| 442 | .readonly_health_credential_generation(&primary) |
| 443 | .unwrap(), |
| 444 | ); |
| 445 | assert!(require_worker_with_health(&config, &primary, "same-model", &checked).is_ok()); |
| 446 | let mut refused = ProviderReadinessSnapshot::default(); |
| 447 | refused.record_failure_message( |
| 448 | &config, |
| 449 | &primary, |
| 450 | "same-model", |
| 451 | codewhale_error_taxonomy::ErrorCategory::Authentication, |
| 452 | "fixture credential refused", |
| 453 | ); |
| 454 | assert!(require_worker_with_health(&config, &primary, "same-model", &refused).is_err()); |
| 455 | let mut header_rotation = config.clone(); |
| 456 | header_rotation |
| 457 | .provider_config_for_mut(&primary) |
| 458 | .unwrap() |
| 459 | .http_headers = Some(std::collections::HashMap::from([( |
| 460 | "x-account".into(), |
| 461 | "other-account".into(), |
| 462 | )])); |
| 463 | assert!( |
| 464 | read(&header_rotation, &primary) |
| 465 | .unwrap() |
| 466 | .unwrap() |
| 467 | .needs_reselection |
| 468 | ); |
| 469 | config.provider_config_for_mut(&primary).unwrap().api_key = |
| 470 | Some("fixture-rotated-key".into()); |
| 471 | assert!(read(&config, &primary).unwrap().unwrap().needs_reselection); |
| 472 | assert!(require_worker(&config, &primary, "same-model").is_err()); |
| 473 | let (binding_id, _) = |
| 474 | crate::provider_catalog_live::inventory_scope(&config, &primary).unwrap(); |
| 475 | let disabled = update( |
| 476 | &config, |
| 477 | &primary, |
| 478 | SetWorkerPool { |
| 479 | mode: WorkerPoolMode::None, |
| 480 | models: BTreeSet::new(), |
| 481 | expected_revision: 1, |
| 482 | binding_id, |
| 483 | }, |
| 484 | &Default::default(), |
| 485 | ) |
| 486 | .unwrap(); |
| 487 | assert_eq!(disabled.revision, 2); |
| 488 | assert!(require_worker(&config, &primary, "same-model").is_err()); |
| 489 | crate::provider_catalog_live::reset_cache_for_test(); |
| 490 | } |
| 491 | |
| 492 | #[test] |
| 493 | fn pool_with_maximum_length_ids_and_chat_evidence_is_readable() { |
| 494 | let _home = crate::test_support::SealedHome::new(); |
| 495 | let config = Config::default(); |
| 496 | let identity = config.active_provider_identity().unwrap(); |
| 497 | let files = PoolFiles::for_connection(&config, &identity).unwrap(); |
| 498 | let models: BTreeSet<_> = (0..MAX_MODELS) |
| 499 | .map(|index| format!("{index:03}{}", "a".repeat(253))) |
| 500 | .collect(); |
| 501 | assert!( |
| 502 | models |
| 503 | .iter() |
| 504 | .all(|id| codewhale_runtime::catalog_cache::valid_catalog_model_id(id)) |
| 505 | ); |
| 506 | let stored = StoredPool { |
| 507 | mode: WorkerPoolMode::Selected, |
| 508 | verified_chat_models: models.clone(), |
| 509 | models, |
| 510 | revision: 1, |
| 511 | connection: "fixture".to_string(), |
| 512 | }; |
| 513 | let encoded = serde_json::to_vec(&stored).unwrap(); |
| 514 | let file = WorkspaceFile::open_resolved_root(&files.home, &files.slot, true).unwrap(); |
| 515 | file.replace(&encoded).unwrap(); |
| 516 | let restored = files.read().unwrap().unwrap(); |
| 517 | assert_eq!(restored.models, stored.models); |
| 518 | assert_eq!(restored.verified_chat_models, stored.verified_chat_models); |
| 519 | } |
| 520 | } |
| 521 |