use std::sync::Arc;
use gadk_genai::Content;
use gadk_model::LlmResponse;
use gadk_platform::Platform;
use gadk_session::compaction::Config;
use gadk_session::{Event, EventActions, Session};
use serde_json::{Map, Value};
use super::apply::{CoverIndex, has_compaction};
use super::compactor::{Finish, latest_invocation_id, span_params, summarize_traced};
use super::window::{
latest_compaction_event_in_scope, longest_self_contained_prefix, skip_blocked_head,
trim_to_one_scope,
};
use super::{BoxError, ProgressGate, err_text, has_tail_retention, wrap_err};
use crate::llm::processors::go_json_marshal;
use crate::telemetry::{COMPACTION_TRIGGER_TOKEN_THRESHOLD, trace_compaction_declined};
use crate::tool::utils::event_belongs_to_branch;
pub(crate) type TokenCounter = dyn Fn(&[Event]) -> i64 + Send + Sync;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct TurnScope {
pub(crate) invocation_id: String,
pub(crate) branch: String,
pub(crate) isolation_scope: String,
}
impl TurnScope {
pub(crate) fn visible(&self, ev: &Event) -> bool {
event_belongs_to_branch(&self.branch, &ev.branch)
&& ev.isolation_scope == self.isolation_scope
}
}
pub(crate) async fn tail_retention(
platform: &Platform,
cfg: &Config,
sess: Option<&dyn Session>,
scope: &TurnScope,
estimate: Option<&TokenCounter>,
progress: Option<Arc<dyn ProgressGate>>,
) -> Result<(Option<Event>, Finish), BoxError> {
if !has_tail_retention(Some(cfg)) {
return Ok((None, Finish::noop()));
}
if cfg.summarizer.is_none() {
return Err(err_text("no Summarizer configured"));
}
let Some(sess) = sess else {
return Ok((None, Finish::noop()));
};
let events = sess.events();
let Some(tokens) = prompt_token_count(&events, scope, estimate) else {
return Ok((None, Finish::noop()));
};
if tokens < i64::from(cfg.token_threshold) {
if let Some(p) = &progress {
p.recovered();
}
return Ok((None, Finish::noop()));
}
if let Some(p) = &progress
&& !p.allow_at()
{
trace_declined(
cfg,
Some(sess),
"the previous compaction did not bring the prompt back under the threshold",
);
return Ok((None, Finish::noop()));
}
let window = select_tail_retention_window(&events, cfg.event_retention_size, scope);
if window.is_empty() {
trace_declined(
cfg,
Some(sess),
"no compactable window past the retained tail",
);
return Ok((None, Finish::noop()));
}
let (summary, finish) = match summarize_traced(
platform,
cfg,
Some(sess),
&scope.invocation_id,
COMPACTION_TRIGGER_TOKEN_THRESHOLD,
&window,
)
.await
{
Ok(r) => r,
Err(e) => {
if let Some(p) = &progress {
p.failed();
}
return Err(wrap_err("tail-retention summarization failed", e));
}
};
let Some(summary) = summary else {
if let Some(p) = &progress {
p.failed();
}
return Ok((None, Finish::noop()));
};
let finish = finish.then_after(move |err, discard_reason| {
if let Some(p) = progress {
if err.is_some() {
p.failed();
} else if discard_reason.is_empty() {
p.record_at(tokens);
}
}
});
Ok((Some(summary), finish))
}
const CHARS_PER_TOKEN: i64 = 4;
fn json_chars(v: &Map<String, Value>) -> i64 {
if v.is_empty() {
return 0;
}
go_json_marshal(&Value::Object(v.clone())).chars().count() as i64
}
pub(crate) fn prompt_token_count(
events: &[Event],
scope: &TurnScope,
estimate: Option<&TokenCounter>,
) -> Option<i64> {
for (i, ev) in events.iter().enumerate().rev() {
if !scope.visible(ev) || has_compaction(ev) {
continue;
}
if let Some(usage) = &ev.response.usage_metadata
&& usage.prompt_token_count > 0
{
let mut tokens = i64::from(usage.prompt_token_count);
if let Some(est) = estimate
&& i < events.len() - 1
{
tokens += est(&events[i + 1..]);
}
return Some(tokens);
}
}
let est = estimate?;
let tokens = est(events);
(tokens > 0).then_some(tokens)
}
pub(crate) fn estimate_tokens_from_contents(contents: &[Content]) -> i64 {
let mut chars: i64 = 0;
for content in contents {
for part in &content.parts {
chars += part.text.chars().count() as i64;
if let Some(fc) = &part.function_call {
chars += fc.name.chars().count() as i64 + json_chars(&fc.args);
}
if let Some(fr) = &part.function_response {
chars += fr.name.chars().count() as i64 + json_chars(&fr.response);
}
}
}
if chars <= 0 {
return 0;
}
chars / CHARS_PER_TOKEN
}
pub(crate) fn select_tail_retention_window(
events: &[Event],
retention_size: i32,
scope: &TurnScope,
) -> Vec<Event> {
if retention_size < 0 {
return Vec::new();
}
let retention = retention_size as usize;
let latest = latest_compaction_event_in_scope(events, &scope.branch, &scope.isolation_scope);
let live_head = if scope.invocation_id.is_empty() {
""
} else {
events
.iter()
.find(|ev| ev.invocation_id == scope.invocation_id && !has_compaction(ev))
.map_or("", |ev| ev.id.as_str())
};
let cover = CoverIndex::new(events);
let mut candidates: Vec<Event> = Vec::new();
for (i, ev) in events.iter().enumerate() {
if has_compaction(ev) || !scope.visible(ev) {
continue;
}
if !live_head.is_empty() && ev.id == live_head {
continue;
}
if cover.covers_after(i, ev) {
continue;
}
candidates.push(ev.clone());
}
if candidates.len() <= retention {
return Vec::new();
}
let mut first_retained = candidates.len();
if retention > 0 {
first_retained -= retention;
let boundary = candidates[first_retained].timestamp;
while first_retained > 0 && candidates[first_retained - 1].timestamp >= boundary {
first_retained -= 1;
}
}
candidates.truncate(first_retained);
let scoped = trim_to_one_scope(candidates);
let mut window = longest_self_contained_prefix(&scoped);
if window.is_empty() {
window = skip_blocked_head(scoped);
}
if window.is_empty() {
return Vec::new();
}
let Some(latest) = latest else {
return window;
};
let Some(prev) = latest.actions.compaction.clone() else {
return window;
};
let seed = Event {
id: latest.id.clone(),
author: "model".to_owned(),
timestamp: prev.start_timestamp,
branch: latest.branch.clone(),
isolation_scope: latest.isolation_scope.clone(),
response: LlmResponse {
content: prev.compacted_content.clone(),
..Default::default()
},
actions: EventActions {
compaction: Some(prev),
..Default::default()
},
..Default::default()
};
if seed.branch != window[0].branch || seed.isolation_scope != window[0].isolation_scope {
return window;
}
let mut out = Vec::with_capacity(window.len() + 1);
out.push(seed);
out.extend(window);
out
}
fn trace_declined(cfg: &Config, sess: Option<&dyn Session>, reason: &str) {
let id = sess.map(|s| s.id().to_owned()).unwrap_or_default();
let params = span_params(
cfg,
&id,
&latest_invocation_id(sess),
COMPACTION_TRIGGER_TOKEN_THRESHOLD,
0,
);
trace_compaction_declined(¶ms, reason);
}