| 1 | use std::collections::HashMap; |
| 2 | use std::sync::{Arc, Mutex, OnceLock}; |
| 3 | use std::time::{Duration, Instant}; |
| 4 | |
| 5 | use codewhale_config::OwnerRef; |
| 6 | use codewhale_execpolicy::tool_rules::tool_denied; |
| 7 | use serde::Deserialize; |
| 8 | use serde_json::{Value, json}; |
| 9 | use tokio_util::sync::CancellationToken; |
| 10 | |
| 11 | use super::dsh_broker::{ |
| 12 | BrokerCall, BrokerContext, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode, |
| 13 | }; |
| 14 | use super::protocol::DshService; |
| 15 | use crate::core::engine::rlm_host::{CapturedRlmCaller, RlmInvocation, RlmMode, RlmPromptPolicy}; |
| 16 | use crate::llm_client::ProviderUsageCoverage; |
| 17 | use crate::rlm::bridge::{RlmUsageAccumulator, RlmUsageSnapshot}; |
| 18 | use crate::tools::rlm::RLM_TOOL_NAME; |
| 19 | use crate::tools::spec::ToolContext; |
| 20 | |
| 21 | pub const SESSION_PROVIDER: &str = "session"; |
| 22 | const MAX_PROMPT_BYTES: usize = 256 * 1024; |
| 23 | const MAX_SYSTEM_BYTES: usize = 4096; |
| 24 | const MAX_NAME_BYTES: usize = 256; |
| 25 | const DEFAULT_OUTPUT_TOKENS: u32 = 4096; |
| 26 | const MAX_OUTPUT_TOKENS: u32 = 16_384; |
| 27 | const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120); |
| 28 | const MAX_TIMEOUT: Duration = Duration::from_secs(300); |
| 29 | const MAX_IN_FLIGHT: u32 = 2; |
| 30 | const MAX_IN_FLIGHT_ROWS: usize = 256; |
| 31 | const LOG: &str = "codewhale::dsh_llm"; |
| 32 | |
| 33 | #[derive(Deserialize)] |
| 34 | #[serde(tag = "method", content = "input", deny_unknown_fields)] |
| 35 | enum LlmMethod { |
| 36 | #[serde(rename = "catalog")] |
| 37 | Catalog(Empty), |
| 38 | #[serde(rename = "complete")] |
| 39 | Complete(CompleteInput), |
| 40 | } |
| 41 | |
| 42 | impl BrokerMethods for LlmMethod { |
| 43 | const NAMES: &'static [&'static str] = &["catalog", "complete"]; |
| 44 | } |
| 45 | |
| 46 | #[derive(Deserialize)] |
| 47 | #[serde(deny_unknown_fields)] |
| 48 | struct Empty {} |
| 49 | |
| 50 | #[derive(Deserialize)] |
| 51 | #[serde(deny_unknown_fields)] |
| 52 | struct CompleteInput { |
| 53 | prompt: String, |
| 54 | #[serde(default)] |
| 55 | system: Option<String>, |
| 56 | #[serde(default)] |
| 57 | provider: Option<String>, |
| 58 | #[serde(default)] |
| 59 | model: Option<String>, |
| 60 | #[serde(default)] |
| 61 | max_output_tokens: Option<u32>, |
| 62 | #[serde(default)] |
| 63 | timeout_ms: Option<u64>, |
| 64 | } |
| 65 | |
| 66 | fn invalid(message: &str) -> BrokerRefusal { |
| 67 | BrokerRefusal::InvalidInput { |
| 68 | service: DshService::Llm, |
| 69 | message: message.to_string(), |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | fn refused(message: &str) -> BrokerRefusal { |
| 74 | BrokerRefusal::Refused { |
| 75 | service: DshService::Llm, |
| 76 | message: message.to_string(), |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | fn denied(message: &str) -> BrokerRefusal { |
| 81 | BrokerRefusal::Denied { |
| 82 | service: DshService::Llm, |
| 83 | message: message.to_string(), |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | #[derive(Clone)] |
| 88 | enum Gate { |
| 89 | Live(Arc<BrokerContext>), |
| 90 | #[cfg(test)] |
| 91 | Stub, |
| 92 | } |
| 93 | |
| 94 | impl Gate { |
| 95 | async fn act( |
| 96 | &self, |
| 97 | method: &str, |
| 98 | effect: BrokerEffect, |
| 99 | target: Option<&str>, |
| 100 | ) -> Result<(), BrokerRefusal> { |
| 101 | match self { |
| 102 | Self::Live(context) => context.act(method, effect, target).await, |
| 103 | #[cfg(test)] |
| 104 | Self::Stub => Ok(()), |
| 105 | } |
| 106 | } |
| 107 | |
| 108 | fn record(&self, entry: Value) -> bool { |
| 109 | match self { |
| 110 | Self::Live(context) => context.record(entry), |
| 111 | #[cfg(test)] |
| 112 | Self::Stub => true, |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | type FlightKey = (String, String); |
| 118 | |
| 119 | fn flights() -> &'static Mutex<HashMap<FlightKey, u32>> { |
| 120 | static FLIGHTS: OnceLock<Mutex<HashMap<FlightKey, u32>>> = OnceLock::new(); |
| 121 | FLIGHTS.get_or_init(Mutex::default) |
| 122 | } |
| 123 | |
| 124 | fn flight_key(owner: &OwnerRef, session_id: &str) -> FlightKey { |
| 125 | (owner.plugin_id.clone(), session_id.to_string()) |
| 126 | } |
| 127 | |
| 128 | fn with_flights<T>(act: impl FnOnce(&mut HashMap<FlightKey, u32>) -> T) -> T { |
| 129 | act(&mut flights() |
| 130 | .lock() |
| 131 | .unwrap_or_else(std::sync::PoisonError::into_inner)) |
| 132 | } |
| 133 | |
| 134 | #[cfg(test)] |
| 135 | fn in_flight_count(key: &FlightKey) -> u32 { |
| 136 | with_flights(|table| table.get(key).copied().unwrap_or(0)) |
| 137 | } |
| 138 | |
| 139 | fn reserve(table: &mut HashMap<FlightKey, u32>, key: &FlightKey) -> Result<(), BrokerRefusal> { |
| 140 | if !table.contains_key(key) && table.len() >= MAX_IN_FLIGHT_ROWS { |
| 141 | return Err(refused("the llm broker is busy")); |
| 142 | } |
| 143 | let count = table.entry(key.clone()).or_insert(0); |
| 144 | if *count >= MAX_IN_FLIGHT { |
| 145 | return Err(refused( |
| 146 | "this plugin already has model calls running in this session", |
| 147 | )); |
| 148 | } |
| 149 | *count += 1; |
| 150 | Ok(()) |
| 151 | } |
| 152 | |
| 153 | fn release(table: &mut HashMap<FlightKey, u32>, key: &FlightKey) { |
| 154 | if let Some(count) = table.get_mut(key) { |
| 155 | if *count <= 1 { |
| 156 | table.remove(key); |
| 157 | } else { |
| 158 | *count -= 1; |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | struct RecordMeta { |
| 164 | plugin_id: String, |
| 165 | session_id: String, |
| 166 | provider: String, |
| 167 | model: String, |
| 168 | prompt_bytes: usize, |
| 169 | prompt_sha256: String, |
| 170 | system_bytes: usize, |
| 171 | system_sha256: Option<String>, |
| 172 | started: Instant, |
| 173 | } |
| 174 | |
| 175 | fn record_completion( |
| 176 | meta: &RecordMeta, |
| 177 | gate: &Gate, |
| 178 | outcome: &str, |
| 179 | observed: Option<&Observed>, |
| 180 | ) -> u64 { |
| 181 | let duration_ms = u64::try_from(meta.started.elapsed().as_millis()).unwrap_or(u64::MAX); |
| 182 | let (provider, model) = observed |
| 183 | .and_then(|obs| obs.route.clone()) |
| 184 | .unwrap_or_else(|| (meta.provider.clone(), meta.model.clone())); |
| 185 | let tokens = observed.and_then(|obs| obs.tokens.as_ref()); |
| 186 | let requests = observed.map_or(0, |obs| obs.requests); |
| 187 | let coverage = observed.map_or("unknown", |obs| obs.coverage); |
| 188 | tracing::info!( |
| 189 | target: LOG, |
| 190 | plugin = %meta.plugin_id, |
| 191 | session = %meta.session_id, |
| 192 | outcome, |
| 193 | provider = %provider, |
| 194 | model = %model, |
| 195 | coverage, |
| 196 | input_tokens = tokens.map(|tokens| tokens.input), |
| 197 | output_tokens = tokens.map(|tokens| tokens.output), |
| 198 | requests, |
| 199 | duration_ms, |
| 200 | prompt_bytes = meta.prompt_bytes, |
| 201 | prompt_sha256 = %meta.prompt_sha256, |
| 202 | system_bytes = meta.system_bytes, |
| 203 | "auxiliary model call for a plugin" |
| 204 | ); |
| 205 | let mut entry = json!({ |
| 206 | "method": "complete", |
| 207 | "outcome": outcome, |
| 208 | "provider": provider, |
| 209 | "model": model, |
| 210 | "requests": requests, |
| 211 | "duration_ms": duration_ms, |
| 212 | "prompt_bytes": meta.prompt_bytes, |
| 213 | "prompt_sha256": meta.prompt_sha256, |
| 214 | "system_bytes": meta.system_bytes, |
| 215 | }); |
| 216 | if let Some(system_sha256) = &meta.system_sha256 { |
| 217 | entry["system_sha256"] = json!(system_sha256); |
| 218 | } |
| 219 | if let Some(tokens) = tokens { |
| 220 | entry["input_tokens"] = json!(tokens.input); |
| 221 | entry["output_tokens"] = json!(tokens.output); |
| 222 | } |
| 223 | gate.record(entry); |
| 224 | duration_ms |
| 225 | } |
| 226 | |
| 227 | struct Flight { |
| 228 | key: FlightKey, |
| 229 | gate: Gate, |
| 230 | meta: RecordMeta, |
| 231 | settled: bool, |
| 232 | } |
| 233 | |
| 234 | impl Flight { |
| 235 | fn admit(key: FlightKey, gate: Gate, meta: RecordMeta) -> Result<Self, BrokerRefusal> { |
| 236 | with_flights(|table| reserve(table, &key))?; |
| 237 | Ok(Self { |
| 238 | key, |
| 239 | gate, |
| 240 | meta, |
| 241 | settled: false, |
| 242 | }) |
| 243 | } |
| 244 | |
| 245 | fn settle(mut self, outcome: &str, observed: &Observed) -> u64 { |
| 246 | self.settled = true; |
| 247 | with_flights(|table| release(table, &self.key)); |
| 248 | record_completion(&self.meta, &self.gate, outcome, Some(observed)) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | impl Drop for Flight { |
| 253 | fn drop(&mut self) { |
| 254 | if self.settled { |
| 255 | return; |
| 256 | } |
| 257 | with_flights(|table| release(table, &self.key)); |
| 258 | record_completion(&self.meta, &self.gate, "unknown", None); |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | struct Tokens { |
| 263 | input: u64, |
| 264 | output: u64, |
| 265 | cache_read: Option<u64>, |
| 266 | cache_write: Option<u64>, |
| 267 | reasoning: Option<u64>, |
| 268 | } |
| 269 | |
| 270 | struct Observed { |
| 271 | route: Option<(String, String)>, |
| 272 | coverage: &'static str, |
| 273 | tokens: Option<Tokens>, |
| 274 | requests: usize, |
| 275 | } |
| 276 | |
| 277 | impl Observed { |
| 278 | fn of(snapshot: &RlmUsageSnapshot) -> Self { |
| 279 | let route = snapshot |
| 280 | .records |
| 281 | .iter() |
| 282 | .map(|record| &record.usage.route) |
| 283 | .chain(snapshot.drop_records.iter().map(|record| &record.route)) |
| 284 | .next() |
| 285 | .map(|route| (route.provider_identity.clone(), route.model.clone())); |
| 286 | let requests = snapshot.records.len() + snapshot.drop_records.len(); |
| 287 | let clean = snapshot.drop_records.is_empty() && snapshot.dropped_records == 0; |
| 288 | let coverages: Vec<Option<ProviderUsageCoverage>> = snapshot |
| 289 | .records |
| 290 | .iter() |
| 291 | .map(|record| record.settlement.as_ref().map(|revision| revision.coverage)) |
| 292 | .collect(); |
| 293 | let all = |wanted: ProviderUsageCoverage| { |
| 294 | !coverages.is_empty() && coverages.iter().all(|coverage| *coverage == Some(wanted)) |
| 295 | }; |
| 296 | let coverage = if !clean { |
| 297 | "unknown" |
| 298 | } else if coverages.is_empty() { |
| 299 | "not_dispatched" |
| 300 | } else if all(ProviderUsageCoverage::Reported) { |
| 301 | "reported" |
| 302 | } else if all(ProviderUsageCoverage::Missing) { |
| 303 | "missing" |
| 304 | } else if all(ProviderUsageCoverage::NotDispatched) { |
| 305 | "not_dispatched" |
| 306 | } else if all(ProviderUsageCoverage::Rejected) { |
| 307 | "rejected" |
| 308 | } else if coverages.iter().any(Option::is_none) { |
| 309 | "unknown" |
| 310 | } else { |
| 311 | "incomplete" |
| 312 | }; |
| 313 | let tokens = (coverage == "reported").then(|| { |
| 314 | let sum = |field: fn(&codewhale_models::Usage) -> Option<u32>| { |
| 315 | let values: Vec<u64> = snapshot |
| 316 | .records |
| 317 | .iter() |
| 318 | .filter_map(|record| field(&record.usage.usage).map(u64::from)) |
| 319 | .collect(); |
| 320 | (!values.is_empty()).then(|| values.iter().sum::<u64>()) |
| 321 | }; |
| 322 | Tokens { |
| 323 | input: sum(|usage| Some(usage.input_tokens)).unwrap_or(0), |
| 324 | output: sum(|usage| Some(usage.output_tokens)).unwrap_or(0), |
| 325 | cache_read: sum(|usage| usage.prompt_cache_hit_tokens), |
| 326 | cache_write: sum(|usage| usage.prompt_cache_write_tokens), |
| 327 | reasoning: sum(|usage| usage.reasoning_tokens), |
| 328 | } |
| 329 | }); |
| 330 | Self { |
| 331 | route, |
| 332 | coverage, |
| 333 | tokens, |
| 334 | requests, |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | fn usage_json(&self) -> Value { |
| 339 | let tokens = self.tokens.as_ref(); |
| 340 | json!({ |
| 341 | "coverage": self.coverage, |
| 342 | "input_tokens": tokens.map(|tokens| tokens.input), |
| 343 | "output_tokens": tokens.map(|tokens| tokens.output), |
| 344 | "cache_read_tokens": tokens.and_then(|tokens| tokens.cache_read), |
| 345 | "cache_write_tokens": tokens.and_then(|tokens| tokens.cache_write), |
| 346 | "reasoning_tokens": tokens.and_then(|tokens| tokens.reasoning), |
| 347 | }) |
| 348 | } |
| 349 | |
| 350 | fn route_json(&self) -> Value { |
| 351 | self.route.as_ref().map_or( |
| 352 | Value::Null, |
| 353 | |(provider, model)| json!({ "provider": provider, "model": model }), |
| 354 | ) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | fn authority<'a>( |
| 359 | owner: &OwnerRef, |
| 360 | tool: &'a ToolContext, |
| 361 | cancel: &CancellationToken, |
| 362 | ) -> Result<&'a CapturedRlmCaller, BrokerRefusal> { |
| 363 | if cancel.is_cancelled() { |
| 364 | return Err(refused("the llm broker call was withdrawn")); |
| 365 | } |
| 366 | let Some(caller) = tool.rlm_caller.as_deref() else { |
| 367 | return Err(BrokerRefusal::NotAvailable(DshService::Llm)); |
| 368 | }; |
| 369 | if tool_denied(Some(&tool.disallowed_tools), RLM_TOOL_NAME) |
| 370 | || tool_denied(Some(&tool.disallowed_tools), "rlm_eval") |
| 371 | || tool |
| 372 | .child_host |
| 373 | .as_ref() |
| 374 | .is_some_and(|child| !child.is_action_allowed(RLM_TOOL_NAME, "eval")) |
| 375 | { |
| 376 | tracing::info!(target: LOG, plugin = %owner.plugin_id, "model call denied by the caller's own tool limits"); |
| 377 | return Err(denied("model calls are not allowed for this caller")); |
| 378 | } |
| 379 | caller.validate_context(tool).map_err(|error| { |
| 380 | tracing::warn!(target: LOG, plugin = %owner.plugin_id, %error, "the session route refused an llm broker call"); |
| 381 | refused("the session's model route is not available to this call") |
| 382 | })?; |
| 383 | Ok(caller) |
| 384 | } |
| 385 | |
| 386 | fn route_model(caller: &CapturedRlmCaller) -> Result<&str, BrokerRefusal> { |
| 387 | Some(caller.route_model()) |
| 388 | .filter(|model| !model.is_empty()) |
| 389 | .ok_or(BrokerRefusal::NotAvailable(DshService::Llm)) |
| 390 | } |
| 391 | |
| 392 | async fn catalog( |
| 393 | caller: &CapturedRlmCaller, |
| 394 | tool: &ToolContext, |
| 395 | gate: &Gate, |
| 396 | ) -> Result<Value, BrokerRefusal> { |
| 397 | let model = route_model(caller)?.to_string(); |
| 398 | let context_window = caller.route_context_window().or(tool.route_context_window); |
| 399 | gate.act("catalog", BrokerEffect::Read, None).await?; |
| 400 | Ok(json!({ |
| 401 | "providers": [{ "id": SESSION_PROVIDER, "name": "Codewhale session route" }], |
| 402 | "models": [{ |
| 403 | "provider": SESSION_PROVIDER, |
| 404 | "id": model, |
| 405 | "name": model, |
| 406 | "context_window": context_window, |
| 407 | "default_max_output_tokens": DEFAULT_OUTPUT_TOKENS, |
| 408 | "max_output_tokens": MAX_OUTPUT_TOKENS, |
| 409 | }], |
| 410 | "limits": { |
| 411 | "prompt_bytes": MAX_PROMPT_BYTES, |
| 412 | "system_bytes": MAX_SYSTEM_BYTES, |
| 413 | "default_timeout_ms": u64::try_from(DEFAULT_TIMEOUT.as_millis()).unwrap_or(u64::MAX), |
| 414 | "max_timeout_ms": u64::try_from(MAX_TIMEOUT.as_millis()).unwrap_or(u64::MAX), |
| 415 | "concurrent_calls": MAX_IN_FLIGHT, |
| 416 | }, |
| 417 | })) |
| 418 | } |
| 419 | |
| 420 | struct Checked { |
| 421 | prompt: String, |
| 422 | system: Option<String>, |
| 423 | max_tokens: u32, |
| 424 | timeout: Duration, |
| 425 | } |
| 426 | |
| 427 | fn checked(input: CompleteInput, caller: &CapturedRlmCaller) -> Result<Checked, BrokerRefusal> { |
| 428 | if input.prompt.trim().is_empty() { |
| 429 | return Err(invalid("prompt is empty")); |
| 430 | } |
| 431 | if input.prompt.len() > MAX_PROMPT_BYTES { |
| 432 | return Err(invalid("prompt is larger than the catalog's prompt_bytes")); |
| 433 | } |
| 434 | let system = input.system.filter(|system| !system.trim().is_empty()); |
| 435 | if system |
| 436 | .as_ref() |
| 437 | .is_some_and(|system| system.len() > MAX_SYSTEM_BYTES) |
| 438 | { |
| 439 | return Err(invalid("system is larger than the catalog's system_bytes")); |
| 440 | } |
| 441 | if input.max_output_tokens == Some(0) { |
| 442 | return Err(invalid("max_output_tokens must be greater than zero")); |
| 443 | } |
| 444 | if input.timeout_ms == Some(0) { |
| 445 | return Err(invalid("timeout_ms must be greater than zero")); |
| 446 | } |
| 447 | for name in [input.provider.as_ref(), input.model.as_ref()] |
| 448 | .into_iter() |
| 449 | .flatten() |
| 450 | { |
| 451 | if name.len() > MAX_NAME_BYTES { |
| 452 | return Err(invalid("provider and model names are at most 256 bytes")); |
| 453 | } |
| 454 | } |
| 455 | let model = route_model(caller)?; |
| 456 | if input |
| 457 | .provider |
| 458 | .as_deref() |
| 459 | .is_some_and(|provider| provider != SESSION_PROVIDER) |
| 460 | || input.model.as_deref().is_some_and(|asked| asked != model) |
| 461 | { |
| 462 | return Err(refused( |
| 463 | "the llm broker serves only the session's own provider and model; see catalog", |
| 464 | )); |
| 465 | } |
| 466 | let max_timeout_ms = u64::try_from(MAX_TIMEOUT.as_millis()).unwrap_or(u64::MAX); |
| 467 | Ok(Checked { |
| 468 | prompt: input.prompt, |
| 469 | system, |
| 470 | max_tokens: input |
| 471 | .max_output_tokens |
| 472 | .unwrap_or(DEFAULT_OUTPUT_TOKENS) |
| 473 | .min(MAX_OUTPUT_TOKENS), |
| 474 | timeout: input |
| 475 | .timeout_ms |
| 476 | .map_or(DEFAULT_TIMEOUT, |ms| { |
| 477 | Duration::from_millis(ms.min(max_timeout_ms)) |
| 478 | }) |
| 479 | .min(MAX_TIMEOUT), |
| 480 | }) |
| 481 | } |
| 482 | |
| 483 | async fn complete( |
| 484 | owner: &OwnerRef, |
| 485 | session_id: &str, |
| 486 | cancel: &CancellationToken, |
| 487 | caller: &CapturedRlmCaller, |
| 488 | gate: Gate, |
| 489 | input: CompleteInput, |
| 490 | ) -> Result<Value, BrokerRefusal> { |
| 491 | let checked = checked(input, caller)?; |
| 492 | let model = route_model(caller)?.to_string(); |
| 493 | let provider = caller.route_provider_id(); |
| 494 | let target = format!("model {model}, {} bytes", checked.prompt.len()); |
| 495 | gate.act("complete", BrokerEffect::Reach, Some(&target)) |
| 496 | .await?; |
| 497 | |
| 498 | let prompt_bytes = checked.prompt.len(); |
| 499 | let prompt_sha256 = codewhale_runtime::hashing::sha256_hex(checked.prompt.as_bytes()); |
| 500 | let system_bytes = checked.system.as_deref().map_or(0, str::len); |
| 501 | let system_sha256 = checked |
| 502 | .system |
| 503 | .as_deref() |
| 504 | .map(|system| codewhale_runtime::hashing::sha256_hex(system.as_bytes())); |
| 505 | let started = Instant::now(); |
| 506 | let flight = Flight::admit( |
| 507 | flight_key(owner, session_id), |
| 508 | gate, |
| 509 | RecordMeta { |
| 510 | plugin_id: owner.plugin_id.clone(), |
| 511 | session_id: session_id.to_string(), |
| 512 | provider, |
| 513 | model, |
| 514 | prompt_bytes, |
| 515 | prompt_sha256, |
| 516 | system_bytes, |
| 517 | system_sha256, |
| 518 | started, |
| 519 | }, |
| 520 | )?; |
| 521 | |
| 522 | let call_deadline = tokio::time::Instant::now() + checked.timeout; |
| 523 | let deadline = caller |
| 524 | .deadline() |
| 525 | .map_or(call_deadline, |turn| turn.min(call_deadline)); |
| 526 | let accounting = RlmUsageAccumulator::new(); |
| 527 | let result = tokio::select! { |
| 528 | biased; |
| 529 | () = cancel.cancelled() => None, |
| 530 | result = caller.dispatch(RlmInvocation { |
| 531 | prompt: checked.prompt, |
| 532 | mode: RlmMode::Completion, |
| 533 | prompt_policy: RlmPromptPolicy::IsolatedPlugin, |
| 534 | max_tokens: Some(checked.max_tokens), |
| 535 | task_instructions: checked.system, |
| 536 | deadline: Some(deadline), |
| 537 | gate: None, |
| 538 | events: None, |
| 539 | usage: accounting.clone(), |
| 540 | }) => Some(result), |
| 541 | }; |
| 542 | let observed = Observed::of(&accounting.snapshot().await); |
| 543 | let outcome = if result.is_none() || cancel.is_cancelled() { |
| 544 | "cancelled" |
| 545 | } else if result.as_ref().is_some_and(|result| result.error.is_some()) { |
| 546 | if tokio::time::Instant::now() >= deadline { |
| 547 | "timed_out" |
| 548 | } else { |
| 549 | "failed" |
| 550 | } |
| 551 | } else { |
| 552 | "completed" |
| 553 | }; |
| 554 | if let Some(error) = result.as_ref().and_then(|result| result.error.as_ref()) { |
| 555 | tracing::warn!( |
| 556 | target: LOG, |
| 557 | plugin = %owner.plugin_id, |
| 558 | session = %session_id, |
| 559 | %error, |
| 560 | "auxiliary model call failed" |
| 561 | ); |
| 562 | } |
| 563 | if observed.coverage != "reported" && observed.requests > 0 { |
| 564 | tracing::warn!( |
| 565 | target: LOG, |
| 566 | plugin = %owner.plugin_id, |
| 567 | session = %session_id, |
| 568 | coverage = observed.coverage, |
| 569 | "auxiliary model call has no complete usage report; the work is unaffected" |
| 570 | ); |
| 571 | } |
| 572 | let duration_ms = flight.settle(outcome, &observed); |
| 573 | match outcome { |
| 574 | "cancelled" => Err(refused("the model call was cancelled")), |
| 575 | "timed_out" => Err(refused("the model call ran out of time")), |
| 576 | "failed" => Err(refused("the model call did not complete")), |
| 577 | _ => { |
| 578 | let answer = result.expect("completed outcome has result").answer; |
| 579 | Ok(json!({ |
| 580 | "text": answer, |
| 581 | "finish": "stop", |
| 582 | "route": observed.route_json(), |
| 583 | "usage": observed.usage_json(), |
| 584 | "receipt": { |
| 585 | "requests": observed.requests, |
| 586 | "duration_ms": duration_ms, |
| 587 | }, |
| 588 | })) |
| 589 | } |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | async fn run( |
| 594 | owner: &OwnerRef, |
| 595 | session_id: &str, |
| 596 | tool: &ToolContext, |
| 597 | cancel: &CancellationToken, |
| 598 | gate: Gate, |
| 599 | method: LlmMethod, |
| 600 | ) -> Result<Value, BrokerRefusal> { |
| 601 | let caller = authority(owner, tool, cancel)?; |
| 602 | match method { |
| 603 | LlmMethod::Catalog(Empty {}) => catalog(caller, tool, &gate).await, |
| 604 | LlmMethod::Complete(input) => { |
| 605 | complete(owner, session_id, cancel, caller, gate, input).await |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | pub(super) fn serve(call: BrokerCall) -> BrokerFuture { |
| 611 | Box::pin(async move { |
| 612 | let method = decode::<LlmMethod>(&call)?; |
| 613 | let context = Arc::new(call.context); |
| 614 | run( |
| 615 | &call.owner, |
| 616 | &call.session_id, |
| 617 | context.tool(), |
| 618 | context.cancel(), |
| 619 | Gate::Live(Arc::clone(&context)), |
| 620 | method, |
| 621 | ) |
| 622 | .await |
| 623 | }) |
| 624 | } |
| 625 | |
| 626 | #[cfg(test)] |
| 627 | mod tests { |
| 628 | use std::future::Future; |
| 629 | use std::pin::Pin; |
| 630 | use std::sync::Arc; |
| 631 | |
| 632 | use codewhale_agent_contract::role::FleetRole; |
| 633 | use codewhale_agent_contract::worker_profile::WorkerRuntimeProfile; |
| 634 | use codewhale_models::{ContentBlock, MessageRequest, MessageResponse, Usage}; |
| 635 | use codewhale_runtime::config::Config; |
| 636 | |
| 637 | use super::*; |
| 638 | use crate::client::CodewhaleClient; |
| 639 | use crate::core::engine::tests::rlm_host::{Replies, context_for_replies, fixture_config}; |
| 640 | use crate::llm_client::mock::MockLlmClient; |
| 641 | use crate::tools::subagent::engine::ChildAuthority; |
| 642 | use crate::tools::subagent::{SubAgentRuntime, new_shared_subagent_manager}; |
| 643 | |
| 644 | const MODEL: &str = "captured-model"; |
| 645 | |
| 646 | fn owner(plugin: &str) -> OwnerRef { |
| 647 | OwnerRef { |
| 648 | plugin_id: plugin.to_string(), |
| 649 | generation: 1, |
| 650 | owner_token: "token".to_string(), |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | fn reply(text: &str, usage: Usage) -> MessageResponse { |
| 655 | MessageResponse { |
| 656 | tool_projection_warning: None, |
| 657 | id: "mock_msg".to_string(), |
| 658 | r#type: "message".to_string(), |
| 659 | role: "assistant".to_string(), |
| 660 | content: vec![ContentBlock::Text { |
| 661 | text: text.to_string(), |
| 662 | cache_control: None, |
| 663 | }], |
| 664 | model: MODEL.to_string(), |
| 665 | stop_reason: Some("end_turn".to_string()), |
| 666 | stop_sequence: None, |
| 667 | container: None, |
| 668 | title: None, |
| 669 | stop_details: None, |
| 670 | refusal: None, |
| 671 | usage, |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | fn admitted(replies: Arc<dyn Replies>, session: &str) -> (tempfile::TempDir, ToolContext) { |
| 676 | let workspace = tempfile::tempdir().unwrap(); |
| 677 | let context = context_for_replies( |
| 678 | &fixture_config(MODEL), |
| 679 | MODEL, |
| 680 | &ToolContext::new(workspace.path()), |
| 681 | replies, |
| 682 | ) |
| 683 | .with_session_objects(crate::rlm::session::SessionObjectSnapshot::new( |
| 684 | session.into(), |
| 685 | MODEL.into(), |
| 686 | workspace.path().to_path_buf(), |
| 687 | None, |
| 688 | Arc::new(Vec::new()), |
| 689 | )); |
| 690 | (workspace, context) |
| 691 | } |
| 692 | |
| 693 | async fn ask( |
| 694 | owner: &OwnerRef, |
| 695 | session: &str, |
| 696 | tool: &ToolContext, |
| 697 | cancel: &CancellationToken, |
| 698 | method: &str, |
| 699 | input: Value, |
| 700 | ) -> Result<Value, BrokerRefusal> { |
| 701 | let method = |
| 702 | serde_json::from_value::<LlmMethod>(json!({ "method": method, "input": input })) |
| 703 | .map_err(|error| invalid(&error.to_string()))?; |
| 704 | run(owner, session, tool, cancel, Gate::Stub, method).await |
| 705 | } |
| 706 | |
| 707 | fn code(result: &Result<Value, BrokerRefusal>) -> &'static str { |
| 708 | result.as_ref().expect_err("a refusal").code() |
| 709 | } |
| 710 | |
| 711 | #[tokio::test] |
| 712 | async fn a_completion_runs_on_the_session_route_and_reports_observed_usage() { |
| 713 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 714 | mock.push_message_response(reply( |
| 715 | "brokered answer", |
| 716 | Usage { |
| 717 | input_tokens: 7, |
| 718 | output_tokens: 11, |
| 719 | ..Usage::default() |
| 720 | }, |
| 721 | )); |
| 722 | mock.push_message_response(reply("answer without usage", Usage::default())); |
| 723 | let (_workspace, tool) = admitted(mock.clone(), "llm-usage-session"); |
| 724 | let owner = owner("llm-usage-plugin"); |
| 725 | let cancel = CancellationToken::new(); |
| 726 | |
| 727 | let catalog = ask( |
| 728 | &owner, |
| 729 | "llm-usage-session", |
| 730 | &tool, |
| 731 | &cancel, |
| 732 | "catalog", |
| 733 | json!({}), |
| 734 | ) |
| 735 | .await |
| 736 | .unwrap(); |
| 737 | assert_eq!(catalog["providers"][0]["id"], SESSION_PROVIDER); |
| 738 | assert_eq!(catalog["models"][0]["id"], MODEL); |
| 739 | assert_eq!(catalog["limits"].get("calls_per_session"), None); |
| 740 | assert!(!catalog.to_string().contains("owned-fixture-key")); |
| 741 | assert!(!catalog.to_string().contains("127.0.0.1")); |
| 742 | |
| 743 | let first = ask( |
| 744 | &owner, |
| 745 | "llm-usage-session", |
| 746 | &tool, |
| 747 | &cancel, |
| 748 | "complete", |
| 749 | json!({ |
| 750 | "prompt": "summarize this", |
| 751 | "system": "be brief", |
| 752 | "provider": SESSION_PROVIDER, |
| 753 | "model": MODEL, |
| 754 | "max_output_tokens": 1_000_000, |
| 755 | }), |
| 756 | ) |
| 757 | .await |
| 758 | .unwrap(); |
| 759 | assert_eq!(first["text"], "brokered answer"); |
| 760 | assert_eq!(first["finish"], "stop"); |
| 761 | assert_eq!(first["route"]["model"], MODEL); |
| 762 | assert!( |
| 763 | first["route"]["provider"] |
| 764 | .as_str() |
| 765 | .is_some_and(|id| !id.is_empty()) |
| 766 | ); |
| 767 | assert_eq!(first["usage"]["coverage"], "reported"); |
| 768 | assert_eq!(first["usage"]["input_tokens"], 7); |
| 769 | assert_eq!(first["usage"]["output_tokens"], 11); |
| 770 | assert_eq!(first["receipt"].get("call"), None); |
| 771 | assert_eq!(first["receipt"]["requests"], 1); |
| 772 | assert!(!first.to_string().contains("owned-fixture-key")); |
| 773 | assert!(!first.to_string().contains("127.0.0.1")); |
| 774 | |
| 775 | let requests = mock.captured_requests(); |
| 776 | assert_eq!(requests.len(), 1, "one real Engine dispatch"); |
| 777 | assert_eq!(requests[0].model, MODEL); |
| 778 | assert!((1..=MAX_OUTPUT_TOKENS).contains(&requests[0].max_tokens)); |
| 779 | assert!(requests[0].tools.as_ref().is_none_or(Vec::is_empty)); |
| 780 | let system = serde_json::to_string(&requests[0].system).unwrap(); |
| 781 | assert!(system.contains("be brief")); |
| 782 | assert!(!system.contains("subject to the captured Core policy")); |
| 783 | |
| 784 | let second = ask( |
| 785 | &owner, |
| 786 | "llm-usage-session", |
| 787 | &tool, |
| 788 | &cancel, |
| 789 | "complete", |
| 790 | json!({ "prompt": "again" }), |
| 791 | ) |
| 792 | .await |
| 793 | .unwrap(); |
| 794 | assert_eq!(second["text"], "answer without usage"); |
| 795 | assert_eq!(second["usage"]["coverage"], "missing"); |
| 796 | assert_eq!(second["usage"]["input_tokens"], Value::Null); |
| 797 | assert_eq!(second["usage"]["output_tokens"], Value::Null); |
| 798 | assert!((1..=DEFAULT_OUTPUT_TOKENS).contains(&mock.captured_requests()[1].max_tokens)); |
| 799 | assert_eq!(in_flight_count(&flight_key(&owner, "llm-usage-session")), 0); |
| 800 | } |
| 801 | |
| 802 | #[tokio::test] |
| 803 | async fn a_missing_route_a_denied_caller_and_bad_input_are_refused_before_any_dispatch() { |
| 804 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 805 | let (workspace, tool) = admitted(mock.clone(), "llm-refusal-session"); |
| 806 | let owner = owner("llm-refusal-plugin"); |
| 807 | let cancel = CancellationToken::new(); |
| 808 | let complete = |tool: ToolContext, cancel: CancellationToken, input: Value| { |
| 809 | let owner = owner.clone(); |
| 810 | async move { |
| 811 | ask( |
| 812 | &owner, |
| 813 | "llm-refusal-session", |
| 814 | &tool, |
| 815 | &cancel, |
| 816 | "complete", |
| 817 | input, |
| 818 | ) |
| 819 | .await |
| 820 | } |
| 821 | }; |
| 822 | |
| 823 | let bare = ToolContext::new(workspace.path()); |
| 824 | assert_eq!( |
| 825 | code( |
| 826 | &ask( |
| 827 | &owner, |
| 828 | "llm-refusal-session", |
| 829 | &bare, |
| 830 | &cancel, |
| 831 | "catalog", |
| 832 | json!({}) |
| 833 | ) |
| 834 | .await |
| 835 | ), |
| 836 | "not_available" |
| 837 | ); |
| 838 | assert_eq!( |
| 839 | code(&complete(bare, cancel.clone(), json!({ "prompt": "x" })).await), |
| 840 | "not_available" |
| 841 | ); |
| 842 | assert_eq!( |
| 843 | code( |
| 844 | &ask( |
| 845 | &owner, |
| 846 | "llm-refusal-session", |
| 847 | &tool, |
| 848 | &cancel, |
| 849 | "usage", |
| 850 | json!({}) |
| 851 | ) |
| 852 | .await |
| 853 | ), |
| 854 | "invalid_input" |
| 855 | ); |
| 856 | |
| 857 | let mut denied = tool.clone(); |
| 858 | denied.disallowed_tools = vec!["rlm".to_string()]; |
| 859 | let result = complete(denied, cancel.clone(), json!({ "prompt": "x" })).await; |
| 860 | assert_eq!(code(&result), "denied"); |
| 861 | |
| 862 | let mut moved = tool.clone(); |
| 863 | moved.state_namespace.push_str("-other"); |
| 864 | let result = complete(moved, cancel.clone(), json!({ "prompt": "x" })).await; |
| 865 | assert_eq!(code(&result), "refused"); |
| 866 | assert!(!result.unwrap_err().wire().message.contains("RLM")); |
| 867 | |
| 868 | for input in [ |
| 869 | json!({ "prompt": " " }), |
| 870 | json!({ "prompt": "x".repeat(MAX_PROMPT_BYTES + 1) }), |
| 871 | json!({ "prompt": "x", "system": "s".repeat(MAX_SYSTEM_BYTES + 1) }), |
| 872 | json!({ "prompt": "x", "max_output_tokens": 0 }), |
| 873 | json!({ "prompt": "x", "timeout_ms": 0 }), |
| 874 | json!({ "prompt": "x", "tools": [] }), |
| 875 | json!({ "prompt": "x", "api_key": "sk-own" }), |
| 876 | json!({ "messages": [] }), |
| 877 | ] { |
| 878 | assert_eq!( |
| 879 | code(&complete(tool.clone(), cancel.clone(), input).await), |
| 880 | "invalid_input" |
| 881 | ); |
| 882 | } |
| 883 | for input in [ |
| 884 | json!({ "prompt": "x", "model": "another-model" }), |
| 885 | json!({ "prompt": "x", "provider": "openai" }), |
| 886 | ] { |
| 887 | assert_eq!( |
| 888 | code(&complete(tool.clone(), cancel.clone(), input).await), |
| 889 | "refused" |
| 890 | ); |
| 891 | } |
| 892 | |
| 893 | let withdrawn = CancellationToken::new(); |
| 894 | withdrawn.cancel(); |
| 895 | assert_eq!( |
| 896 | code(&complete(tool.clone(), withdrawn, json!({ "prompt": "x" })).await), |
| 897 | "refused" |
| 898 | ); |
| 899 | |
| 900 | tool.cancel_token.as_ref().unwrap().cancel(); |
| 901 | assert_eq!( |
| 902 | code(&complete(tool.clone(), cancel.clone(), json!({ "prompt": "x" })).await), |
| 903 | "refused" |
| 904 | ); |
| 905 | |
| 906 | assert_eq!(mock.call_count(), 0, "nothing reached the provider"); |
| 907 | assert_eq!( |
| 908 | in_flight_count(&flight_key(&owner, "llm-refusal-session")), |
| 909 | 0 |
| 910 | ); |
| 911 | } |
| 912 | |
| 913 | #[tokio::test] |
| 914 | async fn a_sub_agent_saved_without_the_model_action_gets_no_completion() { |
| 915 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 916 | mock.push_message_response(reply("allowed child reply", Usage::default())); |
| 917 | let (workspace, tool) = admitted(mock.clone(), "llm-child-session"); |
| 918 | let owner = owner("llm-child-plugin"); |
| 919 | let cancel = CancellationToken::new(); |
| 920 | let client = CodewhaleClient::new( |
| 921 | &Config::default().with_legacy_root(Some("test-key".to_string()), None), |
| 922 | ) |
| 923 | .expect("stub client"); |
| 924 | let manager = new_shared_subagent_manager(workspace.path().to_path_buf(), 4); |
| 925 | |
| 926 | let mut blocked_runtime = SubAgentRuntime::new( |
| 927 | client.clone(), |
| 928 | MODEL.to_string(), |
| 929 | tool.clone(), |
| 930 | false, |
| 931 | None, |
| 932 | manager.clone(), |
| 933 | ); |
| 934 | blocked_runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Builder); |
| 935 | blocked_runtime.worker_profile.denied_tools = |
| 936 | vec!["rlm_open".to_string(), "rlm_eval".to_string()]; |
| 937 | let blocked_child = ChildAuthority::capture( |
| 938 | blocked_runtime, |
| 939 | FleetRole::Builder, |
| 940 | "agent_child".into(), |
| 941 | "child".into(), |
| 942 | None, |
| 943 | ); |
| 944 | let mut blocked_tool = tool.clone(); |
| 945 | blocked_tool.child_host = Some(blocked_child); |
| 946 | let denied = ask( |
| 947 | &owner, |
| 948 | "llm-child-session", |
| 949 | &blocked_tool, |
| 950 | &cancel, |
| 951 | "complete", |
| 952 | json!({ "prompt": "blocked child" }), |
| 953 | ) |
| 954 | .await; |
| 955 | assert_eq!(code(&denied), "denied"); |
| 956 | assert_eq!(mock.call_count(), 0); |
| 957 | |
| 958 | let mut allowed_runtime = SubAgentRuntime::new( |
| 959 | client, |
| 960 | MODEL.to_string(), |
| 961 | tool.clone(), |
| 962 | false, |
| 963 | None, |
| 964 | manager, |
| 965 | ); |
| 966 | allowed_runtime.worker_profile = WorkerRuntimeProfile::for_role(FleetRole::Builder); |
| 967 | let allowed_child = ChildAuthority::capture( |
| 968 | allowed_runtime, |
| 969 | FleetRole::Builder, |
| 970 | "agent_child_ok".into(), |
| 971 | "child".into(), |
| 972 | None, |
| 973 | ); |
| 974 | let mut allowed_tool = tool; |
| 975 | allowed_tool.child_host = Some(allowed_child); |
| 976 | let served = ask( |
| 977 | &owner, |
| 978 | "llm-child-session", |
| 979 | &allowed_tool, |
| 980 | &cancel, |
| 981 | "complete", |
| 982 | json!({ "prompt": "allowed child" }), |
| 983 | ) |
| 984 | .await |
| 985 | .unwrap(); |
| 986 | assert_eq!(served["text"], "allowed child reply"); |
| 987 | assert_eq!(mock.call_count(), 1); |
| 988 | } |
| 989 | |
| 990 | #[tokio::test] |
| 991 | async fn a_session_deny_list_naming_the_model_action_refuses_a_completion() { |
| 992 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 993 | mock.push_message_response(reply("unrelated deny passes", Usage::default())); |
| 994 | let (_workspace, tool) = admitted(mock.clone(), "llm-deny-action-session"); |
| 995 | let owner = owner("llm-deny-action-plugin"); |
| 996 | let cancel = CancellationToken::new(); |
| 997 | |
| 998 | for rule in ["rlm_eval", "rlm", "rlm*", "Bash"] { |
| 999 | let mut denied = tool.clone(); |
| 1000 | denied.disallowed_tools = vec![rule.to_string()]; |
| 1001 | let result = ask( |
| 1002 | &owner, |
| 1003 | "llm-deny-action-session", |
| 1004 | &denied, |
| 1005 | &cancel, |
| 1006 | "complete", |
| 1007 | json!({ "prompt": "must refuse" }), |
| 1008 | ) |
| 1009 | .await; |
| 1010 | assert_eq!(code(&result), "denied", "deny rule {rule}"); |
| 1011 | } |
| 1012 | assert_eq!(mock.call_count(), 0); |
| 1013 | |
| 1014 | let mut unrelated = tool; |
| 1015 | unrelated.disallowed_tools = vec!["read_file".to_string()]; |
| 1016 | let served = ask( |
| 1017 | &owner, |
| 1018 | "llm-deny-action-session", |
| 1019 | &unrelated, |
| 1020 | &cancel, |
| 1021 | "complete", |
| 1022 | json!({ "prompt": "allowed" }), |
| 1023 | ) |
| 1024 | .await |
| 1025 | .unwrap(); |
| 1026 | assert_eq!(served["text"], "unrelated deny passes"); |
| 1027 | assert_eq!(mock.call_count(), 1); |
| 1028 | } |
| 1029 | |
| 1030 | struct Pending(tokio::sync::Notify); |
| 1031 | |
| 1032 | impl Replies for Pending { |
| 1033 | fn effective_route_envelope( |
| 1034 | &self, |
| 1035 | model: &str, |
| 1036 | at: chrono::DateTime<chrono::Utc>, |
| 1037 | ) -> crate::cost_status::EffectiveRouteEnvelope { |
| 1038 | crate::cost_status::EffectiveRouteEnvelope::capture_observed( |
| 1039 | codewhale_config::ProviderKind::Custom, |
| 1040 | "rlm-fixture", |
| 1041 | model, |
| 1042 | Some("http://127.0.0.1:9/v1"), |
| 1043 | at, |
| 1044 | ) |
| 1045 | } |
| 1046 | |
| 1047 | fn effective_max_output_tokens(&self, _: &str) -> u32 { |
| 1048 | 8192 |
| 1049 | } |
| 1050 | |
| 1051 | fn create_message_boxed( |
| 1052 | &self, |
| 1053 | _: MessageRequest, |
| 1054 | ) -> Pin<Box<dyn Future<Output = anyhow::Result<MessageResponse>> + Send + '_>> { |
| 1055 | Box::pin(async move { |
| 1056 | self.0.notify_one(); |
| 1057 | std::future::pending().await |
| 1058 | }) |
| 1059 | } |
| 1060 | } |
| 1061 | |
| 1062 | #[tokio::test] |
| 1063 | async fn cancellation_a_deadline_and_the_concurrency_cap_end_calls_with_a_terminal_receipt() { |
| 1064 | let pending = Arc::new(Pending(tokio::sync::Notify::new())); |
| 1065 | let (_workspace, tool) = admitted(pending.clone(), "llm-cancel-session"); |
| 1066 | let owner = owner("llm-cancel-plugin"); |
| 1067 | let key = flight_key(&owner, "llm-cancel-session"); |
| 1068 | |
| 1069 | let never = CancellationToken::new(); |
| 1070 | let timed_out = ask( |
| 1071 | &owner, |
| 1072 | "llm-cancel-session", |
| 1073 | &tool, |
| 1074 | &never, |
| 1075 | "complete", |
| 1076 | json!({ "prompt": "slow", "timeout_ms": 150 }), |
| 1077 | ) |
| 1078 | .await; |
| 1079 | assert_eq!(code(&timed_out), "refused"); |
| 1080 | assert_eq!( |
| 1081 | timed_out.unwrap_err().wire().message, |
| 1082 | "the model call ran out of time" |
| 1083 | ); |
| 1084 | assert_eq!(in_flight_count(&key), 0); |
| 1085 | |
| 1086 | let cancel = CancellationToken::new(); |
| 1087 | let (cancelled, ()) = tokio::join!( |
| 1088 | ask( |
| 1089 | &owner, |
| 1090 | "llm-cancel-session", |
| 1091 | &tool, |
| 1092 | &cancel, |
| 1093 | "complete", |
| 1094 | json!({ "prompt": "slow" }), |
| 1095 | ), |
| 1096 | async { |
| 1097 | pending.0.notified().await; |
| 1098 | cancel.cancel(); |
| 1099 | } |
| 1100 | ); |
| 1101 | assert_eq!(code(&cancelled), "refused"); |
| 1102 | assert_eq!( |
| 1103 | cancelled.unwrap_err().wire().message, |
| 1104 | "the model call was cancelled" |
| 1105 | ); |
| 1106 | assert_eq!(in_flight_count(&key), 0); |
| 1107 | |
| 1108 | let hold = CancellationToken::new(); |
| 1109 | let running: Vec<_> = (0..MAX_IN_FLIGHT) |
| 1110 | .map(|_| { |
| 1111 | let (owner, tool, hold) = (owner.clone(), tool.clone(), hold.clone()); |
| 1112 | tokio::spawn(async move { |
| 1113 | ask( |
| 1114 | &owner, |
| 1115 | "llm-cancel-session", |
| 1116 | &tool, |
| 1117 | &hold, |
| 1118 | "complete", |
| 1119 | json!({ "prompt": "slow" }), |
| 1120 | ) |
| 1121 | .await |
| 1122 | }) |
| 1123 | }) |
| 1124 | .collect(); |
| 1125 | for _ in 0..200 { |
| 1126 | if in_flight_count(&key) == MAX_IN_FLIGHT { |
| 1127 | break; |
| 1128 | } |
| 1129 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 1130 | } |
| 1131 | assert_eq!(in_flight_count(&key), MAX_IN_FLIGHT); |
| 1132 | let over = ask( |
| 1133 | &owner, |
| 1134 | "llm-cancel-session", |
| 1135 | &tool, |
| 1136 | &never, |
| 1137 | "complete", |
| 1138 | json!({ "prompt": "one too many" }), |
| 1139 | ) |
| 1140 | .await; |
| 1141 | assert_eq!(code(&over), "refused"); |
| 1142 | running[0].abort(); |
| 1143 | hold.cancel(); |
| 1144 | for task in running { |
| 1145 | let _ = task.await; |
| 1146 | } |
| 1147 | assert_eq!( |
| 1148 | in_flight_count(&key), |
| 1149 | 0, |
| 1150 | "dropped and cancelled calls leave no in-flight row" |
| 1151 | ); |
| 1152 | } |
| 1153 | |
| 1154 | #[test] |
| 1155 | fn in_flight_rows_exist_only_while_a_call_runs_and_a_full_table_refuses() { |
| 1156 | let mut table = HashMap::new(); |
| 1157 | let owner_gen1 = owner("llm-bound-plugin"); |
| 1158 | let mut owner_gen2 = owner("llm-bound-plugin"); |
| 1159 | owner_gen2.generation = 99; |
| 1160 | let k1 = flight_key(&owner_gen1, "s0"); |
| 1161 | let k2 = flight_key(&owner_gen2, "s0"); |
| 1162 | assert_eq!(k1, k2, "generation changes share one plugin/session key"); |
| 1163 | |
| 1164 | reserve(&mut table, &k1).unwrap(); |
| 1165 | reserve(&mut table, &k2).unwrap(); |
| 1166 | assert_eq!(table.len(), 1); |
| 1167 | assert_eq!(table[&k1], MAX_IN_FLIGHT); |
| 1168 | assert_eq!(reserve(&mut table, &k2).unwrap_err().code(), "refused"); |
| 1169 | |
| 1170 | release(&mut table, &k1); |
| 1171 | assert_eq!(table[&k1], 1); |
| 1172 | release(&mut table, &k2); |
| 1173 | assert!(table.is_empty(), "finished calls leave no row behind"); |
| 1174 | |
| 1175 | for index in 0..MAX_IN_FLIGHT_ROWS { |
| 1176 | let key = (format!("plugin-{index}"), "s".to_string()); |
| 1177 | reserve(&mut table, &key).unwrap(); |
| 1178 | } |
| 1179 | assert_eq!(table.len(), MAX_IN_FLIGHT_ROWS); |
| 1180 | let extra = ("plugin-overflow".to_string(), "s".to_string()); |
| 1181 | assert_eq!(reserve(&mut table, &extra).unwrap_err().code(), "refused"); |
| 1182 | assert_eq!(table.len(), MAX_IN_FLIGHT_ROWS); |
| 1183 | assert!(!table.contains_key(&extra)); |
| 1184 | let existing = ("plugin-0".to_string(), "s".to_string()); |
| 1185 | assert!(table.contains_key(&existing), "live row was not evicted"); |
| 1186 | } |
| 1187 | } |
| 1188 |