| 1 | //! RPC bridge that services `llm_query` / `rlm_query` calls coming back |
| 2 | //! from the long-lived Python REPL during an RLM turn. |
| 3 | //! |
| 4 | //! This is the spiritual successor to the HTTP sidecar from earlier |
| 5 | //! versions — except instead of binding a localhost port and routing |
| 6 | //! through `urllib`, requests come in through stdin/stdout and we just |
| 7 | //! submit an admitted call to the canonical Engine. |
| 8 | //! |
| 9 | //! The bridge tracks cumulative token usage and the recursion budget. For |
| 10 | //! `Rlm` / `RlmBatch` requests it submits an admitted Core turn at depth-1. |
| 11 | //! Python and its persistent session never retain this borrowed dispatcher. |
| 12 | |
| 13 | use codewhale_models::Usage; |
| 14 | use codewhale_repl::runtime::{BatchResp, RpcDispatcher, RpcRequest, RpcResponse, SingleResp}; |
| 15 | use futures_util::future::join_all; |
| 16 | use std::sync::Arc; |
| 17 | use std::sync::Mutex; |
| 18 | #[cfg(test)] |
| 19 | use std::time::Duration; |
| 20 | use uuid::Uuid; |
| 21 | |
| 22 | pub const MAX_BATCH: usize = 16; |
| 23 | |
| 24 | /// One pre-dispatch reservation in the shared routed-usage ledger. |
| 25 | #[derive(Debug, Clone, Copy)] |
| 26 | pub struct RlmUsageReservation { |
| 27 | index: usize, |
| 28 | } |
| 29 | |
| 30 | #[derive(Debug, Default)] |
| 31 | struct RlmUsageState { |
| 32 | ledger_id: String, |
| 33 | usage: Usage, |
| 34 | records: Vec<Option<RlmUsageSlot>>, |
| 35 | drop_records: Vec<crate::cost_status::RuntimeUsageDropRecord>, |
| 36 | dropped_records: u64, |
| 37 | nested_events: Vec<serde_json::Value>, |
| 38 | nested_runs: usize, |
| 39 | } |
| 40 | |
| 41 | #[derive(Debug)] |
| 42 | struct RlmUsageSlot { |
| 43 | record: crate::cost_status::RuntimeUsageRecord, |
| 44 | completed: bool, |
| 45 | } |
| 46 | |
| 47 | /// Shared, bounded provider-call ledger for one complete RLM tree. |
| 48 | /// |
| 49 | /// Every root, child, batch member, and recursive call reserves one slot |
| 50 | /// before invoking a provider. A distinct call is never coalesced merely |
| 51 | /// because it used the same route: its dispatch instant and frozen quote are |
| 52 | /// independent accounting evidence. Sharing one accumulator across recursion |
| 53 | /// makes the bound global instead of allowing every nested bridge to reset it. |
| 54 | #[derive(Debug, Clone)] |
| 55 | pub struct RlmUsageAccumulator { |
| 56 | state: Arc<Mutex<RlmUsageState>>, |
| 57 | } |
| 58 | |
| 59 | /// Atomic snapshot returned after all RPC work for a round has settled. |
| 60 | #[derive(Debug, Clone, Default)] |
| 61 | pub struct RlmUsageSnapshot { |
| 62 | pub usage: Usage, |
| 63 | pub records: Vec<crate::cost_status::RuntimeUsageRecord>, |
| 64 | /// Exact frozen routes for provider-success responses that did not carry |
| 65 | /// authoritative usage. Keeping these separate prevents a missing payload |
| 66 | /// from becoming a priced zero-usage receipt. |
| 67 | pub drop_records: Vec<crate::cost_status::RuntimeUsageDropRecord>, |
| 68 | /// Calls whose execution/usage became ambiguous (for example a timeout). |
| 69 | /// They are never represented as authoritative zero-usage responses. |
| 70 | pub dropped_records: u64, |
| 71 | /// Producer-owned nested loop events, retained in the enclosing tool body |
| 72 | /// so every session host persists them through its existing result path. |
| 73 | pub nested_events: Vec<serde_json::Value>, |
| 74 | } |
| 75 | |
| 76 | impl RlmUsageAccumulator { |
| 77 | #[must_use] |
| 78 | pub(crate) fn new() -> Self { |
| 79 | Self { |
| 80 | state: Arc::new(Mutex::new(RlmUsageState { |
| 81 | ledger_id: Uuid::new_v4().simple().to_string(), |
| 82 | ..RlmUsageState::default() |
| 83 | })), |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Reserve durable accounting capacity before a provider request. |
| 88 | /// Definite transport failure cancels the slot; ambiguous cancellation is |
| 89 | /// explicit incomplete coverage. Reaching the cap rejects before any |
| 90 | /// unreceipted provider work can occur. |
| 91 | pub async fn reserve( |
| 92 | &self, |
| 93 | route: crate::cost_status::EffectiveRouteEnvelope, |
| 94 | ) -> std::result::Result<RlmUsageReservation, String> { |
| 95 | let mut state = self |
| 96 | .state |
| 97 | .lock() |
| 98 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 99 | if state.records.len() == crate::cost_status::MAX_CHILD_USAGE_RECORDS { |
| 100 | return Err(format!( |
| 101 | "RLM provider-call receipt limit reached ({}); request rejected before dispatch", |
| 102 | crate::cost_status::MAX_CHILD_USAGE_RECORDS |
| 103 | )); |
| 104 | } |
| 105 | let index = state.records.len(); |
| 106 | let source_id = format!("rlm:{}:request:{index}", state.ledger_id); |
| 107 | state.records.push(Some(RlmUsageSlot { |
| 108 | record: crate::cost_status::RuntimeUsageRecord::legacy( |
| 109 | source_id, |
| 110 | crate::cost_status::EffectiveRouteUsage { |
| 111 | route: route.sanitized_for_persistence(), |
| 112 | usage: Usage::default(), |
| 113 | }, |
| 114 | ), |
| 115 | completed: false, |
| 116 | })); |
| 117 | Ok(RlmUsageReservation { index }) |
| 118 | } |
| 119 | |
| 120 | pub async fn source_id(&self, reservation: RlmUsageReservation) -> Option<String> { |
| 121 | self.state |
| 122 | .lock() |
| 123 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 124 | .records |
| 125 | .get(reservation.index) |
| 126 | .and_then(Option::as_ref) |
| 127 | .map(|slot| slot.record.source_id.clone()) |
| 128 | } |
| 129 | |
| 130 | /// Attach a provider's reported usage to its already-reserved exact route. |
| 131 | pub async fn complete_record( |
| 132 | &self, |
| 133 | reservation: RlmUsageReservation, |
| 134 | record: &crate::cost_status::RuntimeUsageRecord, |
| 135 | ) { |
| 136 | self.complete_record_sync(reservation, record); |
| 137 | } |
| 138 | |
| 139 | pub fn complete_record_sync( |
| 140 | &self, |
| 141 | reservation: RlmUsageReservation, |
| 142 | record: &crate::cost_status::RuntimeUsageRecord, |
| 143 | ) { |
| 144 | let mut state = self |
| 145 | .state |
| 146 | .lock() |
| 147 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 148 | let Some(Some(slot)) = state.records.get_mut(reservation.index) else { |
| 149 | return; |
| 150 | }; |
| 151 | if crate::cost_status::usage_source_fingerprint(&slot.record.source_id) |
| 152 | != crate::cost_status::usage_source_fingerprint(&record.source_id) |
| 153 | || slot.record.usage.route != record.usage.route |
| 154 | { |
| 155 | return; |
| 156 | } |
| 157 | if !record.supersedes(slot.completed.then_some(&slot.record)) { |
| 158 | return; |
| 159 | } |
| 160 | slot.record = record.clone(); |
| 161 | slot.completed = true; |
| 162 | let mut usage = Usage::default(); |
| 163 | for slot in state.records.iter().flatten().filter(|slot| slot.completed) { |
| 164 | crate::core::turn::add_usage_to(&mut usage, &slot.record.usage.usage); |
| 165 | } |
| 166 | state.usage = usage; |
| 167 | } |
| 168 | |
| 169 | #[cfg(any(test, feature = "test-support"))] |
| 170 | pub async fn complete(&self, reservation: RlmUsageReservation, usage: &Usage) { |
| 171 | let mut state = self |
| 172 | .state |
| 173 | .lock() |
| 174 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 175 | let completed = if let Some(Some(slot)) = state.records.get_mut(reservation.index) |
| 176 | && !slot.completed |
| 177 | { |
| 178 | crate::core::turn::add_usage_to(&mut slot.record.usage.usage, usage); |
| 179 | slot.completed = true; |
| 180 | true |
| 181 | } else { |
| 182 | false |
| 183 | }; |
| 184 | if completed { |
| 185 | crate::core::turn::add_usage_to(&mut state.usage, usage); |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// Remove a reservation that never produced provider-reported usage. |
| 190 | /// Ambiguous execution increments explicit incomplete coverage instead of |
| 191 | /// being persisted as a priced-zero response. |
| 192 | #[cfg(any(test, feature = "test-support"))] |
| 193 | pub async fn cancel(&self, reservation: RlmUsageReservation, coverage_unknown: bool) { |
| 194 | self.cancel_sync( |
| 195 | reservation, |
| 196 | coverage_unknown, |
| 197 | crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 198 | ); |
| 199 | } |
| 200 | |
| 201 | pub fn cancel_sync( |
| 202 | &self, |
| 203 | reservation: RlmUsageReservation, |
| 204 | coverage_unknown: bool, |
| 205 | reason: crate::cost_status::RuntimeUsageMissingReason, |
| 206 | ) { |
| 207 | let mut state = self |
| 208 | .state |
| 209 | .lock() |
| 210 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 211 | let cancelled = state.records.get_mut(reservation.index).and_then(|slot| { |
| 212 | if slot.as_ref().is_some_and(|slot| !slot.completed) { |
| 213 | slot.take() |
| 214 | } else { |
| 215 | None |
| 216 | } |
| 217 | }); |
| 218 | if let Some(slot) = cancelled |
| 219 | && coverage_unknown |
| 220 | { |
| 221 | state |
| 222 | .drop_records |
| 223 | .push(crate::cost_status::RuntimeUsageDropRecord { |
| 224 | reason, |
| 225 | source_id: slot.record.source_id, |
| 226 | route: slot.record.usage.route, |
| 227 | }); |
| 228 | state.dropped_records = state.dropped_records.saturating_add(1); |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | /// Bound even nested runs that fail before their first provider request. |
| 233 | /// Without this reservation repeated setup failures could grow event |
| 234 | /// receipts while never consuming the existing provider-call bound. |
| 235 | pub async fn reserve_nested_turn(&self) -> std::result::Result<(), String> { |
| 236 | let mut state = self |
| 237 | .state |
| 238 | .lock() |
| 239 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 240 | if state.nested_runs == crate::cost_status::MAX_CHILD_USAGE_RECORDS { |
| 241 | return Err("RLM nested-turn receipt limit reached before dispatch".into()); |
| 242 | } |
| 243 | state.nested_runs += 1; |
| 244 | Ok(()) |
| 245 | } |
| 246 | |
| 247 | pub async fn record_nested_event(&self, event: serde_json::Value) { |
| 248 | self.state |
| 249 | .lock() |
| 250 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 251 | .nested_events |
| 252 | .push(event); |
| 253 | } |
| 254 | |
| 255 | pub async fn snapshot(&self) -> RlmUsageSnapshot { |
| 256 | let state = self |
| 257 | .state |
| 258 | .lock() |
| 259 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 260 | let pending = state |
| 261 | .records |
| 262 | .iter() |
| 263 | .flatten() |
| 264 | .filter(|slot| !slot.completed) |
| 265 | .map(|slot| crate::cost_status::RuntimeUsageDropRecord { |
| 266 | reason: crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown, |
| 267 | source_id: slot.record.source_id.clone(), |
| 268 | route: slot.record.usage.route.clone(), |
| 269 | }) |
| 270 | .collect::<Vec<_>>(); |
| 271 | let mut drop_records = state.drop_records.clone(); |
| 272 | drop_records.extend(pending.iter().cloned()); |
| 273 | RlmUsageSnapshot { |
| 274 | nested_events: state.nested_events.clone(), |
| 275 | usage: state.usage.clone(), |
| 276 | records: state |
| 277 | .records |
| 278 | .iter() |
| 279 | .flatten() |
| 280 | .filter(|slot| slot.completed) |
| 281 | .map(|slot| slot.record.clone()) |
| 282 | .collect(), |
| 283 | drop_records, |
| 284 | dropped_records: state |
| 285 | .dropped_records |
| 286 | .saturating_add(u64::try_from(pending.len()).unwrap_or(u64::MAX)), |
| 287 | } |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | pub async fn wait_for_deadline(deadline: Option<tokio::time::Instant>) { |
| 292 | match deadline { |
| 293 | Some(deadline) => tokio::time::sleep_until(deadline).await, |
| 294 | None => std::future::pending::<()>().await, |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | /// A dispatcher borrowed by one Python round. Persistent kernels never own |
| 299 | /// this caller, its services or an Engine. All nested work ends with this borrow. |
| 300 | pub struct RlmBridge<'call> { |
| 301 | caller: &'call crate::core::engine::rlm_host::CapturedRlmCaller, |
| 302 | depth_remaining: u32, |
| 303 | usage: RlmUsageAccumulator, |
| 304 | events: Option<tokio::sync::mpsc::Sender<crate::core::events::Event>>, |
| 305 | deadline: Option<tokio::time::Instant>, |
| 306 | gate: Option<crate::tools::codemode::NestedCallGate>, |
| 307 | } |
| 308 | |
| 309 | impl<'call> RlmBridge<'call> { |
| 310 | pub fn new( |
| 311 | caller: &'call crate::core::engine::rlm_host::CapturedRlmCaller, |
| 312 | depth_remaining: u32, |
| 313 | ) -> Self { |
| 314 | Self::with_usage_accumulator(caller, depth_remaining, RlmUsageAccumulator::new()) |
| 315 | } |
| 316 | |
| 317 | pub fn with_usage_accumulator( |
| 318 | caller: &'call crate::core::engine::rlm_host::CapturedRlmCaller, |
| 319 | depth_remaining: u32, |
| 320 | usage: RlmUsageAccumulator, |
| 321 | ) -> Self { |
| 322 | Self { |
| 323 | caller, |
| 324 | depth_remaining, |
| 325 | usage, |
| 326 | events: None, |
| 327 | deadline: caller.deadline(), |
| 328 | gate: None, |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | pub fn with_gate(mut self, gate: Option<crate::tools::codemode::NestedCallGate>) -> Self { |
| 333 | self.gate = gate; |
| 334 | self |
| 335 | } |
| 336 | |
| 337 | pub fn with_deadline(mut self, deadline: Option<tokio::time::Instant>) -> Self { |
| 338 | self.deadline = self.deadline.into_iter().chain(deadline).min(); |
| 339 | self |
| 340 | } |
| 341 | |
| 342 | pub fn deadline(&self) -> Option<tokio::time::Instant> { |
| 343 | self.deadline |
| 344 | } |
| 345 | |
| 346 | pub fn with_events( |
| 347 | mut self, |
| 348 | events: tokio::sync::mpsc::Sender<crate::core::events::Event>, |
| 349 | ) -> Self { |
| 350 | self.events = Some(events); |
| 351 | self |
| 352 | } |
| 353 | |
| 354 | pub async fn usage_snapshot(&self) -> RlmUsageSnapshot { |
| 355 | self.usage.snapshot().await |
| 356 | } |
| 357 | |
| 358 | async fn invoke( |
| 359 | &self, |
| 360 | prompt: String, |
| 361 | mode: crate::core::engine::rlm_host::RlmMode, |
| 362 | max_tokens: Option<u32>, |
| 363 | system: Option<String>, |
| 364 | ) -> SingleResp { |
| 365 | let result = self |
| 366 | .caller |
| 367 | .dispatch(crate::core::engine::rlm_host::RlmInvocation { |
| 368 | prompt, |
| 369 | mode, |
| 370 | prompt_policy: crate::core::engine::rlm_host::RlmPromptPolicy::Session, |
| 371 | max_tokens, |
| 372 | task_instructions: system, |
| 373 | deadline: self.deadline, |
| 374 | gate: self.gate.clone(), |
| 375 | events: self.events.clone(), |
| 376 | usage: self.usage.clone(), |
| 377 | }) |
| 378 | .await; |
| 379 | SingleResp { |
| 380 | text: result.answer, |
| 381 | error: result.error, |
| 382 | } |
| 383 | } |
| 384 | |
| 385 | async fn dispatch_llm( |
| 386 | &self, |
| 387 | prompt: String, |
| 388 | _model: Option<String>, |
| 389 | max_tokens: Option<u32>, |
| 390 | system: Option<String>, |
| 391 | ) -> SingleResp { |
| 392 | self.invoke( |
| 393 | prompt, |
| 394 | crate::core::engine::rlm_host::RlmMode::Completion, |
| 395 | max_tokens, |
| 396 | system, |
| 397 | ) |
| 398 | .await |
| 399 | } |
| 400 | |
| 401 | async fn dispatch_llm_batch( |
| 402 | &self, |
| 403 | prompts: Vec<String>, |
| 404 | _model: Option<String>, |
| 405 | dependency_mode: Option<String>, |
| 406 | ) -> RpcResponse { |
| 407 | if let Some(resp) = batch_guard(prompts.len(), dependency_mode.as_deref()) { |
| 408 | return resp; |
| 409 | } |
| 410 | RpcResponse::Batch(BatchResp { |
| 411 | results: join_all( |
| 412 | prompts |
| 413 | .into_iter() |
| 414 | .map(|prompt| self.dispatch_llm(prompt, None, None, None)), |
| 415 | ) |
| 416 | .await, |
| 417 | }) |
| 418 | } |
| 419 | |
| 420 | pub async fn dispatch_rlm(&self, prompt: String, _model: Option<String>) -> SingleResp { |
| 421 | if self.depth_remaining == 0 { |
| 422 | return self.dispatch_llm(prompt, None, None, None).await; |
| 423 | } |
| 424 | self.invoke( |
| 425 | prompt, |
| 426 | crate::core::engine::rlm_host::RlmMode::Recursive { |
| 427 | depth_remaining: self.depth_remaining.saturating_sub(1), |
| 428 | }, |
| 429 | None, |
| 430 | None, |
| 431 | ) |
| 432 | .await |
| 433 | } |
| 434 | |
| 435 | async fn dispatch_rlm_batch( |
| 436 | &self, |
| 437 | prompts: Vec<String>, |
| 438 | _model: Option<String>, |
| 439 | dependency_mode: Option<String>, |
| 440 | ) -> RpcResponse { |
| 441 | if let Some(resp) = batch_guard(prompts.len(), dependency_mode.as_deref()) { |
| 442 | return resp; |
| 443 | } |
| 444 | RpcResponse::Batch(BatchResp { |
| 445 | results: join_all( |
| 446 | prompts |
| 447 | .into_iter() |
| 448 | .map(|prompt| self.dispatch_rlm(prompt, None)), |
| 449 | ) |
| 450 | .await, |
| 451 | }) |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | /// One nested sub-RLM event as a parent-stream status line, or `None` for an |
| 456 | /// event kind the nested loop does not produce. |
| 457 | pub fn nested_rlm_status_line(event: crate::core::events::Event, depth: u32) -> Option<String> { |
| 458 | use crate::core::events::Event; |
| 459 | let body = match event { |
| 460 | Event::Status { message } => message, |
| 461 | Event::MessageDelta { content, .. } => content.trim().to_string(), |
| 462 | _ => return None, |
| 463 | }; |
| 464 | Some(format!("{NESTED_RLM_STATUS_PREFIX}{depth}): {body}")) |
| 465 | } |
| 466 | |
| 467 | /// Status-line prefix for forwarded nested sub-RLM events; |
| 468 | /// `core::events::status_visibility` classifies these as internal receipts. |
| 469 | pub const NESTED_RLM_STATUS_PREFIX: &str = "sub-RLM (depth "; |
| 470 | |
| 471 | fn batch_guard(prompt_count: usize, dependency_mode: Option<&str>) -> Option<RpcResponse> { |
| 472 | if prompt_count == 0 { |
| 473 | return Some(RpcResponse::Batch(BatchResp { results: vec![] })); |
| 474 | } |
| 475 | if prompt_count > MAX_BATCH { |
| 476 | return Some(RpcResponse::Single(SingleResp { |
| 477 | text: String::new(), |
| 478 | error: Some(format!("batch too large: {prompt_count} > {MAX_BATCH}")), |
| 479 | })); |
| 480 | } |
| 481 | let mode = dependency_mode |
| 482 | .unwrap_or_default() |
| 483 | .trim() |
| 484 | .to_ascii_lowercase() |
| 485 | .replace(['-', ' '], "_"); |
| 486 | if !matches!( |
| 487 | mode.as_str(), |
| 488 | "independent" | "parallel_safe" | "map_reduce" |
| 489 | ) { |
| 490 | return Some(RpcResponse::Single(SingleResp { |
| 491 | text: String::new(), |
| 492 | error: Some( |
| 493 | "batch requires dependency_mode='independent'; use sub_query_sequence or sequential sub_query calls for dependent work" |
| 494 | .to_string(), |
| 495 | ), |
| 496 | })); |
| 497 | } |
| 498 | None |
| 499 | } |
| 500 | |
| 501 | impl RpcDispatcher for RlmBridge<'_> { |
| 502 | fn dispatch<'a>( |
| 503 | &'a self, |
| 504 | req: RpcRequest, |
| 505 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = RpcResponse> + Send + 'a>> { |
| 506 | Box::pin(async move { |
| 507 | match req { |
| 508 | RpcRequest::Llm { |
| 509 | prompt, |
| 510 | model, |
| 511 | max_tokens, |
| 512 | system, |
| 513 | } => { |
| 514 | RpcResponse::Single(self.dispatch_llm(prompt, model, max_tokens, system).await) |
| 515 | } |
| 516 | RpcRequest::LlmBatch { |
| 517 | prompts, |
| 518 | model, |
| 519 | dependency_mode, |
| 520 | safety_note: _, |
| 521 | } => { |
| 522 | self.dispatch_llm_batch(prompts, model, dependency_mode) |
| 523 | .await |
| 524 | } |
| 525 | RpcRequest::Rlm { prompt, model } => { |
| 526 | RpcResponse::Single(self.dispatch_rlm(prompt, model).await) |
| 527 | } |
| 528 | RpcRequest::RlmBatch { |
| 529 | prompts, |
| 530 | model, |
| 531 | dependency_mode, |
| 532 | safety_note: _, |
| 533 | } => { |
| 534 | self.dispatch_rlm_batch(prompts, model, dependency_mode) |
| 535 | .await |
| 536 | } |
| 537 | } |
| 538 | }) |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | #[cfg(test)] |
| 543 | mod tests { |
| 544 | use super::*; |
| 545 | use crate::core::engine::tests::rlm_host::{BridgeFixture, Replies}; |
| 546 | use crate::llm_client::mock::MockLlmClient; |
| 547 | use anyhow::Result; |
| 548 | use codewhale_models::{ContentBlock, MessageRequest, MessageResponse}; |
| 549 | use std::future::Future; |
| 550 | use std::pin::Pin; |
| 551 | |
| 552 | fn mock_response_with_usage(text: &str, usage: Usage) -> MessageResponse { |
| 553 | MessageResponse { |
| 554 | tool_projection_warning: None, |
| 555 | id: "mock_msg".to_string(), |
| 556 | r#type: "message".to_string(), |
| 557 | role: "assistant".to_string(), |
| 558 | content: vec![ContentBlock::Text { |
| 559 | text: text.to_string(), |
| 560 | cache_control: None, |
| 561 | }], |
| 562 | model: "mock-model".to_string(), |
| 563 | stop_reason: Some("end_turn".to_string()), |
| 564 | stop_sequence: None, |
| 565 | container: None, |
| 566 | usage, |
| 567 | title: None, |
| 568 | stop_details: None, |
| 569 | refusal: None, |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | fn mock_response(text: &str, input_tokens: u32, output_tokens: u32) -> MessageResponse { |
| 574 | mock_response_with_usage( |
| 575 | text, |
| 576 | Usage { |
| 577 | input_tokens, |
| 578 | output_tokens, |
| 579 | ..Usage::default() |
| 580 | }, |
| 581 | ) |
| 582 | } |
| 583 | |
| 584 | fn bridge_for(mock: Arc<MockLlmClient>, depth_remaining: u32) -> BridgeFixture { |
| 585 | let client: Arc<dyn Replies> = mock; |
| 586 | BridgeFixture::new(client, "child-model".to_string(), depth_remaining).with_gate(Some( |
| 587 | crate::tools::codemode::NestedCallGate::admitting_for_test(), |
| 588 | )) |
| 589 | } |
| 590 | |
| 591 | #[tokio::test] |
| 592 | async fn expired_parent_deadline_and_nested_receipt_bound_refuse_before_work() { |
| 593 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 594 | for depth in [0, 1] { |
| 595 | let bridge = |
| 596 | bridge_for(mock.clone(), depth).with_deadline(Some(tokio::time::Instant::now())); |
| 597 | let response = bridge.dispatch_rlm("must not dispatch".into(), None).await; |
| 598 | assert!(response.error.unwrap().contains("deadline exhausted")); |
| 599 | assert_eq!(mock.call_count(), 0); |
| 600 | assert!(bridge.usage_snapshot().await.nested_events.is_empty()); |
| 601 | } |
| 602 | let bridge = bridge_for(mock.clone(), 1); |
| 603 | for _ in 0..crate::cost_status::MAX_CHILD_USAGE_RECORDS { |
| 604 | bridge.usage.reserve_nested_turn().await.unwrap(); |
| 605 | } |
| 606 | let response = bridge |
| 607 | .dispatch_rlm("must not spawn Python".into(), None) |
| 608 | .await; |
| 609 | assert!(response.error.unwrap().contains("receipt limit")); |
| 610 | assert_eq!(mock.call_count(), 0); |
| 611 | assert!(bridge.usage_snapshot().await.nested_events.is_empty()); |
| 612 | } |
| 613 | |
| 614 | struct PendingClient(MockLlmClient); |
| 615 | |
| 616 | impl Replies for PendingClient { |
| 617 | fn effective_route_envelope( |
| 618 | &self, |
| 619 | model: &str, |
| 620 | at: chrono::DateTime<chrono::Utc>, |
| 621 | ) -> crate::cost_status::EffectiveRouteEnvelope { |
| 622 | Replies::effective_route_envelope(&self.0, model, at) |
| 623 | } |
| 624 | fn effective_max_output_tokens(&self, model: &str) -> u32 { |
| 625 | Replies::effective_max_output_tokens(&self.0, model) |
| 626 | } |
| 627 | fn create_message_boxed( |
| 628 | &self, |
| 629 | _: MessageRequest, |
| 630 | ) -> Pin<Box<dyn Future<Output = Result<MessageResponse>> + Send + '_>> { |
| 631 | Box::pin(std::future::pending()) |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | #[tokio::test] |
| 636 | async fn parent_deadline_interrupts_plain_and_recursive_model_calls() { |
| 637 | for depth in [0, 1] { |
| 638 | let bridge = BridgeFixture::new( |
| 639 | Arc::new(PendingClient(MockLlmClient::new(Vec::new()))), |
| 640 | "child-model".into(), |
| 641 | depth, |
| 642 | ) |
| 643 | .with_deadline(Some( |
| 644 | tokio::time::Instant::now() + Duration::from_millis(500), |
| 645 | )) |
| 646 | .with_gate(Some( |
| 647 | crate::tools::codemode::NestedCallGate::admitting_for_test(), |
| 648 | )); |
| 649 | let response = tokio::time::timeout( |
| 650 | Duration::from_secs(5), |
| 651 | bridge.dispatch_rlm("bounded nested context".into(), None), |
| 652 | ) |
| 653 | .await |
| 654 | .expect("a child must not replace the inherited budget"); |
| 655 | assert!( |
| 656 | response |
| 657 | .error |
| 658 | .as_deref() |
| 659 | .is_some_and(|error| error.contains("deadline")), |
| 660 | "{:?}", |
| 661 | response.error |
| 662 | ); |
| 663 | if depth == 0 { |
| 664 | let snapshot = bridge.usage_snapshot().await; |
| 665 | assert_eq!(snapshot.records.len(), 1); |
| 666 | let revision = snapshot.records[0] |
| 667 | .settlement |
| 668 | .as_ref() |
| 669 | .expect("canceled provider work keeps a settled receipt"); |
| 670 | assert_eq!( |
| 671 | revision.coverage, |
| 672 | crate::llm_client::ProviderUsageCoverage::Missing, |
| 673 | "canceled provider work has unknown usage, never priced zero" |
| 674 | ); |
| 675 | assert_eq!( |
| 676 | revision.reason, |
| 677 | Some(crate::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown) |
| 678 | ); |
| 679 | assert_eq!(snapshot.dropped_records, 0); |
| 680 | } |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | #[test] |
| 685 | fn batch_guard_allows_non_empty_batches_at_the_cap() { |
| 686 | assert!(batch_guard(MAX_BATCH, Some("independent")).is_none()); |
| 687 | } |
| 688 | |
| 689 | #[test] |
| 690 | fn batch_guard_returns_empty_response_for_empty_batches() { |
| 691 | let response = batch_guard(0, None).expect("empty batch should be handled"); |
| 692 | match response { |
| 693 | RpcResponse::Batch(batch) => assert!(batch.results.is_empty()), |
| 694 | other => panic!("expected empty batch response, got {other:?}"), |
| 695 | } |
| 696 | } |
| 697 | |
| 698 | #[test] |
| 699 | fn batch_guard_returns_bounded_single_error_for_oversized_batch() { |
| 700 | for prompt_count in [MAX_BATCH + 2, 100_000] { |
| 701 | let response = batch_guard(prompt_count, Some("independent")) |
| 702 | .expect("oversized batch should be handled"); |
| 703 | match response { |
| 704 | RpcResponse::Single(single) => { |
| 705 | assert!(single.text.is_empty()); |
| 706 | assert_eq!( |
| 707 | single.error.as_deref(), |
| 708 | Some(format!("batch too large: {prompt_count} > {MAX_BATCH}").as_str()) |
| 709 | ); |
| 710 | } |
| 711 | other => panic!("expected bounded single error response, got {other:?}"), |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | #[test] |
| 717 | fn batch_guard_requires_explicit_independence_for_parallel_work() { |
| 718 | let response = batch_guard(2, None).expect("missing dependency mode should be handled"); |
| 719 | match response { |
| 720 | RpcResponse::Single(single) => { |
| 721 | assert!(single.text.is_empty()); |
| 722 | assert!( |
| 723 | single |
| 724 | .error |
| 725 | .as_deref() |
| 726 | .is_some_and(|err| err.contains("dependency_mode='independent'")) |
| 727 | ); |
| 728 | } |
| 729 | other => panic!("expected bounded single error response, got {other:?}"), |
| 730 | } |
| 731 | |
| 732 | let response = batch_guard(2, Some("sequential")) |
| 733 | .expect("dependent dependency mode should be handled"); |
| 734 | match response { |
| 735 | RpcResponse::Single(single) => { |
| 736 | assert!( |
| 737 | single |
| 738 | .error |
| 739 | .as_deref() |
| 740 | .is_some_and(|err| err.contains("sub_query_sequence")) |
| 741 | ); |
| 742 | } |
| 743 | other => panic!("expected bounded single error response, got {other:?}"), |
| 744 | } |
| 745 | } |
| 746 | |
| 747 | #[tokio::test] |
| 748 | async fn oversized_batch_guard_surfaces_batch_too_large_text_in_python_repl() { |
| 749 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 750 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 751 | let mut rt = codewhale_repl::PythonRuntime::unconfined(&std::env::temp_dir()) |
| 752 | .await |
| 753 | .expect("spawn python runtime"); |
| 754 | let round = rt |
| 755 | .run( |
| 756 | "llm_out = llm_query_batched(['p'] * 20, dependency_mode='independent')\n\ |
| 757 | rlm_out = rlm_query_batched(['p'] * 20, dependency_mode='independent')\n\ |
| 758 | print('LLM:', len(llm_out), llm_out[0])\n\ |
| 759 | print('RLM:', len(rlm_out), rlm_out[0])", |
| 760 | Some(&bridge), |
| 761 | ) |
| 762 | .await |
| 763 | .expect("execute batched guard probes"); |
| 764 | rt.shutdown().await; |
| 765 | |
| 766 | let out = round.stdout.replace("\r\n", "\n"); |
| 767 | assert!( |
| 768 | out.contains("LLM: 20 [llm_query_batched: batch too large: 20 > 16]"), |
| 769 | "unexpected llm_query_batched output: {out}" |
| 770 | ); |
| 771 | assert!( |
| 772 | out.contains("RLM: 20 [rlm_query_batched: batch too large: 20 > 16]"), |
| 773 | "unexpected rlm_query_batched output: {out}" |
| 774 | ); |
| 775 | assert!( |
| 776 | !out.contains("size mismatch"), |
| 777 | "oversized batch guard must not trigger Python size mismatch: {out}" |
| 778 | ); |
| 779 | assert!(mock.captured_requests().is_empty()); |
| 780 | } |
| 781 | |
| 782 | #[tokio::test] |
| 783 | async fn llm_dispatch_pins_configured_child_model() { |
| 784 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 785 | mock.push_message_response(mock_response("child answer", 7, 11)); |
| 786 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 787 | |
| 788 | let response = bridge |
| 789 | .dispatch(RpcRequest::Llm { |
| 790 | prompt: "child prompt".to_string(), |
| 791 | model: Some("override-model".to_string()), |
| 792 | max_tokens: Some(123), |
| 793 | system: Some("child system".to_string()), |
| 794 | }) |
| 795 | .await; |
| 796 | |
| 797 | match response { |
| 798 | RpcResponse::Single(single) => { |
| 799 | assert_eq!(single.text, "child answer"); |
| 800 | assert!(single.error.is_none()); |
| 801 | } |
| 802 | other => panic!("expected single response, got {other:?}"), |
| 803 | } |
| 804 | |
| 805 | let captured = mock.captured_requests(); |
| 806 | assert_eq!(captured.len(), 1); |
| 807 | assert_eq!(captured[0].model, "child-model"); |
| 808 | assert_eq!(captured[0].max_tokens, 123); |
| 809 | let system = serde_json::to_string(&captured[0].system).unwrap(); |
| 810 | assert!(system.contains("Captured operator Core policy")); |
| 811 | assert!(system.contains("child system")); |
| 812 | |
| 813 | let snapshot = bridge.usage_snapshot().await; |
| 814 | assert_eq!(snapshot.usage.input_tokens, 7); |
| 815 | assert_eq!(snapshot.usage.output_tokens, 11); |
| 816 | assert_eq!(snapshot.records.len(), 1); |
| 817 | let mut flat_usage = snapshot.usage.clone(); |
| 818 | flat_usage.request_usages.clear(); |
| 819 | assert_eq!(snapshot.records[0].usage.usage, flat_usage); |
| 820 | assert!(snapshot.drop_records.is_empty()); |
| 821 | assert_eq!(snapshot.dropped_records, 0); |
| 822 | } |
| 823 | |
| 824 | #[tokio::test] |
| 825 | async fn llm_dispatch_keeps_semantic_success_but_marks_missing_usage_once() { |
| 826 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 827 | mock.push_message_response(mock_response_with_usage( |
| 828 | "usable child answer", |
| 829 | Usage::default(), |
| 830 | )); |
| 831 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 832 | |
| 833 | let response = bridge |
| 834 | .dispatch(RpcRequest::Llm { |
| 835 | prompt: "child prompt".to_string(), |
| 836 | model: None, |
| 837 | max_tokens: None, |
| 838 | system: None, |
| 839 | }) |
| 840 | .await; |
| 841 | |
| 842 | let RpcResponse::Single(response) = response else { |
| 843 | panic!("expected single response"); |
| 844 | }; |
| 845 | assert_eq!(response.text, "usable child answer"); |
| 846 | assert!(response.error.is_none()); |
| 847 | |
| 848 | let first = bridge.usage_snapshot().await; |
| 849 | let replay = bridge.usage_snapshot().await; |
| 850 | assert_eq!(first.usage.input_tokens, 0); |
| 851 | assert_eq!(first.usage.output_tokens, 0); |
| 852 | assert_eq!(first.records.len(), 1); |
| 853 | assert_eq!(replay.records, first.records); |
| 854 | let revision = first.records[0] |
| 855 | .settlement |
| 856 | .as_ref() |
| 857 | .expect("settled missing-usage receipt"); |
| 858 | assert_eq!( |
| 859 | revision.coverage, |
| 860 | crate::llm_client::ProviderUsageCoverage::Missing |
| 861 | ); |
| 862 | assert_eq!( |
| 863 | revision.reason, |
| 864 | Some(crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage) |
| 865 | ); |
| 866 | assert!(first.drop_records.is_empty()); |
| 867 | assert_eq!(first.dropped_records, 0); |
| 868 | assert_eq!(first.records[0].usage.route.model, "child-model"); |
| 869 | assert!(first.records[0].source_id.starts_with("rlm:")); |
| 870 | } |
| 871 | |
| 872 | #[tokio::test] |
| 873 | async fn repeated_reservation_settlement_cannot_duplicate_usage_or_missing_coverage() { |
| 874 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 875 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 876 | let route = |
| 877 | Replies::effective_route_envelope(mock.as_ref(), "child-model", chrono::Utc::now()); |
| 878 | |
| 879 | let usage_reservation = bridge |
| 880 | .usage |
| 881 | .reserve(route.clone()) |
| 882 | .await |
| 883 | .expect("usage reservation"); |
| 884 | let reported = Usage { |
| 885 | input_tokens: 3, |
| 886 | output_tokens: 5, |
| 887 | ..Usage::default() |
| 888 | }; |
| 889 | bridge.usage.complete(usage_reservation, &reported).await; |
| 890 | bridge.usage.complete(usage_reservation, &reported).await; |
| 891 | |
| 892 | let missing_reservation = bridge |
| 893 | .usage |
| 894 | .reserve(route) |
| 895 | .await |
| 896 | .expect("missing reservation"); |
| 897 | bridge.usage.cancel(missing_reservation, true).await; |
| 898 | bridge.usage.cancel(missing_reservation, true).await; |
| 899 | |
| 900 | let snapshot = bridge.usage_snapshot().await; |
| 901 | let mut expected_reported = reported.clone(); |
| 902 | expected_reported.request_usages = vec![reported.clone()]; |
| 903 | assert_eq!(snapshot.usage, expected_reported); |
| 904 | assert_eq!(snapshot.records.len(), 1); |
| 905 | assert_eq!(snapshot.drop_records.len(), 1); |
| 906 | assert_eq!(snapshot.dropped_records, 1); |
| 907 | } |
| 908 | |
| 909 | #[tokio::test] |
| 910 | async fn llm_dispatch_preserves_prompt_cache_usage() { |
| 911 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 912 | mock.push_message_response(mock_response_with_usage( |
| 913 | "cached child answer", |
| 914 | Usage { |
| 915 | input_tokens: 1000, |
| 916 | output_tokens: 100, |
| 917 | prompt_cache_hit_tokens: Some(800), |
| 918 | prompt_cache_miss_tokens: Some(200), |
| 919 | ..Usage::default() |
| 920 | }, |
| 921 | )); |
| 922 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 923 | |
| 924 | let response = bridge |
| 925 | .dispatch(RpcRequest::Llm { |
| 926 | prompt: "child prompt".to_string(), |
| 927 | model: None, |
| 928 | max_tokens: None, |
| 929 | system: None, |
| 930 | }) |
| 931 | .await; |
| 932 | |
| 933 | match response { |
| 934 | RpcResponse::Single(single) => { |
| 935 | assert_eq!(single.text, "cached child answer"); |
| 936 | assert!(single.error.is_none()); |
| 937 | } |
| 938 | other => panic!("expected single response, got {other:?}"), |
| 939 | } |
| 940 | |
| 941 | let usage = bridge.usage_snapshot().await.usage; |
| 942 | assert_eq!(usage.input_tokens, 1000); |
| 943 | assert_eq!(usage.output_tokens, 100); |
| 944 | assert_eq!(usage.prompt_cache_hit_tokens, Some(800)); |
| 945 | assert_eq!(usage.prompt_cache_miss_tokens, Some(200)); |
| 946 | } |
| 947 | |
| 948 | #[tokio::test] |
| 949 | async fn llm_dispatch_rejects_max_tokens_partial_output_after_charging_usage() { |
| 950 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 951 | let usage = Usage { |
| 952 | input_tokens: 23, |
| 953 | output_tokens: 4096, |
| 954 | reasoning_tokens: Some(4000), |
| 955 | ..Usage::default() |
| 956 | }; |
| 957 | let mut response = mock_response_with_usage( |
| 958 | "FINAL('partial answer')\n```repl\nFINAL('also partial')\n```", |
| 959 | usage.clone(), |
| 960 | ); |
| 961 | response.stop_reason = Some("max_tokens".to_string()); |
| 962 | mock.push_message_response(response); |
| 963 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 964 | |
| 965 | let response = bridge |
| 966 | .dispatch(RpcRequest::Llm { |
| 967 | prompt: "child prompt".to_string(), |
| 968 | model: None, |
| 969 | max_tokens: None, |
| 970 | system: None, |
| 971 | }) |
| 972 | .await; |
| 973 | |
| 974 | match response { |
| 975 | RpcResponse::Single(single) => { |
| 976 | assert!( |
| 977 | single.text.is_empty(), |
| 978 | "partial output must not be accepted" |
| 979 | ); |
| 980 | let error = single.error.expect("truncation must surface as an error"); |
| 981 | assert!(error.contains("incomplete"), "{error}"); |
| 982 | assert!(error.contains("max_tokens"), "{error}"); |
| 983 | } |
| 984 | other => panic!("expected single response, got {other:?}"), |
| 985 | } |
| 986 | |
| 987 | let snapshot = bridge.usage_snapshot().await; |
| 988 | let mut expected_usage = usage.clone(); |
| 989 | expected_usage.request_usages = vec![usage.clone()]; |
| 990 | assert_eq!(snapshot.usage, expected_usage); |
| 991 | assert_eq!(snapshot.records.len(), 1); |
| 992 | assert_eq!(snapshot.records[0].usage.usage, usage); |
| 993 | let rejected_fragments: Vec<_> = snapshot |
| 994 | .nested_events |
| 995 | .iter() |
| 996 | .filter(|event| { |
| 997 | event["kind"] == "code" |
| 998 | && event["content"] |
| 999 | == "FINAL('partial answer')\n```repl\nFINAL('also partial')\n```" |
| 1000 | }) |
| 1001 | .collect(); |
| 1002 | assert_eq!( |
| 1003 | rejected_fragments.len(), |
| 1004 | 1, |
| 1005 | "retain the real rejected diagnostic fragment" |
| 1006 | ); |
| 1007 | assert_eq!(mock.call_count(), 1, "truncation must not retry"); |
| 1008 | } |
| 1009 | |
| 1010 | #[tokio::test] |
| 1011 | async fn llm_batch_dispatch_pins_configured_child_model() { |
| 1012 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 1013 | mock.push_message_response(mock_response("one", 1, 2)); |
| 1014 | mock.push_message_response(mock_response("two", 3, 4)); |
| 1015 | mock.push_message_response(mock_response("three", 5, 6)); |
| 1016 | let bridge = bridge_for(Arc::clone(&mock), 1); |
| 1017 | |
| 1018 | let response = bridge |
| 1019 | .dispatch(RpcRequest::LlmBatch { |
| 1020 | prompts: vec!["a".to_string(), "b".to_string(), "c".to_string()], |
| 1021 | model: Some("batch-model".to_string()), |
| 1022 | dependency_mode: Some("independent".to_string()), |
| 1023 | safety_note: Some("test prompts are independent".to_string()), |
| 1024 | }) |
| 1025 | .await; |
| 1026 | |
| 1027 | match response { |
| 1028 | RpcResponse::Batch(batch) => { |
| 1029 | let mut texts: Vec<_> = batch |
| 1030 | .results |
| 1031 | .iter() |
| 1032 | .map(|result| result.text.as_str()) |
| 1033 | .collect(); |
| 1034 | texts.sort_unstable(); |
| 1035 | assert_eq!(texts, ["one", "three", "two"]); |
| 1036 | assert!(batch.results.iter().all(|result| result.error.is_none())); |
| 1037 | } |
| 1038 | other => panic!("expected batch response, got {other:?}"), |
| 1039 | } |
| 1040 | |
| 1041 | let captured = mock.captured_requests(); |
| 1042 | assert_eq!(captured.len(), 3); |
| 1043 | assert!( |
| 1044 | captured |
| 1045 | .iter() |
| 1046 | .all(|request| request.model == "child-model") |
| 1047 | ); |
| 1048 | |
| 1049 | let snapshot = bridge.usage_snapshot().await; |
| 1050 | assert_eq!(snapshot.usage.input_tokens, 9); |
| 1051 | assert_eq!(snapshot.usage.output_tokens, 12); |
| 1052 | assert_eq!(snapshot.records.len(), 3); |
| 1053 | assert_ne!( |
| 1054 | snapshot.records[0].source_id, snapshot.records[1].source_id, |
| 1055 | "distinct provider calls must keep distinct stable identities" |
| 1056 | ); |
| 1057 | } |
| 1058 | |
| 1059 | #[tokio::test] |
| 1060 | async fn shared_accumulator_rejects_the_first_unreceipted_request_before_provider_work() { |
| 1061 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 1062 | let client: Arc<dyn Replies> = mock.clone(); |
| 1063 | let usage = RlmUsageAccumulator::new(); |
| 1064 | let bridge = BridgeFixture::with_usage_accumulator( |
| 1065 | Arc::clone(&client), |
| 1066 | "child-model".to_string(), |
| 1067 | 1, |
| 1068 | usage.clone(), |
| 1069 | ); |
| 1070 | let nested_bridge = |
| 1071 | BridgeFixture::with_usage_accumulator(client, "child-model".to_string(), 1, usage); |
| 1072 | let route = |
| 1073 | Replies::effective_route_envelope(mock.as_ref(), "child-model", chrono::Utc::now()); |
| 1074 | for _ in 0..crate::cost_status::MAX_CHILD_USAGE_RECORDS { |
| 1075 | let reservation = bridge |
| 1076 | .usage |
| 1077 | .reserve(route.clone()) |
| 1078 | .await |
| 1079 | .expect("receipt slot below cap"); |
| 1080 | bridge |
| 1081 | .usage |
| 1082 | .complete( |
| 1083 | reservation, |
| 1084 | &Usage { |
| 1085 | input_tokens: 1, |
| 1086 | ..Usage::default() |
| 1087 | }, |
| 1088 | ) |
| 1089 | .await; |
| 1090 | } |
| 1091 | |
| 1092 | let response = nested_bridge |
| 1093 | .dispatch(RpcRequest::Llm { |
| 1094 | prompt: "must not reach provider".to_string(), |
| 1095 | model: None, |
| 1096 | max_tokens: None, |
| 1097 | system: None, |
| 1098 | }) |
| 1099 | .await; |
| 1100 | let RpcResponse::Single(response) = response else { |
| 1101 | panic!("expected single response"); |
| 1102 | }; |
| 1103 | assert!( |
| 1104 | response |
| 1105 | .error |
| 1106 | .as_deref() |
| 1107 | .is_some_and(|error| error.contains("rejected before dispatch")) |
| 1108 | ); |
| 1109 | assert_eq!(mock.call_count(), 0); |
| 1110 | let snapshot = bridge.usage_snapshot().await; |
| 1111 | assert_eq!( |
| 1112 | snapshot.records.len(), |
| 1113 | crate::cost_status::MAX_CHILD_USAGE_RECORDS |
| 1114 | ); |
| 1115 | assert_eq!(snapshot.dropped_records, 0); |
| 1116 | assert!(snapshot.drop_records.is_empty()); |
| 1117 | } |
| 1118 | |
| 1119 | /// #6511: a nested sub-RLM's events used to go to a drain task, so its |
| 1120 | /// model calls never reached the parent's record. |
| 1121 | #[tokio::test] |
| 1122 | async fn nested_rlm_events_reach_the_parent_stream() { |
| 1123 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 1124 | mock.push_message_response(mock_response("```repl\nFINAL('nested answer')\n```", 3, 4)); |
| 1125 | let (tx, mut rx) = tokio::sync::mpsc::channel(256); |
| 1126 | let bridge = bridge_for(Arc::clone(&mock), 1).with_events(tx); |
| 1127 | |
| 1128 | let response = bridge |
| 1129 | .dispatch_rlm("nested context".to_string(), None) |
| 1130 | .await; |
| 1131 | assert_eq!(response.text, "nested answer"); |
| 1132 | assert!(response.error.is_none(), "{:?}", response.error); |
| 1133 | |
| 1134 | let mut lines = Vec::new(); |
| 1135 | while let Ok(event) = rx.try_recv() { |
| 1136 | match event { |
| 1137 | crate::core::events::Event::Status { message } => lines.push(message), |
| 1138 | other => panic!("nested events must arrive as status lines, got {other:?}"), |
| 1139 | } |
| 1140 | } |
| 1141 | assert!( |
| 1142 | lines |
| 1143 | .iter() |
| 1144 | .all(|line| line.starts_with(NESTED_RLM_STATUS_PREFIX)), |
| 1145 | "{lines:#?}" |
| 1146 | ); |
| 1147 | assert!( |
| 1148 | lines |
| 1149 | .iter() |
| 1150 | .any(|line| line.contains("FINAL('nested answer')")), |
| 1151 | "the nested code round is part of the record: {lines:#?}" |
| 1152 | ); |
| 1153 | assert!( |
| 1154 | lines |
| 1155 | .iter() |
| 1156 | .any(|line| line.contains("RLM finished: Final")), |
| 1157 | "{lines:#?}" |
| 1158 | ); |
| 1159 | let receipts = bridge.usage_snapshot().await.nested_events; |
| 1160 | assert_eq!( |
| 1161 | receipts.len(), |
| 1162 | 2, |
| 1163 | "one complete model/code reply and one terminal receipt" |
| 1164 | ); |
| 1165 | assert!(receipts.iter().all(|entry| { |
| 1166 | let content = entry["content"] |
| 1167 | .as_str() |
| 1168 | .expect("canonical receipt content"); |
| 1169 | lines.iter().any(|line| line.contains(content)) |
| 1170 | })); |
| 1171 | assert_eq!( |
| 1172 | receipts |
| 1173 | .iter() |
| 1174 | .filter(|entry| entry["kind"] == "code") |
| 1175 | .count(), |
| 1176 | 1 |
| 1177 | ); |
| 1178 | assert!(receipts.iter().any(|entry| { |
| 1179 | entry["content"] |
| 1180 | .as_str() |
| 1181 | .is_some_and(|text| text.contains("RLM finished: Final")) |
| 1182 | })); |
| 1183 | assert_eq!( |
| 1184 | crate::core::events::status_visibility(&lines[0]), |
| 1185 | crate::core::events::StatusVisibility::Internal |
| 1186 | ); |
| 1187 | } |
| 1188 | |
| 1189 | #[tokio::test] |
| 1190 | async fn rlm_dispatch_at_depth_zero_pins_configured_child_model() { |
| 1191 | let mock = Arc::new(MockLlmClient::new(Vec::new())); |
| 1192 | mock.push_message_response(mock_response("fallback answer", 3, 5)); |
| 1193 | let bridge = bridge_for(Arc::clone(&mock), 0); |
| 1194 | |
| 1195 | let response = bridge |
| 1196 | .dispatch(RpcRequest::Rlm { |
| 1197 | prompt: "nested prompt".to_string(), |
| 1198 | model: Some("override-model".to_string()), |
| 1199 | }) |
| 1200 | .await; |
| 1201 | |
| 1202 | match response { |
| 1203 | RpcResponse::Single(single) => { |
| 1204 | assert_eq!(single.text, "fallback answer"); |
| 1205 | assert!(single.error.is_none()); |
| 1206 | } |
| 1207 | other => panic!("expected single response, got {other:?}"), |
| 1208 | } |
| 1209 | |
| 1210 | let usage = bridge.usage_snapshot().await.usage; |
| 1211 | assert_eq!(usage.input_tokens, 3); |
| 1212 | assert_eq!(usage.output_tokens, 5); |
| 1213 | |
| 1214 | let captured = mock.captured_requests(); |
| 1215 | assert_eq!(captured.len(), 1); |
| 1216 | assert_eq!(captured[0].model, "child-model"); |
| 1217 | } |
| 1218 | } |
| 1219 |