vtcode_core/core/agent/state/
mod.rs1use crate::llm::provider::Message;
2use hashbrown::{HashMap, HashSet};
3use std::sync::Arc;
4use std::time::Duration;
5use vtcode_macros::StringNewtype;
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash, StringNewtype)]
13pub struct ToolCallId(String);
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum OutputStatus {
18 Success,
19 Failed,
20 Canceled,
21 Timeout,
22}
23
24impl OutputStatus {
25 pub fn as_str(&self) -> &'static str {
27 match self {
28 Self::Success => "success",
29 Self::Failed => "failed",
30 Self::Canceled => "canceled",
31 Self::Timeout => "timeout",
32 }
33 }
34}
35
36#[derive(Debug, Clone)]
38pub enum PairableHistoryItem {
39 ToolCall { call_id: ToolCallId, tool_name: String },
41 ToolOutput { call_id: ToolCallId, status: OutputStatus },
43}
44
45#[derive(Debug, Clone)]
47pub struct MissingOutput {
48 pub call_id: ToolCallId,
49 pub tool_name: String,
50}
51
52#[derive(Debug, Default, Clone)]
54pub struct HistoryValidationReport {
55 pub missing_outputs: Vec<MissingOutput>,
57 pub orphan_outputs: Vec<ToolCallId>,
59}
60
61impl HistoryValidationReport {
62 pub fn is_valid(&self) -> bool {
64 self.missing_outputs.is_empty() && self.orphan_outputs.is_empty()
65 }
66
67 pub fn summary(&self) -> String {
69 if self.is_valid() {
70 "History invariants are valid".to_string()
71 } else {
72 format!("{} missing outputs, {} orphan outputs", self.missing_outputs.len(), self.orphan_outputs.len())
73 }
74 }
75
76 pub fn exclude_pending(&mut self, is_pending: impl Fn(&str) -> bool) {
83 self.missing_outputs.retain(|m| !is_pending(m.call_id.as_str()));
84 }
85}
86
87#[cfg(test)]
88#[inline]
89pub(crate) fn record_turn_duration(
90 turn_durations: &mut Vec<u128>,
91 turn_total_ms: &mut u128,
92 turn_max_ms: &mut u128,
93 turn_count: &mut usize,
94 recorded: &mut bool,
95 start: &std::time::Instant,
96) {
97 if !*recorded {
98 let duration_ms = start.elapsed().as_millis();
99 turn_durations.push(duration_ms);
100 *turn_total_ms += duration_ms;
101 if duration_ms > *turn_max_ms {
102 *turn_max_ms = duration_ms;
103 }
104 *turn_count += 1;
105 *recorded = true;
106 }
107}
108
109pub struct ApiFailureTracker {
111 pub consecutive_failures: u32,
112 pub last_failure: Option<std::time::Instant>,
113}
114
115impl Default for ApiFailureTracker {
116 fn default() -> Self {
117 Self::new()
118 }
119}
120
121impl ApiFailureTracker {
122 pub fn new() -> Self {
123 Self { consecutive_failures: 0, last_failure: None }
124 }
125
126 pub fn record_failure(&mut self) {
127 self.consecutive_failures += 1;
128 self.last_failure = Some(std::time::Instant::now());
129 }
130
131 pub fn reset(&mut self) {
132 self.consecutive_failures = 0;
133 self.last_failure = None;
134 }
135
136 pub fn should_circuit_break(&self) -> bool {
137 self.consecutive_failures >= 3
138 }
139
140 pub fn backoff_duration(&self) -> Duration {
141 let base_ms = 1000;
142 let max_ms = 30000;
143 let backoff_ms = base_ms * 2_u64.pow(self.consecutive_failures.saturating_sub(1));
144 Duration::from_millis(backoff_ms.min(max_ms))
145 }
146}
147
148pub fn summarize_list(items: &[String]) -> String {
149 const MAX_ITEMS: usize = 5;
150 if items.is_empty() {
151 return "none".into();
152 }
153 let shown: Vec<&str> = items.iter().take(MAX_ITEMS).map(|s| s.as_str()).collect();
154 if items.len() > MAX_ITEMS {
155 format!("{} [+{} more]", shown.join(", "), items.len() - MAX_ITEMS)
156 } else {
157 shown.join(", ")
158 }
159}
160
161pub fn validate_history_invariants(messages: &[Message]) -> HistoryValidationReport {
167 let mut call_map: HashMap<String, String> = HashMap::new();
168 let mut output_ids: HashSet<String> = HashSet::new();
169
170 for msg in messages {
172 if let Some(tool_calls) = &msg.tool_calls {
174 for tool_call in tool_calls {
175 call_map.insert(tool_call.id.clone(), msg.role.to_string());
176 }
177 }
178
179 if let Some(tool_call_id) = &msg.tool_call_id {
181 output_ids.insert(tool_call_id.clone());
182 }
183 }
184
185 let missing_outputs: Vec<_> = call_map
187 .keys()
188 .filter(|call_id| !output_ids.contains(*call_id))
189 .map(|call_id| MissingOutput {
190 call_id: ToolCallId::new(call_id.clone()),
191 tool_name: "unknown".to_string(),
192 })
193 .collect();
194
195 let orphan_outputs: Vec<_> = output_ids
197 .iter()
198 .filter(|output_id| !call_map.contains_key(*output_id))
199 .map(|output_id| ToolCallId::new(output_id.clone()))
200 .collect();
201
202 HistoryValidationReport { missing_outputs, orphan_outputs }
203}
204
205const REQUEST_HISTORY_CANCELLATION_RESULT: &str =
206 "canceled: no tool result was recorded; this bounded placeholder preserves the tool-call protocol.";
207const REQUEST_HISTORY_AMBIGUOUS_RESULT: &str = "unattributed: multiple outstanding tool calls shared an ID, so their recorded results cannot be safely assigned; original results remain in session history.";
208const REQUEST_HISTORY_EMPTY_ID_RESULT: &str = "unattributed: the tool call had an empty ID, so no result can be safely matched; original history remains available.";
209
210#[derive(Debug)]
211struct MatchedRequestToolResult {
212 message_index: usize,
213 call_index: usize,
214}
215
216#[derive(Debug)]
217struct RequestToolBatch {
218 assistant_index: usize,
219 matched_calls: Vec<bool>,
220 results: Vec<MatchedRequestToolResult>,
221}
222
223#[derive(Debug, Default)]
224struct RequestHistoryAnalysis {
225 batches: Vec<RequestToolBatch>,
226 batch_by_assistant_index: HashMap<usize, usize>,
227 result_batch_by_index: HashMap<usize, usize>,
228 invalid_result_indices: HashSet<usize>,
229 duplicate_call_ids: HashSet<String>,
230 has_empty_call_id: bool,
231 ambiguous_calls: HashSet<(usize, usize)>,
232}
233
234impl RequestHistoryAnalysis {
235 fn needs_repair(&self) -> bool {
236 if !self.invalid_result_indices.is_empty() || !self.duplicate_call_ids.is_empty() || self.has_empty_call_id {
237 return true;
238 }
239
240 self.batches.iter().any(|batch| {
241 batch.matched_calls.iter().any(|matched| !matched)
242 || batch
243 .results
244 .iter()
245 .enumerate()
246 .any(|(offset, result)| result.message_index != batch.assistant_index + offset + 1)
247 })
248 }
249}
250
251fn analyze_request_history(messages: &[Message]) -> RequestHistoryAnalysis {
252 let mut analysis = RequestHistoryAnalysis::default();
253 let mut calls_by_id: HashMap<&str, Vec<(usize, usize)>> = HashMap::new();
254
255 for (message_index, message) in messages.iter().enumerate() {
256 if message.role != crate::llm::provider::MessageRole::Assistant {
257 continue;
258 }
259
260 let Some(tool_calls) = message.tool_calls.as_ref().filter(|calls| !calls.is_empty()) else {
261 continue;
262 };
263
264 let batch_index = analysis.batches.len();
265 let matched_calls = vec![false; tool_calls.len()];
266 analysis.batch_by_assistant_index.insert(message_index, batch_index);
267 analysis.batches.push(RequestToolBatch {
268 assistant_index: message_index,
269 matched_calls,
270 results: Vec::new(),
271 });
272
273 for (call_index, call) in tool_calls.iter().enumerate() {
274 analysis.has_empty_call_id |= call.id.is_empty();
275 calls_by_id.entry(call.id.as_str()).or_default().push((batch_index, call_index));
276 }
277 }
278
279 analysis.duplicate_call_ids = calls_by_id
280 .iter()
281 .filter(|(_, calls)| calls.len() > 1)
282 .map(|(id, _)| (*id).to_owned())
283 .collect();
284
285 for (message_index, message) in messages.iter().enumerate() {
286 let has_tool_call_id = message.tool_call_id.is_some();
287 let is_tool_result = message.role == crate::llm::provider::MessageRole::Tool;
288 if !is_tool_result && !has_tool_call_id {
289 continue;
290 }
291
292 let Some(tool_call_id) = message.tool_call_id.as_deref().filter(|id| !id.is_empty()) else {
293 analysis.invalid_result_indices.insert(message_index);
294 continue;
295 };
296
297 if !is_tool_result {
298 analysis.invalid_result_indices.insert(message_index);
299 continue;
300 }
301
302 let Some(candidates) = calls_by_id.get_mut(tool_call_id) else {
303 analysis.invalid_result_indices.insert(message_index);
304 continue;
305 };
306
307 let mut eligible = candidates.iter().copied().filter(|&(batch_index, call_index)| {
308 analysis.batches[batch_index].assistant_index < message_index
309 && !analysis.batches[batch_index].matched_calls[call_index]
310 });
311 let Some((batch_index, call_index)) = eligible.next() else {
312 analysis.invalid_result_indices.insert(message_index);
314 continue;
315 };
316 if let Some(second) = eligible.next() {
317 analysis.ambiguous_calls.insert((batch_index, call_index));
320 analysis.ambiguous_calls.insert(second);
321 analysis.ambiguous_calls.extend(eligible);
322 analysis.invalid_result_indices.insert(message_index);
323 continue;
324 }
325
326 analysis.batches[batch_index].matched_calls[call_index] = true;
327 analysis.batches[batch_index]
328 .results
329 .push(MatchedRequestToolResult { message_index, call_index });
330 analysis.result_batch_by_index.insert(message_index, batch_index);
331 }
332
333 analysis
334}
335
336pub fn request_history_needs_normalization(messages: &[Message]) -> bool {
341 analyze_request_history(messages).needs_repair()
342}
343
344pub fn normalize_history_for_request_shared(messages: Arc<Vec<Message>>) -> Arc<Vec<Message>> {
355 let analysis = analyze_request_history(&messages);
356 if !analysis.needs_repair() {
357 return messages;
358 }
359
360 let mut normalized = Vec::with_capacity(messages.len());
361 let mut used_ids: HashSet<String> = messages
362 .iter()
363 .flat_map(|message| message.tool_calls.iter().flatten().map(|call| call.id.clone()))
364 .collect();
365 let mut next_repaired_id = 0usize;
366 let mut seen_duplicate_ids = HashSet::new();
367 for (message_index, message) in messages.iter().enumerate() {
368 if analysis.invalid_result_indices.contains(&message_index)
369 || analysis.result_batch_by_index.contains_key(&message_index)
370 {
371 continue;
372 }
373
374 let Some(&batch_index) = analysis.batch_by_assistant_index.get(&message_index) else {
375 normalized.push(message.clone());
376 continue;
377 };
378
379 let batch = &analysis.batches[batch_index];
380 let mut assistant = message.clone();
381 for call in assistant.tool_calls.iter_mut().flatten() {
382 if call.id.is_empty()
383 || (analysis.duplicate_call_ids.contains(&call.id) && !seen_duplicate_ids.insert(call.id.clone()))
384 {
385 let prefix = if call.id == "harness-auto-verify" || call.id.starts_with("harness-auto-verify-") {
386 "harness-auto-verify-repaired"
387 } else {
388 "vtcode-repaired-tool-call"
389 };
390 loop {
391 let candidate = format!("{prefix}-{next_repaired_id}");
392 next_repaired_id += 1;
393 if used_ids.insert(candidate.clone()) {
394 call.id = candidate;
395 break;
396 }
397 }
398 }
399 }
400 for matched_result in &batch.results {
401 let mut result = messages[matched_result.message_index].clone();
402 if let Some(call) = assistant
403 .tool_calls
404 .as_ref()
405 .and_then(|calls| calls.get(matched_result.call_index))
406 {
407 result.tool_call_id = Some(call.id.clone());
408 }
409 normalized.push(result);
410 }
411 let result_start = normalized.len() - batch.results.len();
412 normalized.insert(result_start, assistant.clone());
413 for (call_index, (call, matched)) in assistant.tool_calls.iter().flatten().zip(&batch.matched_calls).enumerate()
414 {
415 if !matched {
416 let result = if message
417 .tool_calls
418 .as_ref()
419 .and_then(|calls| calls.get(call_index))
420 .is_some_and(|call| call.id.is_empty())
421 {
422 REQUEST_HISTORY_EMPTY_ID_RESULT
423 } else if analysis.ambiguous_calls.contains(&(batch_index, call_index)) {
424 REQUEST_HISTORY_AMBIGUOUS_RESULT
425 } else {
426 REQUEST_HISTORY_CANCELLATION_RESULT
427 };
428 normalized.push(Message::tool_response(call.id.clone(), result.to_owned()));
429 }
430 }
431 }
432
433 Arc::new(normalized)
434}
435
436pub fn normalize_history_for_request(messages: &[Message]) -> Vec<Message> {
441 Arc::unwrap_or_clone(normalize_history_for_request_shared(Arc::new(messages.to_vec())))
442}
443
444const CLEARED_TOOL_RESULT_NOTE: &str = "Older tool result cleared to bound context growth. Full output remains in session logs; re-run the tool if raw bytes are needed.";
448
449#[must_use]
453pub fn resolve_tool_result_clearing_trigger(
454 config: &crate::config::VTCodeConfig,
455 provider: &dyn crate::llm::provider::LLMProvider,
456 model: &str,
457 prompt_overhead_tokens: usize,
458 reserved_output_tokens: usize,
459) -> u64 {
460 let clearing = &config.agent.harness.tool_result_clearing;
461 if !clearing.enabled || clearing.trigger_tokens == 0 {
462 return 0;
463 }
464 let capacity = crate::compaction::effective_context_budget(Some(config), provider, model);
465 if capacity == 0 {
466 return clearing.trigger_tokens;
467 }
468 let history_budget = capacity
469 .saturating_sub(reserved_output_tokens)
470 .saturating_sub(prompt_overhead_tokens) as u64;
471 let cap = (history_budget / 5)
474 .saturating_mul(3)
475 .saturating_add((history_budget % 5) * 3 / 5)
476 .max(1);
477 clearing.trigger_tokens.min(cap)
478}
479
480pub fn clear_old_tool_results(
503 messages: &[Message],
504 trigger_tokens: u64,
505 keep_tool_uses: u32,
506 clear_at_least_tokens: u64,
507 clear_tool_inputs: bool,
508) -> Vec<Message> {
509 clear_old_tool_results_with_recent_batches(
510 messages,
511 trigger_tokens,
512 keep_tool_uses,
513 0,
514 clear_at_least_tokens,
515 clear_tool_inputs,
516 )
517}
518
519pub fn clear_old_tool_results_with_recent_batches(
523 messages: &[Message],
524 trigger_tokens: u64,
525 keep_tool_uses: u32,
526 keep_recent_tool_batches: u32,
527 clear_at_least_tokens: u64,
528 clear_tool_inputs: bool,
529) -> Vec<Message> {
530 if trigger_tokens == 0 || messages.is_empty() {
531 return messages.to_vec();
532 }
533
534 let estimated_tokens: u64 = messages
535 .iter()
536 .map(|message| message.estimate_tokens() as u64)
537 .fold(0u64, u64::saturating_add);
538 if estimated_tokens < trigger_tokens {
539 return messages.to_vec();
540 }
541
542 let tool_indices: Vec<usize> = messages
543 .iter()
544 .enumerate()
545 .filter(|(_, message)| message.role == crate::llm::provider::MessageRole::Tool)
546 .map(|(index, _)| index)
547 .collect();
548 let keep = keep_tool_uses as usize;
549 if tool_indices.len() <= keep {
550 return messages.to_vec();
551 }
552
553 let mut cleared_tokens = 0u64;
554 let analysis = analyze_request_history(messages);
555 let mut retained_batches: HashSet<usize> = tool_indices
556 .iter()
557 .rev()
558 .take(keep)
559 .filter_map(|index| analysis.result_batch_by_index.get(index).copied())
560 .collect();
561 retained_batches.extend((0..analysis.batches.len()).rev().take(keep_recent_tool_batches as usize));
564 let evidence_budget = trigger_tokens / 2;
570 let mut batch_tokens: Vec<u64> = analysis
571 .batches
572 .iter()
573 .map(|batch| messages[batch.assistant_index].estimate_tokens() as u64)
574 .collect();
575 for (&result_index, &batch_index) in &analysis.result_batch_by_index {
576 batch_tokens[batch_index] =
577 batch_tokens[batch_index].saturating_add(messages[result_index].estimate_tokens() as u64);
578 }
579 let mut retained_tokens = 0u64;
580 for (batch_index, &tokens) in batch_tokens.iter().enumerate().rev() {
581 let next_tokens = retained_tokens.saturating_add(tokens);
582 if next_tokens > evidence_budget {
583 break;
584 }
585 retained_tokens = next_tokens;
586 retained_batches.insert(batch_index);
587 }
588 let mut cleared_result_count = 0usize;
589 let mut cleared_calls_by_assistant: HashMap<usize, HashSet<&str>> = HashMap::new();
590 let mut out = messages.to_vec();
594 for &tool_index in &tool_indices[..tool_indices.len() - keep] {
595 let batch_index = analysis.result_batch_by_index.get(&tool_index);
596 if batch_index.is_some_and(|index| retained_batches.contains(index)) {
597 continue;
598 }
599 let original = &messages[tool_index];
600 let original_tokens = original.estimate_tokens() as u64;
601 let stub = build_cleared_tool_result_stub(original);
602 let stub_tokens = stub.estimate_tokens() as u64;
603 if stub_tokens >= original_tokens {
604 continue;
605 }
606 if let Some(&batch_index) = batch_index
607 && let Some(call_id) = original.tool_call_id.as_deref()
608 {
609 cleared_calls_by_assistant
610 .entry(analysis.batches[batch_index].assistant_index)
611 .or_default()
612 .insert(call_id);
613 }
614 out[tool_index] = stub;
615 cleared_result_count += 1;
616 cleared_tokens = cleared_tokens.saturating_add(original_tokens.saturating_sub(stub_tokens));
617 }
618
619 if cleared_tokens < clear_at_least_tokens {
623 tracing::debug!(
624 cleared_tokens,
625 clear_at_least_tokens,
626 "tool-result clearing reclaimed less than the configured floor"
627 );
628 }
629
630 if clear_tool_inputs {
631 for (assistant_index, original_message) in out.iter_mut().enumerate() {
632 let Some(cleared_call_ids) = cleared_calls_by_assistant.remove(&assistant_index) else {
633 continue;
634 };
635 let mut message = original_message.clone();
636 let Some(tool_calls) = message.tool_calls.as_mut() else {
637 continue;
638 };
639 for call in tool_calls.iter_mut() {
640 if cleared_call_ids.contains(call.id.as_str()) {
641 if let Some(function) = call.function.as_mut()
642 && function.arguments.len() > RETAINED_TOOL_INPUT_BYTES
643 {
644 function.arguments = CLEARED_TOOL_INPUT_PLACEHOLDER.to_string();
647 }
648 if call.text.as_ref().is_some_and(|text| text.len() > RETAINED_TOOL_INPUT_BYTES) {
651 call.text = Some(CLEARED_TOOL_INPUT_PLACEHOLDER.to_string());
652 }
653 call.thought_signature = None;
654 }
655 }
656 let input_growth =
659 (message.estimate_tokens() as u64).saturating_sub(original_message.estimate_tokens() as u64);
660 if input_growth <= cleared_tokens {
661 *original_message = message;
662 cleared_tokens = cleared_tokens.saturating_sub(input_growth);
663 }
664 }
665 }
666
667 tracing::debug!(
668 original_tokens = estimated_tokens,
669 projected_tokens = out
670 .iter()
671 .map(|message| message.estimate_tokens() as u64)
672 .fold(0u64, u64::saturating_add),
673 cleared_result_count,
674 protected_batch_count = retained_batches.len(),
675 first_changed_message_index = messages.iter().zip(&out).position(|(before, after)| before != after),
676 "local tool-result clearing projection"
677 );
678 out
679}
680
681pub fn invalidate_reasoning_details_after_request_edits(
689 request_messages: &mut [Message],
690 original_messages: &[Message],
691) -> usize {
692 debug_assert_eq!(request_messages.len(), original_messages.len());
693 let Some(first_edited) = request_messages
694 .iter()
695 .zip(original_messages)
696 .position(|(projected, original)| projected != original)
697 else {
698 return 0;
699 };
700
701 let mut invalidated = 0usize;
702 for message in &mut request_messages[first_edited..] {
703 if message.reasoning_details.take().is_some() {
704 invalidated = invalidated.saturating_add(1);
705 }
706 }
707 invalidated
708}
709
710const CLEARED_TOOL_INPUT_PLACEHOLDER: &str = "{\"cleared\":\"tool_input\"}";
712const RETAINED_TOOL_INPUT_BYTES: usize = 1024;
715
716pub fn should_apply_local_tool_result_clearing(
722 provider_name: &str,
723 context_edits: bool,
724 clearing_enabled: bool,
725) -> bool {
726 clearing_enabled && !(provider_name.eq_ignore_ascii_case("anthropic") && context_edits)
727}
728
729fn build_cleared_tool_result_stub(original: &Message) -> Message {
730 let mut stub = original.clone();
731 let body = serde_json::json!({
733 "cleared": "tool_result",
734 "reason": "tool_result_clearing",
735 "note": CLEARED_TOOL_RESULT_NOTE,
736 "tool": original.origin_tool.as_deref().unwrap_or("tool"),
737 "tool_call_id": original.tool_call_id.as_deref().unwrap_or(""),
738 })
739 .to_string();
740 stub.content = crate::llm::provider::MessageContent::Text(body);
741 stub
742}
743
744pub fn safe_history_split_point(messages: &[Message], conversation_len: usize, preferred_split_at: usize) -> usize {
746 if preferred_split_at == 0 || preferred_split_at >= conversation_len {
747 return preferred_split_at;
748 }
749
750 let mut call_indices: HashMap<&str, usize> = HashMap::new();
751 for (i, msg) in messages.iter().enumerate() {
752 if let Some(tool_calls) = &msg.tool_calls {
753 for call in tool_calls {
754 call_indices.insert(&call.id, i);
755 }
756 }
757 }
758
759 let mut safe_split_at = preferred_split_at;
760 loop {
761 if safe_split_at == 0 {
762 break;
763 }
764
765 let has_orphan = ((safe_split_at + 1)..messages.len()).any(|i| {
766 messages
767 .get(i)
768 .and_then(|msg| msg.tool_call_id.as_ref())
769 .and_then(|id| call_indices.get(id.as_str()))
770 .is_some_and(|&call_idx| call_idx <= safe_split_at)
771 });
772
773 if !has_orphan {
774 break;
775 }
776
777 safe_split_at -= 1;
778 }
779
780 safe_split_at
781}
782
783pub fn ensure_call_outputs_present(messages: &mut Vec<Message>) {
785 let report = validate_history_invariants(messages);
786
787 for missing in report.missing_outputs.iter().rev() {
789 let synthetic_message = Message::tool_response(
790 missing.call_id.as_str().to_string(),
791 "canceled: Tool execution was interrupted. This synthetic output was created \
792 during history normalization to maintain conversation invariants."
793 .to_string(),
794 );
795
796 tracing::warn!("Creating synthetic output for call {} due to missing execution result", missing.call_id);
797
798 let insert_pos = messages
800 .iter()
801 .position(|msg| {
802 msg.tool_calls
803 .as_ref()
804 .is_some_and(|calls| calls.iter().any(|call| call.id == missing.call_id.as_str()))
805 })
806 .map(|pos| pos + 1);
807
808 if let Some(pos) = insert_pos {
809 messages.insert(pos, synthetic_message);
810 } else {
811 messages.push(synthetic_message);
813 }
814 }
815}
816
817pub fn remove_orphan_outputs(messages: &mut Vec<Message>) {
819 let report = validate_history_invariants(messages);
820
821 if report.orphan_outputs.is_empty() {
822 return;
823 }
824
825 let orphan_ids: HashSet<String> = report.orphan_outputs.iter().map(|id| id.as_str().to_string()).collect();
826
827 let initial_len = messages.len();
828
829 messages.retain(|msg| {
833 if let Some(tool_call_id) = msg.tool_call_id.as_ref()
834 && orphan_ids.contains(tool_call_id)
835 {
836 tracing::warn!("Removing orphan output for call {}", tool_call_id);
837 return false;
838 }
839 true
840 });
841
842 if messages.len() != initial_len {
843 tracing::info!("Removed {} orphan outputs", initial_len - messages.len());
844 }
845}
846
847pub fn normalize_history(messages: &mut Vec<Message>) {
849 ensure_call_outputs_present(messages);
850 remove_orphan_outputs(messages);
851
852 let report = validate_history_invariants(messages);
854 if !report.is_valid() {
855 tracing::warn!("History validation: {}", report.summary());
856 } else {
857 tracing::debug!("History normalized successfully");
858 }
859}
860
861pub fn recover_history_from_crash(messages: &mut Vec<Message>) {
863 let report = validate_history_invariants(messages);
864
865 if !report.missing_outputs.is_empty() {
866 tracing::warn!("Found {} missing outputs during recovery", report.missing_outputs.len());
867 ensure_call_outputs_present(messages);
868 }
869
870 if !report.orphan_outputs.is_empty() {
871 tracing::warn!("Found {} orphan outputs during recovery", report.orphan_outputs.len());
872 remove_orphan_outputs(messages);
873 }
874
875 if report.is_valid() {
876 tracing::debug!("History invariants are valid");
877 }
878}
879
880#[cfg(test)]
885mod tests;
886#[cfg(test)]
887mod tool_result_clearing_tests;