| 1 | //! Engine-owned compaction lifecycle, recovery and checkpoint installation. |
| 2 | //! Automatic, manual and emergency paths share the existing session and event authority. |
| 3 | |
| 4 | use super::*; |
| 5 | |
| 6 | pub(super) struct CompactionPass { |
| 7 | pub trigger: &'static str, |
| 8 | pub path: Option<crate::compaction::CompactionPath>, |
| 9 | pub messages_before: usize, |
| 10 | pub messages_after: Option<usize>, |
| 11 | pub tokens_before: usize, |
| 12 | pub threshold_tokens: usize, |
| 13 | pub configured_threshold_tokens: usize, |
| 14 | pub usage: Usage, |
| 15 | pub elapsed_ms: u64, |
| 16 | pub reported_input_tokens: Option<u64>, |
| 17 | pub gate_input_tokens: Option<u64>, |
| 18 | pub calibration: (usize, usize), |
| 19 | pub compaction_window_tokens: Option<u32>, |
| 20 | } |
| 21 | |
| 22 | /// Which branch the turn loop takes after [`Engine::run_auto_compaction`]. |
| 23 | /// The phase only reports it; `run_turn` keeps the `continue` and `return`. |
| 24 | pub(super) enum AutoCompactionStep { |
| 25 | /// No pass was due, or a pass reached an outcome (compacted, skipped or |
| 26 | /// failed with the conversation unchanged): build this step's request. |
| 27 | Proceed, |
| 28 | /// The pass was stopped on its own while the turn stays live: start the |
| 29 | /// next loop iteration without sending a request. |
| 30 | Restart, |
| 31 | /// End the turn with this outcome: it was cancelled during the pass, or |
| 32 | /// the pass spent the turn's wall-clock budget. |
| 33 | EndTurn(TurnOutcomeStatus, Option<String>), |
| 34 | } |
| 35 | |
| 36 | /// Engine-side sink for compaction downgrade notices. |
| 37 | /// |
| 38 | /// Delivered as `Event::Status`, the same channel other engine status lines |
| 39 | /// use, so a long recovery says what it is doing while it runs. A full event |
| 40 | /// channel drops the notice instead of stalling the pass; the same sentence |
| 41 | /// is already in the log via `logging::warn`. |
| 42 | #[derive(Debug)] |
| 43 | struct EngineCompactionNoticeSink { |
| 44 | tx: mpsc::Sender<Event>, |
| 45 | child: Option<Arc<crate::tools::subagent::engine::ChildAuthority>>, |
| 46 | origin: Option<crate::cost_status::NativeUsageOrigin>, |
| 47 | } |
| 48 | |
| 49 | impl crate::compaction::CompactionNoticeSink for EngineCompactionNoticeSink { |
| 50 | fn notice(&self, message: String) { |
| 51 | let _ = self.tx.try_send(Event::Status { message }); |
| 52 | } |
| 53 | fn tool_projection_warning(&self, warning: codewhale_models::ToolProjectionWarning) { |
| 54 | let _ = self.tx.try_send(warning.into()); |
| 55 | } |
| 56 | fn accounting_origin(&self) -> std::io::Result<Option<crate::cost_status::NativeUsageOrigin>> { |
| 57 | if let Some(child) = self.child.as_ref() { |
| 58 | let origin = child.usage_origin(); |
| 59 | if origin.is_none() { |
| 60 | tracing::warn!( |
| 61 | "child compaction has no admitted accounting origin; cost stays unknown" |
| 62 | ); |
| 63 | } |
| 64 | return Ok(origin); |
| 65 | } |
| 66 | Ok(self.origin.clone()) |
| 67 | } |
| 68 | fn settled_usage<'a>( |
| 69 | &'a self, |
| 70 | record: &'a crate::cost_status::RuntimeUsageRecord, |
| 71 | ) -> std::pin::Pin<Box<dyn std::future::Future<Output = std::io::Result<()>> + Send + 'a>> { |
| 72 | Box::pin(async move { |
| 73 | if let Some(child) = self.child.as_ref() |
| 74 | && let Err(error) = child.project_settled_response(record).await |
| 75 | { |
| 76 | tracing::warn!( |
| 77 | %error, |
| 78 | "compaction usage projection failed; the pass continues" |
| 79 | ); |
| 80 | } |
| 81 | Ok(()) |
| 82 | }) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | impl Engine { |
| 87 | pub(super) async fn emit_compaction_started( |
| 88 | &mut self, |
| 89 | id: String, |
| 90 | auto: bool, |
| 91 | message: String, |
| 92 | previous_source: Option<crate::core::ops::SessionSnapshotSource>, |
| 93 | ) { |
| 94 | let _ = self |
| 95 | .send_event(Event::CompactionStarted { |
| 96 | previous_source, |
| 97 | id, |
| 98 | auto, |
| 99 | message, |
| 100 | }) |
| 101 | .await; |
| 102 | } |
| 103 | |
| 104 | pub(super) async fn emit_compaction_completed( |
| 105 | &mut self, |
| 106 | id: String, |
| 107 | auto: bool, |
| 108 | message: String, |
| 109 | pass: CompactionPass, |
| 110 | ) { |
| 111 | let summary_prompt = self.rendered_compaction_summary(); |
| 112 | // Every call site runs after message replacement and checkpoint |
| 113 | // commit. Reuse the same complete estimate as context pressure. |
| 114 | let post_input_tokens = Some(self.estimated_input_tokens() as u64); |
| 115 | let messages_before = pass.messages_before; |
| 116 | let reduction_ratio = pass |
| 117 | .messages_after |
| 118 | .filter(|_| messages_before > 0) |
| 119 | .map(|after| 1.0 - after as f64 / messages_before as f64); |
| 120 | self.record_compaction_event( |
| 121 | "compaction.completed", |
| 122 | compaction_audit_details("success", &id, &pass, post_input_tokens, reduction_ratio), |
| 123 | ) |
| 124 | .await; |
| 125 | let _ = self |
| 126 | .send_event(Event::CompactionCompleted { |
| 127 | id, |
| 128 | auto, |
| 129 | message, |
| 130 | messages_before: Some(pass.messages_before), |
| 131 | messages_after: pass.messages_after, |
| 132 | summary_prompt, |
| 133 | post_input_tokens, |
| 134 | }) |
| 135 | .await; |
| 136 | } |
| 137 | |
| 138 | /// One audit producer shared by interactive, headless and Runtime hosts. |
| 139 | /// No transcript content or credentials enter this diagnostic record. |
| 140 | pub(super) async fn record_compaction_event( |
| 141 | &self, |
| 142 | event: &'static str, |
| 143 | mut details: serde_json::Value, |
| 144 | ) { |
| 145 | details["session_id"] = serde_json::json!(self.session.id); |
| 146 | details["thread_id"] = serde_json::json!(self.config.runtime_services.active_thread_id); |
| 147 | details["model"] = serde_json::json!(self.config.model); |
| 148 | details["provider"] = serde_json::json!(self.api_provider.as_str()); |
| 149 | details["provider_identity"] = serde_json::json!( |
| 150 | self.api_provider_identity |
| 151 | .as_ref() |
| 152 | .and_then(|identity| identity.persisted_id()) |
| 153 | ); |
| 154 | details["route_model"] = serde_json::json!(self.session.model); |
| 155 | details["effective_context_window_tokens"] = |
| 156 | serde_json::json!(self.active_context_window.map(|window| window.tokens)); |
| 157 | details["effective_context_window_source"] = serde_json::json!( |
| 158 | self.active_context_window |
| 159 | .map(|window| window.source.label()) |
| 160 | ); |
| 161 | #[cfg(any(test, feature = "test-support"))] |
| 162 | let env_ticket = crate::test_support::env_scope_ticket(); |
| 163 | if let Err(error) = tokio::task::spawn_blocking(move || { |
| 164 | #[cfg(any(test, feature = "test-support"))] |
| 165 | let _membership = crate::test_support::join_env_scope(env_ticket); |
| 166 | codewhale_runtime::audit::log_sensitive_event(event, details); |
| 167 | }) |
| 168 | .await |
| 169 | { |
| 170 | tracing::warn!(%error, "compaction audit writer failed"); |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | pub(super) async fn emit_compaction_cancelled( |
| 175 | &mut self, |
| 176 | id: String, |
| 177 | auto: bool, |
| 178 | message: String, |
| 179 | pass: CompactionPass, |
| 180 | ) { |
| 181 | self.record_compaction_event( |
| 182 | "compaction.cancelled", |
| 183 | compaction_audit_details("cancelled", &id, &pass, None, None), |
| 184 | ) |
| 185 | .await; |
| 186 | let _ = self |
| 187 | .send_event(Event::CompactionCancelled { id, auto, message }) |
| 188 | .await; |
| 189 | } |
| 190 | |
| 191 | /// Render the accumulated compaction summary prompt to plain text so it |
| 192 | /// can travel in events and be persisted by host layers. All emit sites |
| 193 | /// run after `commit_compaction_checkpoint`, so this reflects the checkpoint |
| 194 | /// state the engine will use for subsequent requests. |
| 195 | pub(super) fn rendered_compaction_summary(&self) -> Option<String> { |
| 196 | self.session |
| 197 | .compaction_summary_prompt |
| 198 | .as_ref() |
| 199 | .map(|prompt| match prompt { |
| 200 | SystemPrompt::Text(text) => text.clone(), |
| 201 | SystemPrompt::Blocks(blocks) => blocks |
| 202 | .iter() |
| 203 | .map(|block| block.text.as_str()) |
| 204 | .collect::<Vec<_>>() |
| 205 | .join("\n\n"), |
| 206 | }) |
| 207 | .filter(|text| !text.trim().is_empty()) |
| 208 | } |
| 209 | |
| 210 | pub(super) async fn emit_compaction_failed( |
| 211 | &mut self, |
| 212 | id: String, |
| 213 | auto: bool, |
| 214 | message: String, |
| 215 | pass: CompactionPass, |
| 216 | ) { |
| 217 | self.record_compaction_event( |
| 218 | "compaction.failed", |
| 219 | compaction_audit_details("failed", &id, &pass, None, None), |
| 220 | ) |
| 221 | .await; |
| 222 | let _ = self |
| 223 | .send_event(Event::CompactionFailed { id, auto, message }) |
| 224 | .await; |
| 225 | } |
| 226 | |
| 227 | pub(super) fn claim_compaction(&self, id: &str) -> Option<CancellationToken> { |
| 228 | self.compaction_cancellation |
| 229 | .lock() |
| 230 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 231 | .claim(id) |
| 232 | } |
| 233 | |
| 234 | pub(super) fn finish_compaction(&self, id: &str) { |
| 235 | self.compaction_cancellation |
| 236 | .lock() |
| 237 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 238 | .finish(id); |
| 239 | } |
| 240 | |
| 241 | /// Pressure and effective trigger in append-only turn metadata. Numeric |
| 242 | /// estimates never modify the session-pinned system/tool prefix. |
| 243 | pub(super) fn context_pressure_line( |
| 244 | &self, |
| 245 | current_text: &str, |
| 246 | prompt_context: &NextTurnPromptContext, |
| 247 | system_prompt: Option<&SystemPrompt>, |
| 248 | messages: &[Message], |
| 249 | planned_compaction: Option<&CompactionConfig>, |
| 250 | ) -> Option<String> { |
| 251 | let input_tokens = |
| 252 | crate::compaction::estimate_input_tokens_for_pressure(messages, system_prompt) |
| 253 | .saturating_add(if current_text.trim().is_empty() { |
| 254 | 0 |
| 255 | } else { |
| 256 | crate::compaction::estimate_message_text_tokens(current_text) + 12 |
| 257 | }); |
| 258 | let budget = crate::route_budget::route_context_budget_with_window( |
| 259 | prompt_context.provider, |
| 260 | &prompt_context.model, |
| 261 | prompt_context.route_limits, |
| 262 | prompt_context.context_window.map(|window| window.tokens), |
| 263 | input_tokens, |
| 264 | )?; |
| 265 | let estimate = format!( |
| 266 | "Estimated conversation input: {input_tokens} / {} context tokens ({:.1}%).", |
| 267 | budget.window_tokens, |
| 268 | budget.usage_percent(), |
| 269 | ); |
| 270 | let compaction = planned_compaction.unwrap_or(&self.config.compaction); |
| 271 | if compaction.enabled { |
| 272 | let matches_route = planned_compaction.is_some() |
| 273 | || (self.api_provider == prompt_context.provider |
| 274 | && self.config.model == prompt_context.model |
| 275 | && self.active_route_limits == prompt_context.route_limits); |
| 276 | if matches_route |
| 277 | && compaction.effective_context_window.map(u64::from) == Some(budget.window_tokens) |
| 278 | { |
| 279 | return Some(format!( |
| 280 | "{estimate} Automatic compaction threshold: {} tokens.", |
| 281 | compaction.token_threshold |
| 282 | )); |
| 283 | } |
| 284 | return Some(format!("{estimate} Automatic compaction is enabled.")); |
| 285 | } |
| 286 | let conservative = crate::compaction::estimate_input_tokens_conservative_with_text( |
| 287 | messages, |
| 288 | system_prompt, |
| 289 | current_text, |
| 290 | ); |
| 291 | let pressure = codewhale_runtime::context_budget::usage_percent( |
| 292 | budget.window_tokens, |
| 293 | conservative as u64, |
| 294 | ); |
| 295 | Some(context_pressure_message(pressure).map_or_else( |
| 296 | || format!("{estimate} Automatic compaction is off."), |
| 297 | |warning| format!("{warning}. {estimate} Making room automatically is off for this session. /compact saves the original conversation and its model-written handoff before replacing context."), |
| 298 | )) |
| 299 | } |
| 300 | |
| 301 | fn learn_summary_image_cap( |
| 302 | &mut self, |
| 303 | prepared: &PreparedCompactionEnvelope, |
| 304 | err: &anyhow::Error, |
| 305 | ) -> Option<usize> { |
| 306 | let rejection = |
| 307 | crate::llm_client::image_count_rejection(&format!("{err:#}").to_lowercase())?; |
| 308 | let mut messages = self.session.messages.to_vec(); |
| 309 | crate::image_attach::strip_images_when_unsupported( |
| 310 | &mut messages, |
| 311 | prepared.config.image_input, |
| 312 | &prepared.config.model, |
| 313 | ); |
| 314 | if let Some(cap) = prepared.image_cap { |
| 315 | codewhale_models::image_window::cap_request_images(&mut messages, cap); |
| 316 | } |
| 317 | let sent = codewhale_models::image_window::count_request_images(&messages); |
| 318 | self.learn_image_cap(&prepared.config.model, sent, rejection) |
| 319 | } |
| 320 | |
| 321 | pub(super) fn prepare_compaction_envelope( |
| 322 | &self, |
| 323 | mut config: CompactionConfig, |
| 324 | ) -> PreparedCompactionEnvelope { |
| 325 | // Host-supplied configs may not carry the workspace; compaction needs |
| 326 | // it only to re-state the user's `/anchor` file after the summary. |
| 327 | config |
| 328 | .workspace |
| 329 | .get_or_insert_with(|| self.config.workspace.clone()); |
| 330 | let (image_input, image_cap) = self.request_image_policy( |
| 331 | &self.image_route_provider_key(), |
| 332 | &config.model, |
| 333 | config.image_input, |
| 334 | ); |
| 335 | config.image_input = image_input; |
| 336 | let mut prepared = PreparedCompactionEnvelope::new(config); |
| 337 | prepared.image_cap = image_cap; |
| 338 | prepared.session_id = Some(self.session.id.clone()); |
| 339 | prepared.notice_sink = Some(std::sync::Arc::new(EngineCompactionNoticeSink { |
| 340 | tx: self.tx_event.clone(), |
| 341 | origin: self.turn_accounting_origin(), |
| 342 | child: self |
| 343 | .child_host |
| 344 | .as_ref() |
| 345 | .map(|child| child.authority.clone()), |
| 346 | })); |
| 347 | // The summary request must carry the reasoning tier the turn sends: |
| 348 | // reasoning routes render it at the head of the prompt, so omitting |
| 349 | // it forfeited the whole cached history prefix (#6540). |
| 350 | prepared.reasoning_effort = super::turn_loop::resolve_auto_effort( |
| 351 | self.session.reasoning_effort.as_deref(), |
| 352 | self.api_provider, |
| 353 | &self.api_config.active_route_base_url(), |
| 354 | &self.config.model, |
| 355 | ); |
| 356 | prepared |
| 357 | } |
| 358 | |
| 359 | async fn reconstruct_active_tools_for_compaction(&mut self) -> Option<Vec<Tool>> { |
| 360 | let input_policy = effective_input_policy( |
| 361 | UserInputProvenance::ExternalUser, |
| 362 | self.current_mode, |
| 363 | "", |
| 364 | self.session.allow_shell, |
| 365 | self.session.trust_mode, |
| 366 | self.session.auto_approve, |
| 367 | self.session.approval_mode, |
| 368 | ); |
| 369 | let route_context = TurnRouteContext { |
| 370 | provider: self.api_provider, |
| 371 | model: self.session.model.clone(), |
| 372 | capabilities: self.active_route_capabilities, |
| 373 | limits: self.active_route_limits, |
| 374 | client: self.codewhale_client.clone(), |
| 375 | api_config: Box::new(self.api_config.clone()), |
| 376 | locale_tag: self.config.locale_tag.clone(), |
| 377 | role_models: self.subagent_role_models(), |
| 378 | auto_model: self.session.auto_model, |
| 379 | reasoning_effort: self.session.reasoning_effort.clone(), |
| 380 | reasoning_effort_auto: self.session.reasoning_effort_auto, |
| 381 | }; |
| 382 | let build = self |
| 383 | .build_turn_tool_registry_and_catalog( |
| 384 | &input_policy, |
| 385 | &[], |
| 386 | self.config.allowed_tools.clone(), |
| 387 | SubAgentWiring::Inert, |
| 388 | McpAccess::PassiveSnapshot, |
| 389 | &[], |
| 390 | route_context, |
| 391 | "", |
| 392 | ) |
| 393 | .await; |
| 394 | let mut active_names = build.surface.active_names; |
| 395 | active_names.extend( |
| 396 | self.session |
| 397 | .tool_activation_cache |
| 398 | .names() |
| 399 | .filter(|name| build.surface.catalog.iter().any(|tool| tool.name == *name)) |
| 400 | .map(str::to_owned), |
| 401 | ); |
| 402 | active_tools_for_request( |
| 403 | &super::tool_catalog::mode_visible_catalog(&build.surface.catalog, build.surface.mode), |
| 404 | &active_names, |
| 405 | build.surface.strict_tool_mode, |
| 406 | ) |
| 407 | } |
| 408 | |
| 409 | pub(super) async fn handle_manual_compaction_op( |
| 410 | &mut self, |
| 411 | id: String, |
| 412 | route: ResolvedRuntimeRoute, |
| 413 | compaction: CompactionConfig, |
| 414 | ) { |
| 415 | // Manual compaction terminals identify the compaction operation, never |
| 416 | // a surrounding host submission or a model turn. |
| 417 | let audit_started = Instant::now(); |
| 418 | let messages_before = self.session.messages.len(); |
| 419 | let tokens_before = self.estimated_input_tokens(); |
| 420 | let reported_input_tokens = self.session.latest_parent_input_tokens.map(u64::from); |
| 421 | let threshold_tokens = compaction.token_threshold; |
| 422 | let compaction_window_tokens = compaction.effective_context_window; |
| 423 | let pass = || CompactionPass { |
| 424 | trigger: "manual", |
| 425 | path: None, |
| 426 | messages_before, |
| 427 | messages_after: None, |
| 428 | tokens_before, |
| 429 | threshold_tokens, |
| 430 | configured_threshold_tokens: threshold_tokens, |
| 431 | usage: Usage::default(), |
| 432 | elapsed_ms: elapsed_millis(audit_started), |
| 433 | reported_input_tokens, |
| 434 | gate_input_tokens: None, |
| 435 | calibration: (1, 1), |
| 436 | compaction_window_tokens, |
| 437 | }; |
| 438 | let compaction_id = Some(id.clone()); |
| 439 | let Some(cancel_token) = self.claim_compaction(&id) else { |
| 440 | let message = "Making room stopped before it started".to_string(); |
| 441 | self.emit_compaction_cancelled(id, false, message, pass()) |
| 442 | .await; |
| 443 | let _ = self |
| 444 | .send_event(Event::TurnComplete { |
| 445 | source_accounting: true, |
| 446 | |
| 447 | turn_id: None, |
| 448 | submission_id: None, |
| 449 | compaction_id, |
| 450 | usage: Usage::default(), |
| 451 | parent_route_usage: Usage::default(), |
| 452 | routed_usage_dropped_records: 0, |
| 453 | status: TurnOutcomeStatus::Interrupted, |
| 454 | error: None, |
| 455 | tool_catalog: None, |
| 456 | base_url: None, |
| 457 | }) |
| 458 | .await; |
| 459 | return; |
| 460 | }; |
| 461 | let previous_source = self.session.snapshot_source.clone(); |
| 462 | self.session.snapshot_source = Some(crate::core::ops::SessionSnapshotSource::compaction( |
| 463 | id.clone(), |
| 464 | )); |
| 465 | self.emit_compaction_started( |
| 466 | id.clone(), |
| 467 | false, |
| 468 | "Making room…".to_string(), |
| 469 | previous_source, |
| 470 | ) |
| 471 | .await; |
| 472 | if let Err(err) = self.install_resolved_runtime_route_async(route).await { |
| 473 | let message = |
| 474 | format!("Cannot compact context because its provider route is not ready: {err}"); |
| 475 | self.finish_compaction(&id); |
| 476 | self.emit_compaction_failed(id, false, message.clone(), pass()) |
| 477 | .await; |
| 478 | let _ = self |
| 479 | .send_event(Event::error(ErrorEnvelope::fatal_auth(message.clone()))) |
| 480 | .await; |
| 481 | // Route rejection is still a terminal for the compaction |
| 482 | // operation: hosts waiting on its lifecycle must be released. |
| 483 | let _ = self |
| 484 | .send_event(Event::TurnComplete { |
| 485 | source_accounting: true, |
| 486 | |
| 487 | turn_id: None, |
| 488 | submission_id: None, |
| 489 | compaction_id, |
| 490 | usage: Usage::default(), |
| 491 | parent_route_usage: Usage::default(), |
| 492 | routed_usage_dropped_records: 0, |
| 493 | status: TurnOutcomeStatus::Failed, |
| 494 | error: Some(message), |
| 495 | tool_catalog: None, |
| 496 | base_url: None, |
| 497 | }) |
| 498 | .await; |
| 499 | return; |
| 500 | } |
| 501 | self.config.compaction = compaction; |
| 502 | self.handle_manual_compaction(id, cancel_token).await; |
| 503 | } |
| 504 | |
| 505 | pub(super) async fn emit_compaction_usage(&self, usage: &Usage, elapsed: Duration) { |
| 506 | if *usage == Usage::default() { |
| 507 | return; |
| 508 | } |
| 509 | let _ = self |
| 510 | .send_event(Event::RoutedTurnUsage { |
| 511 | usage: usage.clone(), |
| 512 | duration_ms: u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX), |
| 513 | first_token_ms: None, |
| 514 | request_ms: None, |
| 515 | }) |
| 516 | .await; |
| 517 | } |
| 518 | |
| 519 | pub(super) async fn handle_manual_compaction( |
| 520 | &mut self, |
| 521 | id: String, |
| 522 | cancel_token: CancellationToken, |
| 523 | ) { |
| 524 | // Manual compaction terminals identify the compaction operation, never |
| 525 | // a surrounding host submission or a model turn. |
| 526 | let audit_started = Instant::now(); |
| 527 | let compaction_id = Some(id.clone()); |
| 528 | let zero_usage = Usage { |
| 529 | input_tokens: 0, |
| 530 | output_tokens: 0, |
| 531 | ..Usage::default() |
| 532 | }; |
| 533 | let Some(client) = self.codewhale_client.clone() else { |
| 534 | let message = "Can't make room: no model is connected".to_string(); |
| 535 | let messages_before = self.session.messages.len(); |
| 536 | let tokens_before = self.estimated_input_tokens(); |
| 537 | let reported_input_tokens = self.session.latest_parent_input_tokens.map(u64::from); |
| 538 | let threshold_tokens = self.config.compaction.token_threshold; |
| 539 | let compaction_window_tokens = self.config.compaction.effective_context_window; |
| 540 | self.finish_compaction(&id); |
| 541 | self.emit_compaction_failed( |
| 542 | id, |
| 543 | false, |
| 544 | message.clone(), |
| 545 | CompactionPass { |
| 546 | trigger: "manual", |
| 547 | path: None, |
| 548 | messages_before, |
| 549 | messages_after: None, |
| 550 | tokens_before, |
| 551 | threshold_tokens, |
| 552 | configured_threshold_tokens: threshold_tokens, |
| 553 | usage: Usage::default(), |
| 554 | elapsed_ms: elapsed_millis(audit_started), |
| 555 | reported_input_tokens, |
| 556 | gate_input_tokens: None, |
| 557 | calibration: (1, 1), |
| 558 | compaction_window_tokens, |
| 559 | }, |
| 560 | ) |
| 561 | .await; |
| 562 | let _ = self |
| 563 | .send_event(Event::error(ErrorEnvelope::fatal_auth(message.clone()))) |
| 564 | .await; |
| 565 | let _ = self |
| 566 | .send_event(Event::TurnComplete { |
| 567 | source_accounting: true, |
| 568 | |
| 569 | turn_id: None, |
| 570 | submission_id: None, |
| 571 | compaction_id, |
| 572 | usage: zero_usage, |
| 573 | parent_route_usage: Usage::default(), |
| 574 | routed_usage_dropped_records: 0, |
| 575 | status: TurnOutcomeStatus::Failed, |
| 576 | error: Some(message), |
| 577 | tool_catalog: None, |
| 578 | base_url: None, |
| 579 | }) |
| 580 | .await; |
| 581 | return; |
| 582 | }; |
| 583 | |
| 584 | let messages_before = self.session.messages.len(); |
| 585 | // Message counts alone do not show the win the user cares about: a |
| 586 | // compaction that drops few but enormous messages reads as a no-op. |
| 587 | // The emergency path already reports tokens; manual and auto now match. |
| 588 | let tokens_before = self.estimated_input_tokens(); |
| 589 | let reported_input_tokens = self.session.latest_parent_input_tokens.map(u64::from); |
| 590 | let mut turn_status = TurnOutcomeStatus::Completed; |
| 591 | let mut turn_error = None; |
| 592 | |
| 593 | let mut prepared = self.prepare_compaction_envelope(self.config.compaction.clone()); |
| 594 | prepared.tools = match self.session.last_request_tools.clone() { |
| 595 | Some(tools) => Some(tools), |
| 596 | None => tokio::select! { |
| 597 | biased; |
| 598 | _ = cancel_token.cancelled() => None, |
| 599 | tools = self.reconstruct_active_tools_for_compaction() => tools, |
| 600 | }, |
| 601 | }; |
| 602 | let threshold_tokens = prepared.config.token_threshold; |
| 603 | let compaction_window_tokens = prepared.config.effective_context_window; |
| 604 | let pass = |path: Option<crate::compaction::CompactionPath>, usage: Usage| CompactionPass { |
| 605 | trigger: "manual", |
| 606 | path, |
| 607 | messages_before, |
| 608 | messages_after: None, |
| 609 | tokens_before, |
| 610 | threshold_tokens, |
| 611 | configured_threshold_tokens: threshold_tokens, |
| 612 | usage, |
| 613 | elapsed_ms: elapsed_millis(audit_started), |
| 614 | reported_input_tokens, |
| 615 | gate_input_tokens: None, |
| 616 | calibration: (1, 1), |
| 617 | compaction_window_tokens, |
| 618 | }; |
| 619 | |
| 620 | let started = Instant::now(); |
| 621 | let mut compaction_usage = Usage::default(); |
| 622 | let compaction_result = tokio::select! { |
| 623 | biased; |
| 624 | _ = cancel_token.cancelled() => None, |
| 625 | result = compact_messages_safe( |
| 626 | &client, |
| 627 | &self.session.messages, |
| 628 | self.session.system_prompt.as_ref(), |
| 629 | &prepared, |
| 630 | &mut compaction_usage, |
| 631 | ) => Some(result), |
| 632 | }; |
| 633 | self.session.total_usage.add(&compaction_usage); |
| 634 | self.record_goal_usage_for_turn(&compaction_usage, started); |
| 635 | self.emit_compaction_usage(&compaction_usage, started.elapsed()) |
| 636 | .await; |
| 637 | |
| 638 | let Some(compaction_result) = compaction_result else { |
| 639 | self.finish_compaction(&id); |
| 640 | self.emit_compaction_cancelled( |
| 641 | id, |
| 642 | false, |
| 643 | "Making room stopped; the conversation was not changed".to_string(), |
| 644 | pass(None, compaction_usage.clone()), |
| 645 | ) |
| 646 | .await; |
| 647 | let _ = self |
| 648 | .send_event(Event::TurnComplete { |
| 649 | source_accounting: true, |
| 650 | |
| 651 | turn_id: None, |
| 652 | submission_id: None, |
| 653 | compaction_id, |
| 654 | usage: compaction_usage, |
| 655 | parent_route_usage: Usage::default(), |
| 656 | routed_usage_dropped_records: 0, |
| 657 | status: TurnOutcomeStatus::Interrupted, |
| 658 | error: None, |
| 659 | tool_catalog: None, |
| 660 | base_url: None, |
| 661 | }) |
| 662 | .await; |
| 663 | return; |
| 664 | }; |
| 665 | |
| 666 | match compaction_result { |
| 667 | Ok(mut result) => { |
| 668 | let path = result.coverage.path; |
| 669 | if !result.messages.is_empty() || self.session.messages.is_empty() { |
| 670 | self.append_compaction_agent_topology(&mut result.messages) |
| 671 | .await; |
| 672 | if cancel_token.is_cancelled() { |
| 673 | self.finish_compaction(&id); |
| 674 | self.emit_compaction_cancelled( |
| 675 | id, |
| 676 | false, |
| 677 | "Making room stopped; the conversation was not changed".to_string(), |
| 678 | pass(Some(path), compaction_usage.clone()), |
| 679 | ) |
| 680 | .await; |
| 681 | let _ = self |
| 682 | .send_event(Event::TurnComplete { |
| 683 | source_accounting: true, |
| 684 | |
| 685 | turn_id: None, |
| 686 | submission_id: None, |
| 687 | compaction_id, |
| 688 | usage: compaction_usage, |
| 689 | parent_route_usage: Usage::default(), |
| 690 | routed_usage_dropped_records: 0, |
| 691 | status: TurnOutcomeStatus::Interrupted, |
| 692 | error: None, |
| 693 | tool_catalog: None, |
| 694 | base_url: None, |
| 695 | }) |
| 696 | .await; |
| 697 | return; |
| 698 | } |
| 699 | let messages_after = result.messages.len(); |
| 700 | let retries_used = result.retries_used; |
| 701 | let coverage_clause = result.coverage.receipt_clause(); |
| 702 | if let Some(job) = self.child_job() |
| 703 | && let Err(error) = job |
| 704 | .before_replace(&self.session.messages, &result.messages) |
| 705 | .await |
| 706 | { |
| 707 | self.cancel_token.cancel(); |
| 708 | tracing::error!(%error, "child compaction projection failed; original Session retained"); |
| 709 | return; |
| 710 | } |
| 711 | self.session.replace_messages(result.messages); |
| 712 | if let Some(pm) = self.session.prefix_stability.as_mut() { |
| 713 | pm.note_history_reset("compaction"); |
| 714 | } |
| 715 | self.commit_compaction_checkpoint(result.summary_prompt); |
| 716 | self.emit_session_updated().await; |
| 717 | let removed = messages_before.saturating_sub(messages_after); |
| 718 | let tokens_after = self.estimated_input_tokens(); |
| 719 | let message = if retries_used > 0 { |
| 720 | format!( |
| 721 | "Made room: {messages_before} → {messages_after} messages ({removed} removed, {retries_used} retries), ~{tokens_before} → ~{tokens_after} tokens ({coverage_clause})" |
| 722 | ) |
| 723 | } else { |
| 724 | format!( |
| 725 | "Made room: {messages_before} → {messages_after} messages ({removed} removed), ~{tokens_before} → ~{tokens_after} tokens ({coverage_clause})" |
| 726 | ) |
| 727 | }; |
| 728 | let mut pass = pass(Some(path), compaction_usage.clone()); |
| 729 | pass.messages_after = Some(messages_after); |
| 730 | self.emit_compaction_completed(id.clone(), false, message, pass) |
| 731 | .await; |
| 732 | } else { |
| 733 | let message = "Making room skipped: the summary came back empty".to_string(); |
| 734 | self.emit_compaction_failed( |
| 735 | id.clone(), |
| 736 | false, |
| 737 | message.clone(), |
| 738 | pass(Some(path), compaction_usage.clone()), |
| 739 | ) |
| 740 | .await; |
| 741 | turn_status = TurnOutcomeStatus::Failed; |
| 742 | turn_error = Some(message); |
| 743 | } |
| 744 | } |
| 745 | Err(err) => { |
| 746 | self.learn_summary_image_cap(&prepared, &err); |
| 747 | let message = crate::compaction::report_compaction_failure( |
| 748 | "Making room failed", |
| 749 | &id, |
| 750 | false, |
| 751 | &err, |
| 752 | ); |
| 753 | self.emit_compaction_failed( |
| 754 | id.clone(), |
| 755 | false, |
| 756 | message.clone(), |
| 757 | pass(None, compaction_usage.clone()), |
| 758 | ) |
| 759 | .await; |
| 760 | let _ = self.send_event(Event::status(message.clone())).await; |
| 761 | turn_status = TurnOutcomeStatus::Failed; |
| 762 | turn_error = Some(message); |
| 763 | } |
| 764 | } |
| 765 | |
| 766 | self.finish_compaction(&id); |
| 767 | |
| 768 | let _ = self |
| 769 | .send_event(Event::TurnComplete { |
| 770 | source_accounting: true, |
| 771 | |
| 772 | turn_id: None, |
| 773 | submission_id: None, |
| 774 | compaction_id, |
| 775 | usage: compaction_usage, |
| 776 | parent_route_usage: Usage::default(), |
| 777 | routed_usage_dropped_records: 0, |
| 778 | status: turn_status, |
| 779 | error: turn_error, |
| 780 | tool_catalog: None, |
| 781 | base_url: None, |
| 782 | }) |
| 783 | .await; |
| 784 | } |
| 785 | |
| 786 | /// The automatic compaction phase of `run_turn`, run once per loop |
| 787 | /// iteration before the request is built. |
| 788 | /// |
| 789 | /// When context pressure has reached the trigger, this summarizes history |
| 790 | /// with the tool prefix the next request will carry, installs the |
| 791 | /// checkpoint and reports the pass; a refusal is named once per turn. |
| 792 | /// `auto_compaction_suppressed` is the loop's turn-scoped latch: a failed, |
| 793 | /// cancelled or empty pass, or one that leaves pressure high, sets it so |
| 794 | /// the turn cannot become a paid summarization loop at every tool |
| 795 | /// boundary. The bounded hard-limit recovery |
| 796 | /// ([`Self::recover_context_overflow`]) stays available either way. |
| 797 | /// |
| 798 | /// The loop keeps its own control flow: the returned |
| 799 | /// [`AutoCompactionStep`] names the branch, and `run_turn` takes it. |
| 800 | pub(super) async fn run_auto_compaction( |
| 801 | &mut self, |
| 802 | client: &dyn crate::core::model_client::ModelClient, |
| 803 | active_tools: Option<&[Tool]>, |
| 804 | turn: &mut TurnContext, |
| 805 | auto_compaction_suppressed: &mut bool, |
| 806 | ) -> AutoCompactionStep { |
| 807 | let auto_compaction_config = self.config.compaction.clone(); |
| 808 | // Billing usage accumulates every parent step and child-model |
| 809 | // call. Only the most recent parent-route request describes the |
| 810 | // live message list whose pressure we are checking here. |
| 811 | let billed_input_tokens = turn.live_input_tokens_for_compaction( |
| 812 | &self.session.messages, |
| 813 | self.session.system_prompt.as_ref(), |
| 814 | self.session.latest_parent_input_tokens, |
| 815 | ); |
| 816 | let reported_input_tokens = |
| 817 | turn.billed_input_tokens_for_compaction(self.session.latest_parent_input_tokens); |
| 818 | let prepared = if !*auto_compaction_suppressed |
| 819 | && auto_compaction_config.enabled |
| 820 | && billed_input_tokens |
| 821 | .and_then(|tokens| usize::try_from(tokens).ok()) |
| 822 | .unwrap_or(0) |
| 823 | >= auto_compaction_config.token_threshold |
| 824 | { |
| 825 | let mut prepared = self.prepare_compaction_envelope(auto_compaction_config); |
| 826 | prepared.input_token_ratio = turn.input_token_ratio; |
| 827 | prepared.tools = active_tools.map(<[Tool]>::to_vec); |
| 828 | Some(prepared) |
| 829 | } else { |
| 830 | None |
| 831 | }; |
| 832 | |
| 833 | let compaction_go = match prepared.as_ref() { |
| 834 | None => false, |
| 835 | Some(prepared) => match crate::compaction::compaction_decision_with_billed( |
| 836 | &self.session.messages, |
| 837 | self.session.system_prompt.as_ref(), |
| 838 | prepared, |
| 839 | billed_input_tokens, |
| 840 | ) { |
| 841 | crate::compaction::CompactionDecision::Compact => true, |
| 842 | crate::compaction::CompactionDecision::NotNeeded => false, |
| 843 | crate::compaction::CompactionDecision::Refused(reason) => { |
| 844 | // A silent refusal looks like broken auto-compaction: |
| 845 | // the meter is full and nothing happens (#5577). Name |
| 846 | // the guard once per turn, in both the transcript |
| 847 | // status line and the trace. |
| 848 | if !turn.compaction_refusal_notified { |
| 849 | turn.compaction_refusal_notified = true; |
| 850 | let estimated_tokens_before = self.estimated_input_tokens(); |
| 851 | self.record_compaction_event("compaction.refused", serde_json::json!({ |
| 852 | "trigger": "auto", |
| 853 | "reason": match &reason { |
| 854 | crate::compaction::CompactionRefusal::TooFewMessages { .. } => "too_few_messages", |
| 855 | crate::compaction::CompactionRefusal::RetainedFloor { .. } => "retained_floor", |
| 856 | }, |
| 857 | "messages_before": self.session.messages.len(), |
| 858 | "estimated_tokens_before": estimated_tokens_before, |
| 859 | "billed_input_tokens": billed_input_tokens, |
| 860 | "gate_input_tokens": billed_input_tokens, |
| 861 | "threshold_tokens": prepared.config.token_threshold, |
| 862 | })).await; |
| 863 | let message = match reason { |
| 864 | crate::compaction::CompactionRefusal::TooFewMessages { count } => { |
| 865 | format!( |
| 866 | "Context is filling up, but there is nothing to make room from yet: only {count} messages" |
| 867 | ) |
| 868 | } |
| 869 | crate::compaction::CompactionRefusal::RetainedFloor { |
| 870 | floor, |
| 871 | threshold, |
| 872 | } => format!( |
| 873 | "Context is filling up, but making room would not help: retained context (~{}K tokens) cannot fall below the {}K trigger — /compact to force a pass, or trim pinned context", |
| 874 | floor / 1000, |
| 875 | threshold / 1000 |
| 876 | ), |
| 877 | }; |
| 878 | tracing::warn!( |
| 879 | target: "compaction", |
| 880 | ?reason, |
| 881 | billed = ?billed_input_tokens, |
| 882 | "auto-compaction refused under pressure" |
| 883 | ); |
| 884 | let _ = self.send_event(Event::status(message)).await; |
| 885 | } |
| 886 | false |
| 887 | } |
| 888 | }, |
| 889 | }; |
| 890 | if let Some(prepared) = prepared |
| 891 | && compaction_go |
| 892 | { |
| 893 | if let Some(message) = turn.compaction_thrash_message() { |
| 894 | let _ = self |
| 895 | .send_event(Event::error(ErrorEnvelope::context_overflow( |
| 896 | message.clone(), |
| 897 | ))) |
| 898 | .await; |
| 899 | return AutoCompactionStep::EndTurn(TurnOutcomeStatus::Failed, Some(message)); |
| 900 | } |
| 901 | let compaction_id = format!("compact_{}", &uuid::Uuid::new_v4().to_string()[..8]); |
| 902 | turn.stop_diagnostics.automatic_compaction_attempts = turn |
| 903 | .stop_diagnostics |
| 904 | .automatic_compaction_attempts |
| 905 | .saturating_add(1); |
| 906 | let compaction_cancel = self |
| 907 | .claim_compaction(&compaction_id) |
| 908 | .expect("a fresh automatic compaction id cannot be pre-canceled"); |
| 909 | self.emit_compaction_started( |
| 910 | compaction_id.clone(), |
| 911 | true, |
| 912 | "Making room…".to_string(), |
| 913 | self.session.snapshot_source.clone(), |
| 914 | ) |
| 915 | .await; |
| 916 | let auto_messages_before = self.session.messages.len(); |
| 917 | let auto_tokens_before = self.estimated_input_tokens(); |
| 918 | let turn_cancel = self.cancel_token.clone(); |
| 919 | let started = Instant::now(); |
| 920 | let mut compaction_usage = Usage::default(); |
| 921 | let threshold_tokens = prepared.config.token_threshold; |
| 922 | let compaction_window_tokens = prepared.config.effective_context_window; |
| 923 | let calibration = turn.input_token_ratio; |
| 924 | let pass = |
| 925 | |path: Option<crate::compaction::CompactionPath>, usage: Usage| CompactionPass { |
| 926 | trigger: "auto", |
| 927 | path, |
| 928 | messages_before: auto_messages_before, |
| 929 | messages_after: None, |
| 930 | tokens_before: auto_tokens_before, |
| 931 | threshold_tokens, |
| 932 | configured_threshold_tokens: threshold_tokens, |
| 933 | usage, |
| 934 | elapsed_ms: elapsed_millis(started), |
| 935 | reported_input_tokens, |
| 936 | gate_input_tokens: billed_input_tokens, |
| 937 | calibration, |
| 938 | compaction_window_tokens, |
| 939 | }; |
| 940 | // Parked: the compaction pass owns its own bound. |
| 941 | self.turn_heartbeat |
| 942 | .enter(super::turn_heartbeat::TurnPhase::Compacting, None, None); |
| 943 | let (compaction_result, turn_was_canceled) = tokio::select! { |
| 944 | biased; |
| 945 | _ = turn_cancel.cancelled() => (None, true), |
| 946 | _ = compaction_cancel.cancelled() => (None, false), |
| 947 | result = compact_messages_safe( |
| 948 | client, |
| 949 | &self.session.messages, |
| 950 | self.session.system_prompt.as_ref(), |
| 951 | &prepared, |
| 952 | &mut compaction_usage, |
| 953 | ) => (Some(result), false), |
| 954 | }; |
| 955 | turn.add_usage(&compaction_usage); |
| 956 | self.emit_compaction_usage(&compaction_usage, started.elapsed()) |
| 957 | .await; |
| 958 | let Some(compaction_result) = compaction_result else { |
| 959 | *auto_compaction_suppressed = true; |
| 960 | self.finish_compaction(&compaction_id); |
| 961 | let message = if turn_was_canceled { |
| 962 | "Making room stopped with the turn; the conversation was not changed" |
| 963 | } else { |
| 964 | "Making room stopped; the conversation was not changed" |
| 965 | } |
| 966 | .to_string(); |
| 967 | self.emit_compaction_cancelled( |
| 968 | compaction_id, |
| 969 | true, |
| 970 | message, |
| 971 | pass(None, compaction_usage.clone()), |
| 972 | ) |
| 973 | .await; |
| 974 | if turn_was_canceled { |
| 975 | return AutoCompactionStep::EndTurn(TurnOutcomeStatus::Interrupted, None); |
| 976 | } |
| 977 | return AutoCompactionStep::Restart; |
| 978 | }; |
| 979 | |
| 980 | match compaction_result { |
| 981 | Ok(mut result) => { |
| 982 | // Only update if we got valid messages (never corrupt state) |
| 983 | let path = result.coverage.path; |
| 984 | if !result.messages.is_empty() || self.session.messages.is_empty() { |
| 985 | self.append_compaction_agent_topology(&mut result.messages) |
| 986 | .await; |
| 987 | let turn_was_canceled = turn_cancel.is_cancelled(); |
| 988 | if turn_was_canceled || compaction_cancel.is_cancelled() { |
| 989 | *auto_compaction_suppressed = true; |
| 990 | self.finish_compaction(&compaction_id); |
| 991 | let message = if turn_was_canceled { |
| 992 | "Making room stopped with the turn; the conversation was not changed" |
| 993 | } else { |
| 994 | "Making room stopped; the conversation was not changed" |
| 995 | } |
| 996 | .to_string(); |
| 997 | self.emit_compaction_cancelled( |
| 998 | compaction_id, |
| 999 | true, |
| 1000 | message, |
| 1001 | pass(Some(path), compaction_usage.clone()), |
| 1002 | ) |
| 1003 | .await; |
| 1004 | if turn_was_canceled { |
| 1005 | return AutoCompactionStep::EndTurn( |
| 1006 | TurnOutcomeStatus::Interrupted, |
| 1007 | None, |
| 1008 | ); |
| 1009 | } |
| 1010 | return AutoCompactionStep::Restart; |
| 1011 | } |
| 1012 | let auto_messages_after = result.messages.len(); |
| 1013 | let retries_used = result.retries_used; |
| 1014 | let coverage_clause = result.coverage.receipt_clause(); |
| 1015 | if let Some(job) = self.child_job() |
| 1016 | && let Err(error) = job |
| 1017 | .before_replace(&self.session.messages, &result.messages) |
| 1018 | .await |
| 1019 | { |
| 1020 | return AutoCompactionStep::EndTurn( |
| 1021 | TurnOutcomeStatus::Failed, |
| 1022 | Some(format!("child compaction projection failed: {error:#}")), |
| 1023 | ); |
| 1024 | } |
| 1025 | self.session.replace_messages(result.messages); |
| 1026 | turn.clear_parent_input_tokens(); |
| 1027 | self.session.latest_parent_input_tokens = None; |
| 1028 | turn.last_compaction_step = Some(turn.step); |
| 1029 | if let Some(pm) = self.session.prefix_stability.as_mut() { |
| 1030 | pm.note_history_reset("compaction"); |
| 1031 | } |
| 1032 | self.commit_compaction_checkpoint(result.summary_prompt); |
| 1033 | *auto_compaction_suppressed = |
| 1034 | crate::compaction::compaction_pressure_reached( |
| 1035 | &self.session.messages, |
| 1036 | self.session.system_prompt.as_ref(), |
| 1037 | &self.config.compaction, |
| 1038 | ); |
| 1039 | self.emit_session_updated().await; |
| 1040 | let removed = auto_messages_before.saturating_sub(auto_messages_after); |
| 1041 | let auto_tokens_after = self.estimated_input_tokens(); |
| 1042 | let status = if retries_used > 0 { |
| 1043 | format!( |
| 1044 | "Made room: {auto_messages_before} → {auto_messages_after} messages ({removed} removed, {retries_used} retries), ~{auto_tokens_before} → ~{auto_tokens_after} tokens ({coverage_clause})" |
| 1045 | ) |
| 1046 | } else { |
| 1047 | format!( |
| 1048 | "Made room: {auto_messages_before} → {auto_messages_after} messages ({removed} removed), ~{auto_tokens_before} → ~{auto_tokens_after} tokens ({coverage_clause})" |
| 1049 | ) |
| 1050 | }; |
| 1051 | let mut pass = pass(Some(path), compaction_usage.clone()); |
| 1052 | pass.messages_after = Some(auto_messages_after); |
| 1053 | self.emit_compaction_completed( |
| 1054 | compaction_id.clone(), |
| 1055 | true, |
| 1056 | status.clone(), |
| 1057 | pass, |
| 1058 | ) |
| 1059 | .await; |
| 1060 | } else { |
| 1061 | *auto_compaction_suppressed = true; |
| 1062 | let message = |
| 1063 | "Making room skipped: the summary came back empty".to_string(); |
| 1064 | self.emit_compaction_failed( |
| 1065 | compaction_id.clone(), |
| 1066 | true, |
| 1067 | message.clone(), |
| 1068 | pass(Some(path), compaction_usage.clone()), |
| 1069 | ) |
| 1070 | .await; |
| 1071 | let _ = self.send_event(Event::status(message)).await; |
| 1072 | } |
| 1073 | } |
| 1074 | Err(err) => { |
| 1075 | *auto_compaction_suppressed = true; |
| 1076 | self.learn_summary_image_cap(&prepared, &err); |
| 1077 | let message = crate::compaction::report_compaction_failure( |
| 1078 | "Making room failed", |
| 1079 | &compaction_id, |
| 1080 | true, |
| 1081 | &err, |
| 1082 | ); |
| 1083 | self.emit_compaction_failed( |
| 1084 | compaction_id.clone(), |
| 1085 | true, |
| 1086 | message.clone(), |
| 1087 | pass(None, compaction_usage.clone()), |
| 1088 | ) |
| 1089 | .await; |
| 1090 | let _ = self.send_event(Event::status(message.clone())).await; |
| 1091 | self.finish_compaction(&compaction_id); |
| 1092 | return AutoCompactionStep::EndTurn(TurnOutcomeStatus::Failed, Some(message)); |
| 1093 | } |
| 1094 | } |
| 1095 | self.finish_compaction(&compaction_id); |
| 1096 | // C02-06: a compaction pass has its own bound, not the |
| 1097 | // turn's. Recheck the wall clock before it can authorize the |
| 1098 | // provider request that follows this phase. |
| 1099 | if let Some(error) = self.turn_wall_clock_exhausted_error() { |
| 1100 | self.post_turn_budget_stop(&error).await; |
| 1101 | return AutoCompactionStep::EndTurn(TurnOutcomeStatus::Failed, Some(error)); |
| 1102 | } |
| 1103 | } |
| 1104 | AutoCompactionStep::Proceed |
| 1105 | } |
| 1106 | |
| 1107 | pub(super) async fn report_context_recovery_failure( |
| 1108 | &mut self, |
| 1109 | turn: &mut TurnContext, |
| 1110 | ) -> Option<String> { |
| 1111 | let rejection = turn.context_recovery_rejection.take()?; |
| 1112 | let message = |
| 1113 | self.decorate_auth_error_message(super::turn_loop::initial_stream_error_user_message( |
| 1114 | &self.config.locale_tag, |
| 1115 | &rejection, |
| 1116 | )); |
| 1117 | let envelope = |
| 1118 | crate::llm_error_envelope::envelope_for_llm_error(rejection, message.clone()); |
| 1119 | let _ = self.send_event(Event::error(envelope)).await; |
| 1120 | Some(message) |
| 1121 | } |
| 1122 | |
| 1123 | pub(super) async fn recover_context_overflow( |
| 1124 | &mut self, |
| 1125 | client: &dyn crate::core::model_client::ModelClient, |
| 1126 | tools: Option<&[Tool]>, |
| 1127 | reason: &str, |
| 1128 | turn: &mut TurnContext, |
| 1129 | ) -> bool { |
| 1130 | if !self.config.compaction.enabled { |
| 1131 | let message = "Automatic compaction is disabled. The request exceeds the context budget; the conversation was preserved. Choose a larger context route, shorten the new input, or compact explicitly before retrying.".to_string(); |
| 1132 | turn.context_recovery_rejection = |
| 1133 | Some(crate::llm_client::LlmError::ContextLengthError(message).into()); |
| 1134 | self.record_compaction_event( |
| 1135 | "compaction.refused", |
| 1136 | serde_json::json!({ |
| 1137 | "trigger": reason, |
| 1138 | "reason": "automatic_compaction_disabled", |
| 1139 | "messages": self.session.messages.len(), |
| 1140 | }), |
| 1141 | ) |
| 1142 | .await; |
| 1143 | return false; |
| 1144 | } |
| 1145 | let Some(target_budget) = crate::route_budget::route_context_budget_with_window( |
| 1146 | self.api_provider, |
| 1147 | &self.session.model, |
| 1148 | self.active_route_limits, |
| 1149 | self.active_context_window.map(|window| window.tokens), |
| 1150 | 0, |
| 1151 | ) |
| 1152 | .and_then(|budget| usize::try_from(budget.available_input_tokens).ok()) else { |
| 1153 | return false; |
| 1154 | }; |
| 1155 | if let Some(message) = turn.compaction_thrash_message() { |
| 1156 | turn.context_recovery_rejection = Some(anyhow::anyhow!(message)); |
| 1157 | return false; |
| 1158 | } |
| 1159 | // Nothing to summarize or prune: a pass cannot help, so do not make |
| 1160 | // the user wait on a model call before the failure the caller will |
| 1161 | // report anyway. |
| 1162 | if !crate::compaction::has_compactable_history(&self.session.messages) { |
| 1163 | return false; |
| 1164 | } |
| 1165 | |
| 1166 | let audit_started = Instant::now(); |
| 1167 | let id = format!("compact_{}", &uuid::Uuid::new_v4().to_string()[..8]); |
| 1168 | turn.stop_diagnostics.emergency_compaction_attempts = turn |
| 1169 | .stop_diagnostics |
| 1170 | .emergency_compaction_attempts |
| 1171 | .saturating_add(1); |
| 1172 | let start_message = format!("Making room now ({reason})"); |
| 1173 | self.emit_compaction_started( |
| 1174 | id.clone(), |
| 1175 | true, |
| 1176 | start_message, |
| 1177 | self.session.snapshot_source.clone(), |
| 1178 | ) |
| 1179 | .await; |
| 1180 | let Some(compaction_cancel) = self.claim_compaction(&id) else { |
| 1181 | let messages_before = self.session.messages.len(); |
| 1182 | let tokens_before = self.estimated_input_tokens(); |
| 1183 | let reported_input_tokens = |
| 1184 | turn.billed_input_tokens_for_compaction(self.session.latest_parent_input_tokens); |
| 1185 | let calibration = turn.input_token_ratio; |
| 1186 | let threshold_tokens = self.config.compaction.token_threshold; |
| 1187 | let compaction_window_tokens = self.config.compaction.effective_context_window; |
| 1188 | self.emit_compaction_cancelled( |
| 1189 | id, |
| 1190 | true, |
| 1191 | "Making room stopped before it started; the conversation was not changed" |
| 1192 | .to_string(), |
| 1193 | CompactionPass { |
| 1194 | trigger: "emergency", |
| 1195 | path: None, |
| 1196 | messages_before, |
| 1197 | messages_after: None, |
| 1198 | tokens_before, |
| 1199 | threshold_tokens, |
| 1200 | configured_threshold_tokens: threshold_tokens, |
| 1201 | usage: Usage::default(), |
| 1202 | elapsed_ms: elapsed_millis(audit_started), |
| 1203 | reported_input_tokens, |
| 1204 | gate_input_tokens: None, |
| 1205 | calibration, |
| 1206 | compaction_window_tokens, |
| 1207 | }, |
| 1208 | ) |
| 1209 | .await; |
| 1210 | return false; |
| 1211 | }; |
| 1212 | let turn_cancel = self.cancel_token.clone(); |
| 1213 | |
| 1214 | // Measured with the estimator `after_tokens` and the preflight guard |
| 1215 | // use, so `recovered` compares like with like and the receipt reads |
| 1216 | // ~before → ~after on one scale. |
| 1217 | let before_tokens = |
| 1218 | turn.calibrated_input_tokens(crate::compaction::estimate_request_input_tokens( |
| 1219 | &self.session.messages, |
| 1220 | self.session.system_prompt.as_ref(), |
| 1221 | tools, |
| 1222 | )); |
| 1223 | let before_count = self.session.messages.len(); |
| 1224 | let configured_threshold_tokens = self.config.compaction.token_threshold; |
| 1225 | |
| 1226 | let mut forced_config = self.config.compaction.clone(); |
| 1227 | forced_config.enabled = true; |
| 1228 | forced_config.token_threshold = forced_config |
| 1229 | .token_threshold |
| 1230 | .min(target_budget.saturating_sub(1)) |
| 1231 | .max(1); |
| 1232 | let mut prepared = self.prepare_compaction_envelope(forced_config); |
| 1233 | prepared.input_token_ratio = turn.input_token_ratio; |
| 1234 | prepared.tools = tools.map(<[Tool]>::to_vec); |
| 1235 | |
| 1236 | let started = Instant::now(); |
| 1237 | let mut compaction_usage = Usage::default(); |
| 1238 | let threshold_tokens = prepared.config.token_threshold; |
| 1239 | let compaction_window_tokens = prepared.config.effective_context_window; |
| 1240 | let calibration = turn.input_token_ratio; |
| 1241 | let reported_input_tokens = |
| 1242 | turn.billed_input_tokens_for_compaction(self.session.latest_parent_input_tokens); |
| 1243 | let gate_input_tokens = u64::try_from(before_tokens).ok(); |
| 1244 | let pass = |path: Option<crate::compaction::CompactionPath>, usage: Usage| CompactionPass { |
| 1245 | trigger: "emergency", |
| 1246 | path, |
| 1247 | messages_before: before_count, |
| 1248 | messages_after: None, |
| 1249 | tokens_before: before_tokens, |
| 1250 | threshold_tokens, |
| 1251 | configured_threshold_tokens, |
| 1252 | usage, |
| 1253 | elapsed_ms: elapsed_millis(started), |
| 1254 | reported_input_tokens, |
| 1255 | gate_input_tokens, |
| 1256 | calibration, |
| 1257 | compaction_window_tokens, |
| 1258 | }; |
| 1259 | let (compaction_result, turn_was_canceled) = tokio::select! { |
| 1260 | biased; |
| 1261 | _ = turn_cancel.cancelled() => (None, true), |
| 1262 | _ = compaction_cancel.cancelled() => (None, false), |
| 1263 | result = compact_messages_safe( |
| 1264 | client, |
| 1265 | &self.session.messages, |
| 1266 | self.session.system_prompt.as_ref(), |
| 1267 | &prepared, |
| 1268 | &mut compaction_usage, |
| 1269 | ) => (Some(result), false), |
| 1270 | }; |
| 1271 | turn.add_usage(&compaction_usage); |
| 1272 | self.emit_compaction_usage(&compaction_usage, started.elapsed()) |
| 1273 | .await; |
| 1274 | let Some(compaction_result) = compaction_result else { |
| 1275 | self.finish_compaction(&id); |
| 1276 | let message = if turn_was_canceled { |
| 1277 | "Making room stopped with the turn; the conversation was not changed" |
| 1278 | } else { |
| 1279 | "Making room stopped; the conversation was not changed" |
| 1280 | } |
| 1281 | .to_string(); |
| 1282 | self.emit_compaction_cancelled(id, true, message, pass(None, compaction_usage.clone())) |
| 1283 | .await; |
| 1284 | return false; |
| 1285 | }; |
| 1286 | |
| 1287 | let result = match compaction_result { |
| 1288 | Ok(result) => result, |
| 1289 | Err(err) => { |
| 1290 | if let Some(cap) = self.learn_summary_image_cap(&prepared, &err) { |
| 1291 | let message = format!( |
| 1292 | "Making room: {} refused the summary request's images; retrying with at most {cap} per request. Original conversation was preserved.", |
| 1293 | prepared.config.model |
| 1294 | ); |
| 1295 | self.emit_compaction_failed( |
| 1296 | id.clone(), |
| 1297 | true, |
| 1298 | message, |
| 1299 | pass(None, compaction_usage.clone()), |
| 1300 | ) |
| 1301 | .await; |
| 1302 | self.finish_compaction(&id); |
| 1303 | return true; |
| 1304 | } |
| 1305 | let message = if is_provider_rejection(&err) { |
| 1306 | // The turn's error line carries the provider's answer; |
| 1307 | // this receipt only closes the recovery attempt. |
| 1308 | "Context recovery stopped: the provider rejected the request. Original conversation was preserved.".to_string() |
| 1309 | } else { |
| 1310 | let reason = format!("{err:#}"); |
| 1311 | let reason = reason.trim_end().trim_end_matches('.'); |
| 1312 | if reason |
| 1313 | .to_ascii_lowercase() |
| 1314 | .contains("conversation was preserved") |
| 1315 | { |
| 1316 | format!("Context recovery failed: {reason}.") |
| 1317 | } else { |
| 1318 | format!( |
| 1319 | "Context recovery failed: {reason}. Original conversation was preserved." |
| 1320 | ) |
| 1321 | } |
| 1322 | }; |
| 1323 | if is_provider_rejection(&err) { |
| 1324 | turn.context_recovery_rejection = Some(err); |
| 1325 | } |
| 1326 | self.emit_compaction_failed( |
| 1327 | id.clone(), |
| 1328 | true, |
| 1329 | message, |
| 1330 | pass(None, compaction_usage.clone()), |
| 1331 | ) |
| 1332 | .await; |
| 1333 | self.finish_compaction(&id); |
| 1334 | return false; |
| 1335 | } |
| 1336 | }; |
| 1337 | let retries_used = result.retries_used; |
| 1338 | let summary_prompt = result.summary_prompt; |
| 1339 | let path = result.coverage.path; |
| 1340 | let mut compacted_messages = result.messages; |
| 1341 | |
| 1342 | let turn_was_canceled = turn_cancel.is_cancelled(); |
| 1343 | if turn_was_canceled || compaction_cancel.is_cancelled() { |
| 1344 | self.finish_compaction(&id); |
| 1345 | let message = if turn_was_canceled { |
| 1346 | "Making room stopped with the turn; the conversation was not changed" |
| 1347 | } else { |
| 1348 | "Making room stopped; the conversation was not changed" |
| 1349 | } |
| 1350 | .to_string(); |
| 1351 | self.emit_compaction_cancelled( |
| 1352 | id, |
| 1353 | true, |
| 1354 | message, |
| 1355 | pass(Some(path), compaction_usage.clone()), |
| 1356 | ) |
| 1357 | .await; |
| 1358 | return false; |
| 1359 | } |
| 1360 | |
| 1361 | if !compacted_messages.is_empty() || self.session.messages.is_empty() { |
| 1362 | self.append_compaction_agent_topology(&mut compacted_messages) |
| 1363 | .await; |
| 1364 | let turn_was_canceled = turn_cancel.is_cancelled(); |
| 1365 | if turn_was_canceled || compaction_cancel.is_cancelled() { |
| 1366 | self.finish_compaction(&id); |
| 1367 | let message = if turn_was_canceled { |
| 1368 | "Making room stopped with the turn; the conversation was not changed" |
| 1369 | } else { |
| 1370 | "Making room stopped; the conversation was not changed" |
| 1371 | } |
| 1372 | .to_string(); |
| 1373 | self.emit_compaction_cancelled( |
| 1374 | id, |
| 1375 | true, |
| 1376 | message, |
| 1377 | pass(Some(path), compaction_usage.clone()), |
| 1378 | ) |
| 1379 | .await; |
| 1380 | return false; |
| 1381 | } |
| 1382 | } |
| 1383 | // Validate the complete candidate before the only history swap. Bare |
| 1384 | // front-trimming after a failed summary silently lost user state and |
| 1385 | // could leave orphan tool results in an apparently recovered session. |
| 1386 | let after_tokens = |
| 1387 | turn.calibrated_input_tokens(crate::compaction::estimate_request_input_tokens( |
| 1388 | &compacted_messages, |
| 1389 | self.session.system_prompt.as_ref(), |
| 1390 | tools, |
| 1391 | )); |
| 1392 | let after_count = compacted_messages.len(); |
| 1393 | let recovered = after_tokens <= target_budget && after_tokens < before_tokens; |
| 1394 | |
| 1395 | if recovered { |
| 1396 | if let Some(job) = self.child_job() |
| 1397 | && let Err(error) = job |
| 1398 | .before_replace(&self.session.messages, &compacted_messages) |
| 1399 | .await |
| 1400 | { |
| 1401 | self.cancel_token.cancel(); |
| 1402 | tracing::error!(%error, "child recovery projection failed; original Session retained"); |
| 1403 | return false; |
| 1404 | } |
| 1405 | self.session.replace_messages(compacted_messages); |
| 1406 | turn.clear_parent_input_tokens(); |
| 1407 | self.session.latest_parent_input_tokens = None; |
| 1408 | turn.last_compaction_step = Some(turn.step); |
| 1409 | if let Some(pm) = self.session.prefix_stability.as_mut() { |
| 1410 | pm.note_history_reset("compaction"); |
| 1411 | } |
| 1412 | self.commit_compaction_checkpoint(summary_prompt); |
| 1413 | self.emit_session_updated().await; |
| 1414 | let removed = before_count.saturating_sub(after_count); |
| 1415 | let mut details = format!( |
| 1416 | "Made room: {before_count} → {after_count} messages ({removed} removed), ~{before_tokens} → ~{after_tokens} tokens" |
| 1417 | ); |
| 1418 | if retries_used > 0 { |
| 1419 | details.push_str(&format!(" ({retries_used} retries)")); |
| 1420 | } |
| 1421 | let mut pass = pass(Some(path), compaction_usage.clone()); |
| 1422 | pass.messages_after = Some(after_count); |
| 1423 | self.emit_compaction_completed(id.clone(), true, details.clone(), pass) |
| 1424 | .await; |
| 1425 | let _ = self.send_event(Event::status(details)).await; |
| 1426 | self.finish_compaction(&id); |
| 1427 | return true; |
| 1428 | } |
| 1429 | |
| 1430 | // Two distinct failures were previously conflated into one banner. |
| 1431 | // When the provider rejected the request (its bill counts framing we |
| 1432 | // cannot see), our estimate may already sit within the budget while |
| 1433 | // the pass removed nothing — reporting that as "failed to reduce |
| 1434 | // below model limit" with an estimate printed *under* the budget |
| 1435 | // reads as self-contradictory. Name the actual outcome instead. |
| 1436 | let message = if after_tokens > target_budget { |
| 1437 | format!( |
| 1438 | "Making room failed: the request is still over the model limit \ |
| 1439 | (estimate ~{after_tokens} tokens, budget ~{target_budget}). Original conversation was preserved." |
| 1440 | ) |
| 1441 | } else { |
| 1442 | format!( |
| 1443 | "Making room made no progress (estimate ~{after_tokens} tokens \ |
| 1444 | is already within the ~{target_budget} budget; the provider may count the \ |
| 1445 | request differently). Original conversation was preserved." |
| 1446 | ) |
| 1447 | }; |
| 1448 | self.emit_compaction_failed( |
| 1449 | id.clone(), |
| 1450 | true, |
| 1451 | message.clone(), |
| 1452 | pass(Some(path), compaction_usage.clone()), |
| 1453 | ) |
| 1454 | .await; |
| 1455 | let _ = self.send_event(Event::status(message)).await; |
| 1456 | self.finish_compaction(&id); |
| 1457 | false |
| 1458 | } |
| 1459 | |
| 1460 | /// Keep the rendered checkpoint for host persistence and repeat-compaction |
| 1461 | /// metadata. The model sees the checkpoint exactly once through ordinary |
| 1462 | /// conversation history; the stable system prefix never carries it. |
| 1463 | pub(super) fn commit_compaction_checkpoint(&mut self, summary_prompt: Option<SystemPrompt>) { |
| 1464 | let Some(summary_prompt) = summary_prompt else { |
| 1465 | return; |
| 1466 | }; |
| 1467 | self.session.compaction_summary_prompt = Some(summary_prompt); |
| 1468 | } |
| 1469 | |
| 1470 | /// Capture the current session-owned Agent topology at the replacement |
| 1471 | /// history boundary. This is the Codewhale equivalent of Codex clearing |
| 1472 | /// its world-state reference after standalone compaction so the next turn |
| 1473 | /// receives fresh environment/subagent context instead of trusting the |
| 1474 | /// narrative summary as live process state. |
| 1475 | pub(super) async fn append_compaction_agent_topology(&self, messages: &mut Vec<Message>) { |
| 1476 | let snapshots = { |
| 1477 | let manager = self.subagent_manager.read().await; |
| 1478 | manager.list_for_session(&self.session.id) |
| 1479 | }; |
| 1480 | crate::runtime_handoff::replace_agent_topology_checkpoint(messages, &snapshots); |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | fn compaction_audit_details( |
| 1485 | outcome: &'static str, |
| 1486 | id: &str, |
| 1487 | pass: &CompactionPass, |
| 1488 | estimated_tokens_after: Option<u64>, |
| 1489 | reduction_ratio: Option<f64>, |
| 1490 | ) -> serde_json::Value { |
| 1491 | serde_json::json!({ |
| 1492 | "compaction_id": id, |
| 1493 | "trigger": pass.trigger, |
| 1494 | "outcome": outcome, |
| 1495 | "path": pass.path.map(|path| match path { |
| 1496 | crate::compaction::CompactionPath::Summary => "summary", |
| 1497 | crate::compaction::CompactionPath::PruneOnly => "pruning_only", |
| 1498 | }), |
| 1499 | "messages_before": pass.messages_before, |
| 1500 | "messages_after": pass.messages_after, |
| 1501 | "estimated_tokens_before": pass.tokens_before, |
| 1502 | "estimated_tokens_after": estimated_tokens_after, |
| 1503 | "threshold_tokens": pass.threshold_tokens, |
| 1504 | "configured_threshold_tokens": pass.configured_threshold_tokens, |
| 1505 | "summarizer_usage": &pass.usage, |
| 1506 | "reduction_ratio": reduction_ratio, |
| 1507 | "elapsed_ms": pass.elapsed_ms, |
| 1508 | "reported_input_tokens": pass.reported_input_tokens, |
| 1509 | "gate_input_tokens": pass.gate_input_tokens, |
| 1510 | "calibration": { |
| 1511 | "numerator": pass.calibration.0, |
| 1512 | "denominator": pass.calibration.1, |
| 1513 | }, |
| 1514 | "compaction_window_tokens": pass.compaction_window_tokens, |
| 1515 | }) |
| 1516 | } |
| 1517 | |
| 1518 | fn elapsed_millis(started: Instant) -> u64 { |
| 1519 | u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX) |
| 1520 | } |
| 1521 | |
| 1522 | /// A context-recovery failure that came from the provider refusing the |
| 1523 | /// request (capability, auth, reachability, quota) rather than from the |
| 1524 | /// summary itself. Context-length rejections are excluded: those really are |
| 1525 | /// the budget problem the caller already reports. |
| 1526 | pub(super) fn is_provider_rejection(err: &anyhow::Error) -> bool { |
| 1527 | use codewhale_error_taxonomy::{ErrorCategory, classify_error_message}; |
| 1528 | let text = format!("{err:#}"); |
| 1529 | if super::context::is_context_length_error_message(&text) |
| 1530 | || matches!( |
| 1531 | err.downcast_ref::<crate::llm_client::LlmError>(), |
| 1532 | Some(crate::llm_client::LlmError::ContextLengthError(_)) |
| 1533 | ) |
| 1534 | { |
| 1535 | return false; |
| 1536 | } |
| 1537 | err.downcast_ref::<crate::llm_client::LlmError>().is_some() |
| 1538 | || matches!( |
| 1539 | classify_error_message(&text), |
| 1540 | ErrorCategory::Authentication |
| 1541 | | ErrorCategory::Authorization |
| 1542 | | ErrorCategory::Network |
| 1543 | | ErrorCategory::RateLimit |
| 1544 | | ErrorCategory::Timeout |
| 1545 | ) |
| 1546 | } |
| 1547 | |
| 1548 | #[cfg(test)] |
| 1549 | mod tests { |
| 1550 | use super::*; |
| 1551 | use crate::compaction::CompactionNoticeSink as _; |
| 1552 | |
| 1553 | /// The engine sink is the one link between a compaction downgrade and the |
| 1554 | /// person watching: the notice must land on the status line, not only in |
| 1555 | /// the log. |
| 1556 | #[tokio::test] |
| 1557 | async fn compaction_notice_sink_delivers_a_status_event() { |
| 1558 | let (tx, mut rx) = mpsc::channel(4); |
| 1559 | let sink = EngineCompactionNoticeSink { |
| 1560 | tx, |
| 1561 | child: None, |
| 1562 | origin: None, |
| 1563 | }; |
| 1564 | sink.notice("Making room re-encoded 2 inline image(s)".to_string()); |
| 1565 | match rx.recv().await { |
| 1566 | Some(Event::Status { message }) => { |
| 1567 | assert!(message.contains("re-encoded"), "{message}"); |
| 1568 | } |
| 1569 | other => panic!("expected a Status event, got {other:?}"), |
| 1570 | } |
| 1571 | } |
| 1572 | #[tokio::test] |
| 1573 | async fn compaction_forwards_blocking_tool_projection_warning() { |
| 1574 | let client = crate::llm_client::mock::MockLlmClient::new(vec![]); |
| 1575 | let mut reply: codewhale_models::MessageResponse = |
| 1576 | serde_json::from_value(serde_json::json!({ |
| 1577 | "id": "summary", "type": "message", "role": "assistant", "model": "test", |
| 1578 | "content": [{"type": "text", "text": "Continue repairing the parser."}], |
| 1579 | "usage": {"input_tokens": 8, "output_tokens": 4} |
| 1580 | })) |
| 1581 | .unwrap(); |
| 1582 | reply.tool_projection_warning = Some(codewhale_models::ToolProjectionWarning { |
| 1583 | provider: "Moonshot".into(), |
| 1584 | omitted_tool_names: vec!["schema_tool".into()], |
| 1585 | omitted_tool_count: 1, |
| 1586 | }); |
| 1587 | client.push_message_response(reply); |
| 1588 | let (tx, mut rx) = mpsc::channel(4); |
| 1589 | let mut prepared = crate::compaction::PreparedCompactionEnvelope::new( |
| 1590 | crate::compaction::CompactionConfig::default(), |
| 1591 | ); |
| 1592 | prepared.notice_sink = Some(Arc::new(EngineCompactionNoticeSink { |
| 1593 | tx, |
| 1594 | child: None, |
| 1595 | origin: None, |
| 1596 | })); |
| 1597 | let history = [serde_json::from_value(serde_json::json!({ |
| 1598 | "role": "user", "content": [{"type": "text", "text": "Repair the parser."}] |
| 1599 | })) |
| 1600 | .unwrap()]; |
| 1601 | crate::compaction::compact_messages_safe( |
| 1602 | &client, |
| 1603 | &history, |
| 1604 | None, |
| 1605 | &prepared, |
| 1606 | &mut Usage::default(), |
| 1607 | ) |
| 1608 | .await |
| 1609 | .unwrap(); |
| 1610 | assert!(matches!(rx.try_recv(), Ok(Event::ToolProjectionWarning { |
| 1611 | provider, omitted_tool_names, omitted_tool_count: 1, |
| 1612 | }) if provider == "Moonshot" && omitted_tool_names == ["schema_tool"])); |
| 1613 | assert!(rx.try_recv().is_err()); |
| 1614 | } |
| 1615 | } |
| 1616 |