Skip to content

Commit cdd63d3

Browse files
authored
Merge pull request #590 from OpenCoven/fix/571-compact-nothing-to-do
fix: tell "nothing to compact" apart from a finished compaction
2 parents ec6c38e + e0ba11e commit cdd63d3

5 files changed

Lines changed: 363 additions & 30 deletions

File tree

‎src-rust/crates/cli/src/goal_dispatch_tests.rs‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,21 +65,31 @@ fn goal_dispatch_recovery_blocks_actual_idle_selector() {
6565
app.context_window_size = 100;
6666
app.context_used_tokens = 99;
6767
app.auto_compact_threshold = 90;
68-
assert_eq!(select_idle_compaction(&app, false), Some(99));
68+
// Long enough to have a head to summarise (#571).
69+
let history: Vec<claurst_core::types::Message> = (0..12)
70+
.map(|n| claurst_core::types::Message::user(format!("m {n}")))
71+
.collect();
72+
assert_eq!(
73+
select_idle_compaction(&app, false, &history),
74+
Some(IdleCompaction::Start(99))
75+
);
6976
app.open_rate_limit_recovery("limited".into(), Some(60));
7077
assert_eq!(
71-
select_idle_compaction(&app, false),
78+
select_idle_compaction(&app, false, &history),
7279
None,
7380
"visible recovery must own idle time"
7481
);
7582
app.rate_limit_recovery.request_retry(None);
7683
assert_eq!(
77-
select_idle_compaction(&app, false),
84+
select_idle_compaction(&app, false, &history),
7885
None,
7986
"pending retry must own idle time"
8087
);
8188
assert!(app.rate_limit_recovery.take_retry_directive().is_some());
82-
assert_eq!(select_idle_compaction(&app, false), Some(99));
89+
assert_eq!(
90+
select_idle_compaction(&app, false, &history),
91+
Some(IdleCompaction::Start(99))
92+
);
8393
}
8494

8595
fn context(path: PathBuf) -> ToolContext {
@@ -1352,17 +1362,21 @@ fn goal_dispatch_file_preparation_blocks_idle_compaction() {
13521362
app.context_window_size = 100;
13531363
app.context_used_tokens = 99;
13541364
app.auto_compact_threshold = 90;
1365+
// Long enough to have a head to summarise (#571).
1366+
let history: Vec<claurst_core::types::Message> = (0..12)
1367+
.map(|n| claurst_core::types::Message::user(format!("m {n}")))
1368+
.collect();
13551369
app.file_injection_dialog
13561370
.show("@large.txt".into(), vec![], vec![], 1, None);
13571371
assert_eq!(
1358-
select_idle_compaction(&app, false),
1372+
select_idle_compaction(&app, false, &history),
13591373
None,
13601374
"file preparation must retain its original owner"
13611375
);
13621376
app.file_injection_dialog.dismiss();
13631377
app.file_injection_force = true;
13641378
assert_eq!(
1365-
select_idle_compaction(&app, false),
1379+
select_idle_compaction(&app, false, &history),
13661380
None,
13671381
"prepared resubmission must retain its owner"
13681382
);

‎src-rust/crates/cli/src/main.rs‎

Lines changed: 177 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2837,7 +2837,7 @@ async fn compact_idle_conversation(
28372837
result = claurst_query::compact_conversation(client, &original, model) => result,
28382838
};
28392839
match compacted {
2840-
Ok(compacted) => {
2840+
Ok(Some(compacted)) => {
28412841
let message = compacted
28422842
.first()
28432843
.cloned()
@@ -2848,6 +2848,13 @@ async fn compact_idle_conversation(
28482848
usage: claurst_core::types::UsageInfo::default(),
28492849
}
28502850
}
2851+
// `select_idle_compaction` does not start a worker for a history this
2852+
// short (#571). Should one start anyway, it ends as a failure, not as
2853+
// a compaction: the history and the context count stay as they were,
2854+
// and, as after any failure, auto-compaction is off for the session.
2855+
Ok(None) => claurst_query::QueryOutcome::Error(claurst_core::error::ClaudeError::Other(
2856+
"Too few messages to compact".to_string(),
2857+
)),
28512858
Err(err) => claurst_query::QueryOutcome::Error(err),
28522859
}
28532860
}
@@ -3063,7 +3070,21 @@ async fn persist_interactive_session(
30633070
saved
30643071
}
30653072

3066-
fn select_idle_compaction(app: &claurst_tui::App, query_running: bool) -> Option<u64> {
3073+
/// What idle auto-compaction does once the context is over its threshold.
3074+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3075+
enum IdleCompaction {
3076+
/// Summarise the history; the context is this many percent full.
3077+
Start(u64),
3078+
/// The history is too short to have a head to summarise (#571), so
3079+
/// nothing starts; the context is this many percent full.
3080+
NothingToCompact(u64),
3081+
}
3082+
3083+
fn select_idle_compaction(
3084+
app: &claurst_tui::App,
3085+
query_running: bool,
3086+
messages: &[claurst_core::types::Message],
3087+
) -> Option<IdleCompaction> {
30673088
if !app.auto_compact_enabled
30683089
|| app.context_window_size == 0
30693090
|| app.is_streaming
@@ -3078,7 +3099,34 @@ fn select_idle_compaction(app: &claurst_tui::App, query_running: bool) -> Option
30783099
return None;
30793100
}
30803101
let used_pct = (app.context_used_tokens as f64 / app.context_window_size as f64 * 100.0) as u64;
3081-
(used_pct >= u64::from(app.auto_compact_threshold)).then_some(used_pct)
3102+
if used_pct < u64::from(app.auto_compact_threshold) {
3103+
return None;
3104+
}
3105+
if claurst_query::compact::has_messages_to_compact(messages) {
3106+
Some(IdleCompaction::Start(used_pct))
3107+
} else {
3108+
Some(IdleCompaction::NothingToCompact(used_pct))
3109+
}
3110+
}
3111+
3112+
/// The context is over the auto-compact threshold but the history is too
3113+
/// short to summarise (#571). The context count is kept, since nothing was
3114+
/// summarised. The status says so once for each history length: the loop
3115+
/// asks every pass, and a turn that adds messages asks again.
3116+
fn note_nothing_to_compact(
3117+
app: &mut claurst_tui::App,
3118+
used_pct: u64,
3119+
history_len: usize,
3120+
noted_len: &mut Option<usize>,
3121+
) {
3122+
if *noted_len == Some(history_len) {
3123+
return;
3124+
}
3125+
*noted_len = Some(history_len);
3126+
app.status_message = Some(format!(
3127+
"Context {}% full — too few messages to compact yet.",
3128+
used_pct
3129+
));
30823130
}
30833131

30843132
#[derive(Debug, Clone)]
@@ -3975,6 +4023,9 @@ async fn run_interactive(
39754023
let (bg_completion_tx, mut bg_completion_rx) =
39764024
mpsc::unbounded_channel::<claurst_tools::BgTaskCompletion>();
39774025
let mut current_query: Option<(tokio::task::JoinHandle<QueryOutcome>, MessagesArc)> = None;
4026+
// History length at which idle auto-compaction last found nothing to
4027+
// compact (#571), so it says so once per length.
4028+
let mut nothing_to_compact_at: Option<usize> = None;
39784029
// Active effort level (None = use model default / High).
39794030
// Tracks the user's /effort selection; flows into qcfg each turn.
39804031
let mut current_effort: Option<claurst_core::effort::EffortLevel> = None;
@@ -5494,7 +5545,21 @@ async fn run_interactive(
54945545
// Auto-compact: when enabled and context usage reaches the configured
54955546
// threshold with no query running, summarize through the dedicated
54965547
// no-tools compaction path instead of starting an agentic turn.
5497-
if let Some(used_pct) = select_idle_compaction(&app, current_query.is_some()) {
5548+
let idle_compaction = select_idle_compaction(&app, current_query.is_some(), &messages);
5549+
if idle_compaction.is_none() {
5550+
// A turn, a cleared conversation or a lower count: say it again
5551+
// the next time there is nothing to compact.
5552+
nothing_to_compact_at = None;
5553+
}
5554+
if let Some(IdleCompaction::NothingToCompact(used_pct)) = idle_compaction {
5555+
note_nothing_to_compact(
5556+
&mut app,
5557+
used_pct,
5558+
messages.len(),
5559+
&mut nothing_to_compact_at,
5560+
);
5561+
}
5562+
if let Some(IdleCompaction::Start(used_pct)) = idle_compaction {
54985563
app.auto_compact_running = true;
54995564
app.status_message = Some(format!("Context {}% full — auto-compacting…", used_pct));
55005565

@@ -7657,6 +7722,114 @@ mod tests {
76577722
server.abort();
76587723
}
76597724

7725+
/// #571: idle compaction of a history too short to summarise is not a
7726+
/// finished compaction. No request is sent, the conversation is as it
7727+
/// was, and the status neither says it completed nor zeroes the count.
7728+
#[tokio::test]
7729+
async fn idle_compaction_of_a_short_history_is_not_reported_as_complete() {
7730+
let (client, mut requests, server) = compaction_fixture(true).await;
7731+
let history: Vec<_> = compactable_history().into_iter().take(11).collect();
7732+
let messages: MessagesArc = Arc::new(tokio::sync::Mutex::new(history.clone()));
7733+
let cancel = tokio_util::sync::CancellationToken::new();
7734+
let outcome =
7735+
compact_idle_conversation(&client, &messages, "claude-sonnet-4-6", &cancel).await;
7736+
assert_eq!(
7737+
serde_json::to_value(&*messages.lock().await).unwrap(),
7738+
serde_json::to_value(&history).unwrap(),
7739+
"the conversation is unchanged"
7740+
);
7741+
assert!(requests.try_recv().is_err(), "no summary request was sent");
7742+
7743+
let mut app = claurst_tui::App::new(Config::default(), CostTracker::new());
7744+
app.auto_compact_enabled = true;
7745+
app.auto_compact_running = true;
7746+
app.context_used_tokens = 9_000;
7747+
finish_idle_compaction(&mut app, Some(&outcome));
7748+
assert_ne!(
7749+
app.status_message.as_deref(),
7750+
Some("Auto-compact complete."),
7751+
"{outcome:?}"
7752+
);
7753+
assert_eq!(app.context_used_tokens, 9_000, "nothing was summarised");
7754+
server.abort();
7755+
}
7756+
7757+
/// #571: the worker is not started for a short history, but one that is
7758+
/// ends as a failure, the same as any other failed compaction.
7759+
#[tokio::test]
7760+
async fn an_idle_compaction_worker_given_a_short_history_fails() {
7761+
let (client, _requests, server) = compaction_fixture(true).await;
7762+
let history: Vec<_> = compactable_history().into_iter().take(11).collect();
7763+
let messages: MessagesArc = Arc::new(tokio::sync::Mutex::new(history));
7764+
let cancel = tokio_util::sync::CancellationToken::new();
7765+
let outcome =
7766+
compact_idle_conversation(&client, &messages, "claude-sonnet-4-6", &cancel).await;
7767+
assert!(
7768+
matches!(outcome, claurst_query::QueryOutcome::Error(_)),
7769+
"{outcome:?}"
7770+
);
7771+
let mut app = claurst_tui::App::new(Config::default(), CostTracker::new());
7772+
app.auto_compact_enabled = true;
7773+
app.auto_compact_running = true;
7774+
finish_idle_compaction(&mut app, Some(&outcome));
7775+
assert_eq!(
7776+
app.status_message.as_deref(),
7777+
Some("Auto-compact failed and was disabled for this session.")
7778+
);
7779+
assert!(!app.auto_compact_enabled);
7780+
server.abort();
7781+
}
7782+
7783+
/// An App whose context is 95% full, over its 90% auto-compact threshold.
7784+
fn app_with_a_full_context() -> claurst_tui::App {
7785+
let mut app = claurst_tui::App::new(Config::default(), CostTracker::new());
7786+
app.auto_compact_enabled = true;
7787+
app.auto_compact_threshold = 90;
7788+
app.context_window_size = 200_000;
7789+
app.context_used_tokens = 190_000;
7790+
app
7791+
}
7792+
7793+
/// #571: over the threshold, idle auto-compaction starts only when the
7794+
/// history has a head to summarise, that is more than 11 messages.
7795+
#[test]
7796+
fn idle_compaction_starts_only_with_a_head_to_summarise() {
7797+
let mut app = app_with_a_full_context();
7798+
let history = compactable_history();
7799+
assert_eq!(
7800+
select_idle_compaction(&app, false, &history[..11]),
7801+
Some(IdleCompaction::NothingToCompact(95))
7802+
);
7803+
assert_eq!(
7804+
select_idle_compaction(&app, false, &history[..12]),
7805+
Some(IdleCompaction::Start(95))
7806+
);
7807+
app.context_used_tokens = 100_000;
7808+
assert_eq!(select_idle_compaction(&app, false, &history[..11]), None);
7809+
}
7810+
7811+
/// #571: a full context in a short history is reported once for each
7812+
/// history length.
7813+
#[test]
7814+
fn nothing_to_compact_is_said_once_per_history_length() {
7815+
let mut app = app_with_a_full_context();
7816+
let mut noted = None;
7817+
note_nothing_to_compact(&mut app, 95, 9, &mut noted);
7818+
assert_eq!(
7819+
app.status_message.as_deref(),
7820+
Some("Context 95% full — too few messages to compact yet.")
7821+
);
7822+
app.status_message = None;
7823+
note_nothing_to_compact(&mut app, 95, 9, &mut noted);
7824+
assert_eq!(app.status_message, None, "not repeated on every pass");
7825+
note_nothing_to_compact(&mut app, 96, 11, &mut noted);
7826+
assert_eq!(
7827+
app.status_message.as_deref(),
7828+
Some("Context 96% full — too few messages to compact yet."),
7829+
"a turn that added messages is reported again"
7830+
);
7831+
}
7832+
76607833
/// #408: a worker that does not watch the token (a tool or approval that
76617834
/// ignores it) is waited for. If it finishes within `TURN_EXIT_WAIT`, the
76627835
/// conversation it wrote is what is kept. Idle auto-compaction watches the

‎src-rust/crates/cli/src/reconcile_tests.rs‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -510,15 +510,21 @@ async fn an_open_rewind_holds_compaction_and_cuts_at_the_chosen_message() {
510510
cli.app.context_window_size = 100;
511511
cli.app.context_used_tokens = 99;
512512
cli.app.auto_compact_threshold = 90;
513-
assert_eq!(select_idle_compaction(&cli.app, false), Some(99), "{case}");
513+
// Long enough to have a head to summarise (#571).
514+
let compactable: Vec<Message> = (0..12).map(|n| Message::user(format!("m {n}"))).collect();
515+
assert_eq!(
516+
select_idle_compaction(&cli.app, false, &compactable),
517+
Some(IdleCompaction::Start(99)),
518+
"{case}"
519+
);
514520

515521
// `/rewind`, as the loop runs it: the App's intercept, then the
516522
// `CommandResult::OpenRewindOverlay` arm.
517523
assert!(cli.app.intercept_slash_command_with_args("rewind", ""));
518524
cli.app.replace_messages(cli.messages.clone());
519525
cli.app.open_rewind_flow();
520526
assert_eq!(
521-
select_idle_compaction(&cli.app, false),
527+
select_idle_compaction(&cli.app, false, &compactable),
522528
None,
523529
"{case}: compaction started under the rewind"
524530
);

0 commit comments

Comments
 (0)