Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(agent): preserve history when compaction overflows

thinhlpg460765170e46
diff --git a/src-tauri/src/core/agent/compaction.rs b/src-tauri/src/core/agent/compaction.rs
index b22c7dbd5..7701acf0e 100644
--- a/src-tauri/src/core/agent/compaction.rs
+++ b/src-tauri/src/core/agent/compaction.rs
@@ -68,25 +68,32 @@ fn tail_start(rest: &[Value], target: usize) -> Option<usize> {
/// Compact `messages` so the result is meaningfully smaller than the input.
/// Returns the input unchanged when there is nothing safe to compact (so the
/// caller can detect a no-op and stop retrying).
+///
+/// The error case is one specific failure: when the *target model's* summarizer
+/// itself overflows its context window, a fallback note must not be fabricated
+/// (it would silently drop the whole dropped span and, for a smaller-window
+/// model, the compacted request could still overflow). The `Err` is propagated
+/// so the caller can preserve history and block the request instead. Every
+/// other summarizer failure stays recoverable and yields a [`FALLBACK_NOTE`].
pub(crate) async fn compact_conversation(
messages: &[Value],
model_id: &str,
model: &dyn ModelInvoker,
keep_recent: usize,
-) -> Vec<Value> {
+) -> Result<Vec<Value>, String> {
let sys_end = messages.iter().take_while(|m| role(m) == "system").count();
let (system_msgs, rest) = messages.split_at(sys_end);
if rest.len() <= keep_recent {
- return messages.to_vec();
+ return Ok(messages.to_vec());
}
let Some(cut) = tail_start(rest, rest.len() - keep_recent) else {
- return messages.to_vec();
+ return Ok(messages.to_vec());
};
let kept = &rest[cut..];
- let summary = summarize(&rest[..cut], model_id, model).await;
+ let summary = summarize(&rest[..cut], model_id, model).await?;
let mut out = Vec::with_capacity(system_msgs.len() + 1 + kept.len());
out.extend_from_slice(system_msgs);
@@ -95,7 +102,7 @@ pub(crate) async fn compact_conversation(
"content": format!("[Summary of earlier conversation, condensed to save context]\n\n{summary}")
}));
out.extend_from_slice(kept);
- out
+ Ok(out)
}
/// Flatten a span of wire messages into a plain-text transcript. Rendering
@@ -160,10 +167,15 @@ fn clamp_middle(text: &str, max: usize) -> String {
/// conversation: this runs after an overflow, so a request carrying the full
/// history plus a prompt is strictly larger than the one that just failed and
/// could only fail too, silently degrading every compaction to [`FALLBACK_NOTE`].
-async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker) -> String {
+///
+/// Returns an `Err` only when the target model's context window overflowed --
+/// the caller must block rather than fabricate a fallback note for a
+/// smaller-window model. Every other failure and empty/unreadable completion
+/// stays recoverable and returns [`FALLBACK_NOTE`].
+async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker) -> Result<String, String> {
let transcript = clamp_middle(&render_transcript(dropped), SUMMARY_INPUT_CHARS);
if transcript.trim().is_empty() {
- return FALLBACK_NOTE.to_string();
+ return Ok(FALLBACK_NOTE.to_string());
}
let request = json!({
"model": model_id,
@@ -176,14 +188,25 @@ async fn summarize(dropped: &[Value], model_id: &str, model: &dyn ModelInvoker)
// never reach the user-facing event stream.
let (sink, _rx) = mpsc::unbounded_channel();
match model.invoke(&request, &sink).await {
- Ok(completion) => extract_choice_message(&completion)
- .and_then(|m| m.get("content"))
- .and_then(|c| c.as_str())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .unwrap_or_else(|| FALLBACK_NOTE.to_string()),
- Err(_) => FALLBACK_NOTE.to_string(),
+ Ok(completion) => {
+ let summary = extract_choice_message(&completion)
+ .and_then(|m| m.get("content"))
+ .and_then(|c| c.as_str())
+ .map(str::trim)
+ .filter(|s| !s.is_empty())
+ .map(str::to_string);
+ Ok(summary.unwrap_or_else(|| FALLBACK_NOTE.to_string()))
+ }
+ Err(e) => {
+ // A model-switch compaction targets the (smaller) new model: if the
+ // summarizer itself overflows, a note is not safe -- the request
+ // could still overflow and the dropped span would be lost. Propagate.
+ if crate::core::agent::upstream::is_context_overflow_error(&e) {
+ Err(e)
+ } else {
+ Ok(FALLBACK_NOTE.to_string())
+ }
+ }
}
}
@@ -240,7 +263,9 @@ mod tests {
requests: tokio::sync::Mutex::new(Vec::new()),
};
let input = convo(4);
- let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;
+ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT)
+ .await
+ .expect("no-op must not fail");
assert_eq!(out, input);
assert_eq!(*model.calls.lock().unwrap(), 0, "no summarization on no-op");
}
@@ -253,7 +278,9 @@ mod tests {
requests: tokio::sync::Mutex::new(Vec::new()),
};
let input = convo(20);
- let out = compact_conversation(&input, "m", &model, 4).await;
+ let out = compact_conversation(&input, "m", &model, 4)
+ .await
+ .expect("successful summary must not fail");
assert!(out.len() < input.len());
assert_eq!(role(&out[0]), "system");
@@ -278,7 +305,9 @@ mod tests {
};
let input = convo(20);
- compact_conversation(&input, "m", &model, 4).await;
+ compact_conversation(&input, "m", &model, 4)
+ .await
+ .expect("successful summary must not fail");
let requests = model.requests.lock().await;
let messages = requests[0]["messages"].as_array().unwrap();
@@ -333,7 +362,9 @@ mod tests {
json!({ "role": "assistant", "content": "welcome" }),
];
- compact_conversation(&input, "m", &model, 2).await;
+ compact_conversation(&input, "m", &model, 2)
+ .await
+ .expect("successful summary must not fail");
let requests = model.requests.lock().await;
let messages = requests[0]["messages"].as_array().unwrap();
@@ -363,7 +394,9 @@ mod tests {
input.push(json!({ "role": r, "content": "x".repeat(8_000) }));
}
- compact_conversation(&input, "m", &model, 4).await;
+ compact_conversation(&input, "m", &model, 4)
+ .await
+ .expect("successful summary must not fail");
let requests = model.requests.lock().await;
let transcript = requests[0]["messages"][1]["content"].as_str().unwrap();
@@ -405,11 +438,41 @@ mod tests {
#[tokio::test]
async fn falls_back_to_note_when_summarizer_fails() {
let input = convo(20);
- let out = compact_conversation(&input, "m", &FailingModel, 4).await;
+ let out = compact_conversation(&input, "m", &FailingModel, 4)
+ .await
+ .expect("an ordinary summarizer error must not fail compaction");
assert!(out[1]["content"].as_str().unwrap().contains(FALLBACK_NOTE));
assert!(out.len() < input.len());
}
+ /// A target-model summarizer that itself overflows its context window must
+ /// fail compaction rather than fabricate a fallback note: for a
+ /// smaller-window model a note could still overflow, and the dropped span
+ /// would be silently lost. The caller (a model switch) blocks instead.
+ struct OverflowingModel;
+ #[async_trait]
+ impl ModelInvoker for OverflowingModel {
+ async fn invoke(
+ &self,
+ _request: &Value,
+ _events: &mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,
+ ) -> Result<Value, String> {
+ Err(format!(
+ "[{}] Upstream returned HTTP 400: prompt is too long",
+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER
+ ))
+ }
+ }
+
+ #[tokio::test]
+ async fn target_summary_context_overflow_is_fatal() {
+ let input = convo(20);
+ let error = compact_conversation(&input, "m", &OverflowingModel, 4)
+ .await
+ .expect_err("a summarizer context overflow must not be swallowed");
+ assert!(crate::core::agent::upstream::is_context_overflow_error(&error));
+ }
+
/// One prompt driving a long agentic run is the normal shape here: a single
/// user message followed by hundreds of assistant/tool rounds. Compaction
/// has to bite into that from the top, or the run it was called to rescue
@@ -434,7 +497,9 @@ mod tests {
"role": "tool", "tool_call_id": format!("t{i}"), "content": format!("out{i}")
}));
}
- let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;
+ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT)
+ .await
+ .expect("successful summary must not fail");
assert!(out.len() < input.len(), "the run must shrink");
assert_ne!(
@@ -487,7 +552,9 @@ mod tests {
}));
}
- let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT).await;
+ let out = compact_conversation(&input, "m", &model, DEFAULT_KEEP_RECENT)
+ .await
+ .expect("successful summary must not fail");
assert!(
out.len() < input.len(),
@@ -517,7 +584,9 @@ mod tests {
}
// keep_recent=4 would place the boundary mid tool-group; the guard must
// advance it so the kept tail does not begin with a tool message.
- let out = compact_conversation(&input, "m", &model, 4).await;
+ let out = compact_conversation(&input, "m", &model, 4)
+ .await
+ .expect("successful summary must not fail");
let first_kept = &out[2];
assert_ne!(
role(first_kept),
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 7301f3a25..7b3d949cc 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -1738,13 +1738,13 @@ pub(crate) async fn compact_history(
.await
.and_then(|(api_type, oauth)| converter_for(Some(&api_type), oauth)),
};
- Ok(crate::core::agent::compaction::compact_conversation(
+ crate::core::agent::compaction::compact_conversation(
messages,
model_id,
&model,
keep_recent,
)
- .await)
+ .await
}
/// Run one stateless `/goal` evaluation against `smol_model_id` (the session's
@@ -1896,7 +1896,7 @@ async fn run_turn_cycle(
model,
keep_recent,
)
- .await;
+ .await?;
if compacted.len() >= conversation_messages.len() {
return Err(e);
}
@@ -3175,6 +3175,70 @@ mod tests {
);
}
+ /// When the *target-model summarizer* itself overflows, compaction must not
+ /// fabricate a fallback-note history (which could still overflow and would
+ /// silently drop the whole span). The turn exits with the summarizer error
+ /// and no `MessagesUpdated` is published for a made-up history.
+ #[tokio::test]
+ async fn turn_cycle_surfaces_summarizer_overflow_without_fabricating_history() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let overflow = || {
+ Err(format!(
+ "[{}] Upstream returned HTTP 400: prompt is too long",
+ crate::core::agent::upstream::CONTEXT_OVERFLOW_MARKER
+ ))
+ };
+ // 1) the main request overflows, 2) the summarizer it spawned overflows too.
+ let model = ResultQueueModel {
+ results: StdMutex::new(vec![overflow(), overflow()].into_iter().collect()),
+ };
+ let tool = MockTool::default();
+ let mut budget = SessionBudget::new(None);
+ let mut convo = vec![json!({ "role": "system", "content": "sys" })];
+ for i in 0..60 {
+ let r = if i % 2 == 0 { "user" } else { "assistant" };
+ convo.push(json!({ "role": r, "content": format!("m{i}") }));
+ }
+
+ let result = run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ convo,
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await;
+
+ assert!(
+ result.is_err(),
+ "a summarizer context overflow must fail the turn"
+ );
+ assert!(
+ crate::core::agent::upstream::is_context_overflow_error(
+ result.as_ref().unwrap_err()
+ ),
+ "the summarizer overflow must propagate, not be rewritten"
+ );
+ drop(tx);
+ let mut published = false;
+ while let Ok(ev) = rx.try_recv() {
+ if let StreamEvent::MessagesUpdated { .. } = ev {
+ published = true;
+ }
+ }
+ assert!(
+ !published,
+ "no fabricated compacted history may be published"
+ );
+ }
+
#[tokio::test]
async fn turn_cycle_skips_execution_on_truncated_tool_calls() {
let (tx, _rx) = mpsc::unbounded_channel();