use adk_core::{AdkError, ErrorCategory, ErrorComponent, Event, Llm};
use async_trait::async_trait;
use std::sync::Arc;
#[derive(Debug, thiserror::Error)]
#[error("Context overflow: {token_count} tokens (limit: {limit})")]
pub struct ContextOverflowError {
pub token_count: usize,
pub limit: usize,
}
impl From<ContextOverflowError> for AdkError {
fn from(err: ContextOverflowError) -> Self {
AdkError::new(
ErrorComponent::Model,
ErrorCategory::InvalidInput,
"runner.context_overflow",
err.to_string(),
)
}
}
#[async_trait]
pub trait CompactionStrategy: Send + Sync {
async fn compact(&self, events: Vec<Event>, budget: usize) -> Result<Vec<Event>, AdkError>;
}
pub struct TruncationCompaction {
pub preserve_recent: usize,
}
#[async_trait]
impl CompactionStrategy for TruncationCompaction {
async fn compact(&self, events: Vec<Event>, _budget: usize) -> Result<Vec<Event>, AdkError> {
let len = events.len();
if len <= self.preserve_recent + 1 {
return Ok(events);
}
let start = adk_core::history::balanced_cut(&events, len - self.preserve_recent);
if start <= 1 {
return Ok(events);
}
let mut compacted = Vec::with_capacity(len - start + 1);
if let Some(first) = events.first() {
compacted.push(first.clone());
}
compacted.extend_from_slice(&events[start..]);
tracing::debug!(
original_count = len,
compacted_count = compacted.len(),
dropped = len - compacted.len(),
"truncation compaction applied"
);
Ok(compacted)
}
}
pub struct SummarisationCompaction {
pub model: Arc<dyn Llm>,
pub turns_to_summarise: usize,
}
#[async_trait]
impl CompactionStrategy for SummarisationCompaction {
async fn compact(&self, events: Vec<Event>, _budget: usize) -> Result<Vec<Event>, AdkError> {
let len = events.len();
if len <= self.turns_to_summarise {
return Ok(events);
}
let summarize_end = adk_core::history::balanced_cut(&events, self.turns_to_summarise);
if summarize_end == 0 {
return Ok(events);
}
let events_to_summarize = &events[..summarize_end];
let events_to_preserve = &events[summarize_end..];
let summary_text = build_summary_prompt(events_to_summarize);
let request = adk_core::LlmRequest::new(
self.model.name().to_string(),
vec![adk_core::Content::new("user").with_text(summary_text)],
);
let mut stream = adk_core::generate_metered(self.model.as_ref(), request, false).await?;
use futures::StreamExt;
let mut summary_content = String::new();
let mut finish_reason = None;
while let Some(response) = stream.next().await {
let response = response.map_err(|cause| {
let mut details = (*cause.details).clone();
details.metadata.insert("cause_code".to_string(), cause.code.into());
AdkError::new(
ErrorComponent::Model,
cause.category,
"model.summary_incomplete",
format!(
"the summarization model failed before finishing its summary ({}); \
summarise fewer turns or retry",
cause.message
),
)
.with_retry(cause.retry.clone())
.with_details(details)
.with_source(cause)
})?;
if let Some(content) = &response.content {
for part in &content.parts {
if let adk_core::Part::Text { text } = part {
summary_content.push_str(text);
}
}
}
finish_reason = response.finish_reason.or(finish_reason);
}
if let Some(reason) = finish_reason.filter(|reason| *reason != adk_core::FinishReason::Stop)
{
return Err(AdkError::new(
ErrorComponent::Model,
ErrorCategory::Internal,
"model.summary_incomplete",
format!(
"the summarization model stopped before finishing its summary ({reason:?}); \
raise its output limit or summarise fewer turns"
),
));
}
let mut summary_event = Event::new("compaction");
summary_event.author = "system".to_string();
summary_event.set_content(
adk_core::Content::new("model")
.with_text(format!("[Context Summary]\n{summary_content}")),
);
if summary_content.trim().is_empty()
|| estimate_event_tokens(std::slice::from_ref(&summary_event))
>= estimate_event_tokens(events_to_summarize)
{
tracing::info!("summary is not smaller than the events it replaces; keeping them");
return Ok(events);
}
let mut compacted = Vec::with_capacity(1 + events_to_preserve.len());
compacted.push(summary_event);
compacted.extend_from_slice(events_to_preserve);
tracing::debug!(
original_count = len,
summarized_count = summarize_end,
preserved_count = events_to_preserve.len(),
"summarisation compaction applied"
);
Ok(compacted)
}
}
fn build_summary_prompt(events: &[Event]) -> String {
let mut prompt = String::from(
"Summarize the following conversation history into a concise summary \
that preserves key facts, decisions, and context. Be brief but complete.\n\n",
);
for event in events {
if event.llm_response.partial {
continue;
}
if let Some(content) = event.content() {
for rendered in
content.parts.iter().filter_map(adk_core::intra_compaction::render_part_for_summary)
{
prompt.push_str(&format!("[{}]: {rendered}\n", content.role));
}
}
}
prompt
}
pub struct CompactionConfig {
pub strategy: Box<dyn CompactionStrategy>,
pub context_budget: usize,
pub max_retries: usize,
}
impl CompactionConfig {
pub fn new(strategy: Box<dyn CompactionStrategy>, context_budget: usize) -> Self {
Self { strategy, context_budget, max_retries: 2 }
}
}
impl std::fmt::Debug for CompactionConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompactionConfig")
.field("context_budget", &self.context_budget)
.field("max_retries", &self.max_retries)
.field("strategy", &"<dyn CompactionStrategy>")
.finish()
}
}
pub fn is_token_limit_error(err: &AdkError) -> bool {
adk_core::intra_compaction::is_context_limit_error(err)
}
pub async fn apply_compaction_with_retry(
config: &CompactionConfig,
events: Vec<Event>,
) -> Result<Vec<Event>, AdkError> {
let mut current_events = events;
for attempt in 0..config.max_retries {
tracing::info!(
attempt = attempt + 1,
max_retries = config.max_retries,
event_count = current_events.len(),
budget = config.context_budget,
"applying context compaction"
);
let held_from = adk_core::history::balanced_cut(
¤t_events,
adk_core::held_call_compaction_limit(¤t_events, current_events.len()),
);
let kept = current_events.split_off(held_from);
current_events = config.strategy.compact(current_events, config.context_budget).await?;
current_events.extend(kept);
let estimated_tokens = estimate_event_tokens(¤t_events);
if estimated_tokens <= config.context_budget {
tracing::info!(
estimated_tokens,
budget = config.context_budget,
"compaction succeeded, context within budget"
);
return Ok(current_events);
}
tracing::warn!(
estimated_tokens,
budget = config.context_budget,
attempt = attempt + 1,
"compaction did not bring context under budget, retrying"
);
}
let final_tokens = estimate_event_tokens(¤t_events);
Err(ContextOverflowError { token_count: final_tokens, limit: config.context_budget }.into())
}
pub fn estimate_event_tokens(events: &[Event]) -> usize {
adk_core::intra_compaction::estimate_tokens(events, 4) as usize
}
#[cfg(test)]
mod tests {
use super::*;
use adk_core::{Content, Event};
fn make_events(count: usize) -> Vec<Event> {
(0..count)
.map(|i| {
let mut event = Event::new("test-inv");
event.author = if i == 0 { "system".to_string() } else { "user".to_string() };
event.set_content(Content::new("user").with_text(format!("message {i}")));
event
})
.collect()
}
fn with_held_call(before: usize, after: usize) -> Vec<Event> {
let mut events = make_events(before);
let mut call = Event::new("inv-held");
call.author = "ops".to_string();
call.set_content(Content {
role: "model".to_string(),
parts: vec![adk_core::Part::FunctionCall {
name: "transfer".to_string(),
args: serde_json::json!({ "amount": 10 }),
id: Some("c1".to_string()),
thought_signature: None,
}],
});
let mut pending = Event::new("inv-held");
pending.author = "ops".to_string();
pending.set_content(Content {
role: "function".to_string(),
parts: vec![adk_core::Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::new(
"transfer",
adk_core::confirmation_pending_response("held"),
),
id: Some("c1".to_string()),
annotations: None,
}],
});
let mut hold = Event::new("inv-held");
hold.author = "ops".to_string();
hold.actions.tool_confirmation = Some(adk_core::ToolConfirmationRequest {
tool_name: "transfer".to_string(),
function_call_id: Some("c1".to_string()),
args: serde_json::json!({ "amount": 10 }),
acting: None,
origin: None,
evidence: Vec::new(),
});
events.extend([call, pending, hold]);
events.extend(make_events(after));
let start = chrono::Utc::now();
for (index, event) in events.iter_mut().enumerate() {
event.timestamp = start + chrono::Duration::milliseconds(index as i64);
}
events
}
#[tokio::test]
async fn context_compaction_keeps_a_held_call_and_everything_after_it() {
let events = with_held_call(8, 3);
let config = CompactionConfig::new(
Box::new(TruncationCompaction { preserve_recent: 1 }),
usize::MAX,
);
let compacted = apply_compaction_with_retry(&config, events.clone()).await.unwrap();
let ids =
|events: &[Event]| events.iter().map(|event| event.id.clone()).collect::<Vec<_>>();
assert_eq!(ids(&compacted[..2]), ids(&[events[0].clone(), events[7].clone()]));
assert_eq!(ids(&compacted[2..]), ids(&events[8..]), "the held call and later events stay");
assert_eq!(adk_core::held_tool_calls(&compacted, "ops", "").len(), 1);
}
struct PricedSummaryModel;
#[async_trait]
impl Llm for PricedSummaryModel {
fn name(&self) -> &str {
"gemini-3.5-flash-lite"
}
async fn generate_content(
&self,
_request: adk_core::LlmRequest,
_stream: bool,
) -> adk_core::Result<adk_core::LlmResponseStream> {
let response = adk_core::LlmResponse {
content: Some(Content::new("model").with_text("summary")),
usage_metadata: Some(adk_core::UsageMetadata {
total_token_count: 50,
cost: Some(0.0005),
..Default::default()
}),
provider: Some("gemini".to_string()),
turn_complete: true,
..Default::default()
};
Ok(Box::pin(futures::stream::iter(vec![Ok(response)])))
}
}
#[tokio::test]
async fn summarisation_counts_against_the_current_scope_and_stops_over_budget() {
use adk_core::{BudgetTracker, ModelCallScope, RunBudget};
let strategy =
SummarisationCompaction { model: Arc::new(PricedSummaryModel), turns_to_summarise: 4 };
let tracker = Arc::new(BudgetTracker::new(RunBudget::new().max_model_calls(1)));
let scope = ModelCallScope::new().with_budget(tracker.clone());
let compacted = scope.clone().within(strategy.compact(make_events(10), 4096)).await;
assert_eq!(compacted.unwrap().len(), 7);
assert_eq!(tracker.usage().total_tokens, 50);
assert_eq!(tracker.usage().cost_micro_usd, 500);
let refused = scope.within(strategy.compact(make_events(10), 4096)).await;
assert_eq!(refused.unwrap_err().code, "budget.model_calls");
assert_eq!(tracker.usage().model_calls, 1);
}
fn call_and_result(id: &str, payload: serde_json::Value) -> [Event; 2] {
let mut call = Event::new("inv");
call.author = "desk".to_string();
call.set_content(Content {
role: "model".to_string(),
parts: vec![adk_core::Part::FunctionCall {
name: "lookup".to_string(),
args: serde_json::json!({"order": "A1"}),
id: Some(id.to_string()),
thought_signature: None,
}],
});
let mut result = Event::new("inv");
result.author = "desk".to_string();
result.set_content(Content {
role: "function".to_string(),
parts: vec![adk_core::Part::FunctionResponse {
function_response: adk_core::FunctionResponseData::new("lookup", payload),
id: Some(id.to_string()),
annotations: None,
}],
});
[call, result]
}
struct ScriptedSummary {
text: String,
finish: adk_core::FinishReason,
prompts: std::sync::Mutex<Vec<String>>,
}
impl ScriptedSummary {
fn new(text: &str, finish: adk_core::FinishReason) -> Arc<Self> {
Arc::new(Self { text: text.to_string(), finish, prompts: Default::default() })
}
}
#[async_trait]
impl Llm for ScriptedSummary {
fn name(&self) -> &str {
"summary"
}
async fn generate_content(
&self,
request: adk_core::LlmRequest,
_stream: bool,
) -> adk_core::Result<adk_core::LlmResponseStream> {
let prompt = request.contents[0].parts[0].text().unwrap_or_default().to_string();
self.prompts.lock().unwrap().push(prompt);
let response = adk_core::LlmResponse {
content: Some(Content::new("model").with_text(&self.text)),
finish_reason: Some(self.finish),
turn_complete: true,
..Default::default()
};
Ok(Box::pin(futures::stream::iter(vec![Ok(response)])))
}
}
#[tokio::test]
async fn truncation_keeps_the_call_of_a_kept_result() {
let mut events = make_events(3);
events.extend(call_and_result("c1", serde_json::json!({"status": "shipped"})));
events.extend(make_events(2));
let compacted = TruncationCompaction { preserve_recent: 3 }
.compact(events.clone(), 4096)
.await
.unwrap();
let ids = compacted.iter().map(|event| event.id.clone()).collect::<Vec<_>>();
let expected = [&events[..1], &events[3..]]
.concat()
.iter()
.map(|event| event.id.clone())
.collect::<Vec<_>>();
assert_eq!(ids, expected);
}
#[tokio::test]
async fn summarisation_never_splits_a_call_from_its_result_and_keeps_tool_facts() {
let mut events = vec![make_events(1)[0].clone()];
events[0].set_content(Content::new("user").with_text("background ".repeat(50)));
events.extend(call_and_result("c1", serde_json::json!({"warehouse": "Nairobi-7"})));
events.extend(make_events(2));
let model = ScriptedSummary::new("short", adk_core::FinishReason::Stop);
let compacted = SummarisationCompaction { model: model.clone(), turns_to_summarise: 2 }
.compact(events.clone(), 4096)
.await
.unwrap();
assert_eq!(compacted.len(), 5, "the summary, then the call, its result and two more");
assert_eq!(compacted[1].id, events[1].id);
let summary_of_tools =
SummarisationCompaction { model: model.clone(), turns_to_summarise: 3 }
.compact(events.clone(), 4096)
.await
.unwrap();
assert_eq!(summary_of_tools.len(), 3);
let prompts = model.prompts.lock().unwrap().clone();
assert!(prompts[1].contains(r#"[function response] lookup: {"warehouse":"Nairobi-7"}"#));
assert!(prompts[1].contains(r#"[function call] lookup({"order":"A1"})"#));
}
#[tokio::test]
async fn summarisation_keeps_the_events_when_the_summary_does_not_shrink_them() {
let events = make_events(6);
let model = ScriptedSummary::new(&"long summary ".repeat(50), adk_core::FinishReason::Stop);
let compacted = SummarisationCompaction { model, turns_to_summarise: 3 }
.compact(events.clone(), 4096)
.await
.unwrap();
assert_eq!(compacted.len(), events.len());
}
#[tokio::test]
async fn summarisation_fails_when_the_summary_was_cut_short() {
let model = ScriptedSummary::new("Summary: the cust", adk_core::FinishReason::MaxTokens);
let error = SummarisationCompaction { model, turns_to_summarise: 3 }
.compact(make_events(6), 4096)
.await
.unwrap_err();
assert_eq!(error.code, "model.summary_incomplete");
}
#[tokio::test]
async fn summarisation_fails_when_the_model_declines() {
let model =
ScriptedSummary::new("I can't summarise that.", adk_core::FinishReason::Refusal);
let error = SummarisationCompaction { model, turns_to_summarise: 3 }
.compact(make_events(6), 4096)
.await
.unwrap_err();
assert_eq!(error.code, "model.summary_incomplete");
}
struct FailingSummary;
#[async_trait]
impl Llm for FailingSummary {
fn name(&self) -> &str {
"summary"
}
async fn generate_content(
&self,
_request: adk_core::LlmRequest,
_stream: bool,
) -> adk_core::Result<adk_core::LlmResponseStream> {
let partial = adk_core::LlmResponse {
content: Some(Content::new("model").with_text("Summary: the cust")),
partial: true,
..Default::default()
};
let stalled = AdkError::new(
ErrorComponent::Model,
ErrorCategory::Timeout,
"model.openai_compat.request",
"the response stopped arriving",
)
.with_provider("openai");
Ok(Box::pin(futures::stream::iter(vec![Ok(partial), Err(stalled)])))
}
}
#[tokio::test]
async fn summarisation_fails_with_the_cause_when_the_stream_fails() {
let error =
SummarisationCompaction { model: Arc::new(FailingSummary), turns_to_summarise: 3 }
.compact(make_events(6), 4096)
.await
.unwrap_err();
assert_eq!(error.code, "model.summary_incomplete");
assert_eq!(error.category, ErrorCategory::Timeout);
assert!(error.is_retryable());
assert_eq!(error.details.provider.as_deref(), Some("openai"));
assert_eq!(error.details.metadata["cause_code"], "model.openai_compat.request");
assert!(std::error::Error::source(&error).is_some());
}
#[test]
fn the_estimate_counts_tool_payloads() {
let events = call_and_result("c1", serde_json::json!({"notes": "n".repeat(4000)}));
assert!(estimate_event_tokens(&events) > 1000, "{}", estimate_event_tokens(&events));
}
#[tokio::test]
async fn test_truncation_preserves_system_and_recent() {
let strategy = TruncationCompaction { preserve_recent: 3 };
let events = make_events(10);
let compacted = strategy.compact(events.clone(), 4096).await.unwrap();
assert_eq!(compacted.len(), 4);
assert_eq!(compacted[0].author, "system");
assert_eq!(compacted[1].id, events[7].id);
assert_eq!(compacted[2].id, events[8].id);
assert_eq!(compacted[3].id, events[9].id);
}
#[tokio::test]
async fn test_truncation_no_op_when_few_events() {
let strategy = TruncationCompaction { preserve_recent: 5 };
let events = make_events(3);
let compacted = strategy.compact(events.clone(), 4096).await.unwrap();
assert_eq!(compacted.len(), 3);
}
#[tokio::test]
async fn test_truncation_exact_boundary() {
let strategy = TruncationCompaction { preserve_recent: 4 };
let events = make_events(5);
let compacted = strategy.compact(events.clone(), 4096).await.unwrap();
assert_eq!(compacted.len(), 5);
}
#[test]
fn test_context_overflow_error_display() {
let err = ContextOverflowError { token_count: 50_000, limit: 32_000 };
assert_eq!(err.to_string(), "Context overflow: 50000 tokens (limit: 32000)");
}
#[test]
fn test_context_overflow_error_into_adk_error() {
let err = ContextOverflowError { token_count: 50_000, limit: 32_000 };
let adk_err: AdkError = err.into();
assert!(adk_err.is_model());
assert_eq!(adk_err.code, "runner.context_overflow");
}
#[test]
fn test_compaction_config_new_defaults_max_retries() {
let strategy = TruncationCompaction { preserve_recent: 5 };
let config = CompactionConfig::new(Box::new(strategy), 100_000);
assert_eq!(config.context_budget, 100_000);
assert_eq!(config.max_retries, 2);
}
#[test]
fn test_compaction_config_custom_max_retries() {
let config = CompactionConfig {
strategy: Box::new(TruncationCompaction { preserve_recent: 3 }),
context_budget: 50_000,
max_retries: 5,
};
assert_eq!(config.context_budget, 50_000);
assert_eq!(config.max_retries, 5);
}
#[test]
fn test_compaction_config_debug() {
let config =
CompactionConfig::new(Box::new(TruncationCompaction { preserve_recent: 3 }), 32_000);
let debug_str = format!("{config:?}");
assert!(debug_str.contains("CompactionConfig"));
assert!(debug_str.contains("32000"));
assert!(debug_str.contains("max_retries: 2"));
}
#[test]
fn test_build_summary_prompt() {
let mut events = Vec::new();
let mut e1 = Event::new("inv");
e1.set_content(Content::new("user").with_text("Hello"));
events.push(e1);
let mut e2 = Event::new("inv");
e2.set_content(Content::new("model").with_text("Hi there!"));
events.push(e2);
let prompt = build_summary_prompt(&events);
assert!(prompt.contains("[user]: Hello"));
assert!(prompt.contains("[model]: Hi there!"));
assert!(prompt.contains("Summarize"));
}
#[test]
fn test_is_token_limit_error_detects_openai_style() {
let err = AdkError::new(
adk_core::ErrorComponent::Model,
adk_core::ErrorCategory::InvalidInput,
"model.openai.bad_request",
"This model's maximum context length is 128000 tokens",
);
assert!(is_token_limit_error(&err));
}
#[test]
fn test_is_token_limit_error_detects_anthropic_style() {
let err = AdkError::new(
adk_core::ErrorComponent::Model,
adk_core::ErrorCategory::InvalidInput,
"model.anthropic.bad_request",
"prompt is too long: 200000 tokens > 100000 maximum",
);
assert!(is_token_limit_error(&err));
}
#[test]
fn test_is_token_limit_error_detects_context_overflow_code() {
let err = AdkError::new(
adk_core::ErrorComponent::Model,
adk_core::ErrorCategory::InvalidInput,
"runner.context_overflow",
"Context overflow: 50000 tokens (limit: 32000)",
);
assert!(is_token_limit_error(&err));
}
#[test]
fn test_is_token_limit_error_rejects_non_model_error() {
let err = AdkError::new(
adk_core::ErrorComponent::Tool,
adk_core::ErrorCategory::InvalidInput,
"tool.error",
"token limit exceeded",
);
assert!(!is_token_limit_error(&err));
}
#[test]
fn test_is_token_limit_error_rejects_non_invalid_input() {
let err = AdkError::new(
adk_core::ErrorComponent::Model,
adk_core::ErrorCategory::Internal,
"model.internal",
"token limit exceeded",
);
assert!(!is_token_limit_error(&err));
}
#[test]
fn test_is_token_limit_error_rejects_unrelated_invalid_input() {
let err = AdkError::new(
adk_core::ErrorComponent::Model,
adk_core::ErrorCategory::InvalidInput,
"model.openai.bad_request",
"invalid JSON in request body",
);
assert!(!is_token_limit_error(&err));
}
#[test]
fn test_estimate_event_tokens_empty() {
let events: Vec<Event> = Vec::new();
assert_eq!(estimate_event_tokens(&events), 0);
}
#[test]
fn test_estimate_event_tokens_with_content() {
let mut event = Event::new("inv");
event.set_content(Content::new("user").with_text("Hello world"));
let events = vec![event];
assert_eq!(estimate_event_tokens(&events), 11 / 4); }
#[tokio::test]
async fn test_apply_compaction_with_retry_succeeds_first_try() {
let strategy = TruncationCompaction { preserve_recent: 2 };
let config = CompactionConfig {
strategy: Box::new(strategy),
context_budget: 100, max_retries: 2,
};
let events = make_events(10);
let result = apply_compaction_with_retry(&config, events).await;
assert!(result.is_ok());
let compacted = result.unwrap();
assert_eq!(compacted.len(), 3);
}
#[tokio::test]
async fn test_apply_compaction_with_retry_fails_when_budget_too_small() {
let strategy = TruncationCompaction { preserve_recent: 2 };
let config = CompactionConfig {
strategy: Box::new(strategy),
context_budget: 0, max_retries: 2,
};
let mut events = Vec::new();
for i in 0..5 {
let mut e = Event::new("inv");
e.set_content(Content::new("user").with_text(format!("message {i} with some content")));
events.push(e);
}
let result = apply_compaction_with_retry(&config, events).await;
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.code, "runner.context_overflow");
}
}