use super::*;
use super::test_support::{
active_prompt_card, assistant_call, recording_summarizer, run, run_count_only, sys, tool_heavy,
tool_result, user, EST,
};
use serde_json::json;
use std::sync::{Arc, Mutex};
async fn run_non_authoritative(
messages: &[Value],
budget: usize,
max_messages: Option<usize>,
summarizer: Option<&SummarizeFn>,
state: &mut CompressState,
) -> CompressOutcome {
compress(
CompressRequest {
rewrites_history: true,
messages,
budget,
max_messages,
replay_protected_tail_len: 0,
task: "fix the failing test",
hard_budget: true,
authoritative: false,
focus: None,
est: EST,
summary_input_cap_floor_chars: 8_192,
compaction_store: None,
compaction_stage: None,
},
summarizer,
state,
)
.await
}
#[tokio::test]
async fn count_only_never_feeds_or_consults_anti_thrash() {
let mut msgs = vec![sys("you are newt"), user("task")];
for i in 0..10 {
msgs.push(user(&format!("note {i}")));
}
let mut state = CompressState::new();
for _ in 0..4 {
let budget = estimate_tokens(&msgs, EST) / 2;
let out = run_count_only(&msgs, budget, Some(6), None, &mut state).await;
assert_ne!(out.action, CompressAction::Refused);
}
assert!(!state.disabled, "count-only passes must never latch");
assert_eq!(state.attempts, 0, "count-only passes must never record");
let mut latched = CompressState::new();
latched.disabled = true;
latched.notified = true;
let budget = estimate_tokens(&msgs, EST) / 2;
let out = run_count_only(&msgs, budget, Some(6), None, &mut latched).await;
assert_ne!(out.action, CompressAction::Refused);
assert!(
out.messages.len() < msgs.len(),
"the VRAM guard must stay alive while anti-thrash is latched"
);
}
fn push_tool_round(msgs: &mut Vec<Value>, round: usize) {
msgs.push(assistant_call(
"read_file",
json!({"path": format!("src/f{round}.rs")}),
));
msgs.push(tool_result(&format!("{round}:{}", "x".repeat(300))));
}
#[tokio::test]
async fn repeated_pruned_rounds_under_headroom_aware_proactively_escalate() {
let budget = 3_000usize;
let mut msgs = vec![
sys("you are newt"),
active_prompt_card(),
user("fix the bug"),
];
let mut state = CompressState::new();
let mut escalated: Option<(usize, FloorTrend)> = None;
for round in 0..80 {
push_tool_round(&mut msgs, round);
let trend_before = state.floor_trend();
let out = run(&msgs, budget, None, None, &mut state).await;
assert_ne!(
out.action,
CompressAction::Refused,
"round {round}: must never refuse — nothing here is irreducible"
);
msgs = out.messages.clone();
if matches!(
out.action,
CompressAction::Summarized | CompressAction::StaticFallback
) {
escalated = Some((round, trend_before));
break;
}
assert!(
matches!(out.action, CompressAction::Fit | CompressAction::Pruned),
"round {round}: expected Fit-or-Pruned before escalation, got {:?}",
out.action
);
}
let (round, trend_before) = escalated.expect(
"the pipeline never escalated past structural-pruned-only across 80 \
rounds of a growing transcript — the accreting floor should have \
crossed the proactive threshold well before this",
);
let trend = state.floor_trend();
assert_ne!(
trend, trend_before,
"round {round}: no NEW floor reading landed on the escalating round \
itself — `record_floor` only fires from a genuine settle-then-maybe-\
override branch, so an unchanged trend here means this escalation \
was the pre-existing REACTIVE (over-budget) path, which skips that \
branch entirely, not a proactive one: {trend:?}"
);
let latest = trend.latest.expect(
"a floor reading must have been recorded for the round that escalated \
(`compress` records it before the proactive check can override the \
settle) — got no reading at all",
);
assert!(
latest < 1.0,
"round {round}: escalation must be PROACTIVE — the internal post-prune \
floor fraction that triggered it ({latest}) must still be within \
budget (< 1.0); a value >= 1.0 would mean this was only the \
pre-existing REACTIVE over-budget path: {trend:?}"
);
assert!(
latest >= PROACTIVE_SUMMARIZE_FLOOR_FRACTION,
"round {round}: the recorded floor fraction ({latest}) must have \
crossed the proactive threshold ({PROACTIVE_SUMMARIZE_FLOOR_FRACTION}) \
to explain why this round escalated: {trend:?}"
);
assert!(
trend.rising(),
"the floor trend across the settled prune-only rounds leading up to \
escalation must show a RISE — the accretion the issue's evidence \
found invisible: {trend:?}"
);
}
fn push_big_tool_round(msgs: &mut Vec<Value>, round: usize) {
msgs.push(assistant_call(
"read_file",
json!({"path": format!("src/f{round}.rs")}),
));
msgs.push(tool_result(&format!("{round}:{}", "x".repeat(5_000))));
}
#[tokio::test]
async fn a_healthy_session_with_a_stable_floor_never_proactively_escalates() {
let budget = 20_000usize;
let mut msgs = vec![
sys("you are newt"),
active_prompt_card(),
user("fix the bug"),
];
let mut state = CompressState::new();
let mut prune_engaged = false;
for round in 0..80 {
push_big_tool_round(&mut msgs, round);
let out = run(&msgs, budget, None, None, &mut state).await;
assert!(
matches!(out.action, CompressAction::Fit | CompressAction::Pruned),
"round {round}: a healthy, far-under-threshold floor must never \
escalate to summarize, got {:?}",
out.action
);
prune_engaged |= out.action == CompressAction::Pruned;
msgs = out.messages.clone();
}
assert!(
prune_engaged,
"structural prune was never exercised across 80 rounds — this twin \
proves nothing about the proactive threshold if the code path it \
gates was never reached"
);
}
#[test]
fn floor_trend_starts_unrecorded_and_is_never_rising() {
let state = CompressState::new();
let trend = state.floor_trend();
assert_eq!(trend.previous, None);
assert_eq!(trend.latest, None);
assert!(!trend.rising());
}
#[test]
fn floor_trend_detects_a_rise_across_two_recordings() {
let mut state = CompressState::new();
state.record_floor(2_500, 10_000); state.record_floor(7_500, 10_000); let trend = state.floor_trend();
assert_eq!(trend.previous, Some(0.25));
assert_eq!(trend.latest, Some(0.75));
assert!(trend.rising(), "{trend:?}");
}
#[test]
fn floor_trend_does_not_report_rising_when_the_floor_holds_or_shrinks() {
let mut state = CompressState::new();
state.record_floor(7_500, 10_000);
state.record_floor(7_500, 10_000); assert!(
!state.floor_trend().rising(),
"holding: {:?}",
state.floor_trend()
);
state.record_floor(2_500, 10_000); assert!(
!state.floor_trend().rising(),
"shrinking: {:?}",
state.floor_trend()
);
}
#[test]
fn record_floor_is_a_defensive_noop_on_a_zero_budget() {
let mut state = CompressState::new();
state.record_floor(1_000, 0);
assert_eq!(
state.floor_trend(),
FloorTrend {
previous: None,
latest: None
}
);
}
#[tokio::test]
async fn anti_thrash_disables_notifies_once_then_refuses() {
let mut msgs = vec![sys("small protected system"), user("task")];
for i in 0..3 {
msgs.push(user(&format!("note {i} {}", "x".repeat(4_000))));
}
let mut state = CompressState::new();
let first = run(&msgs, 100, None, None, &mut state).await;
assert_ne!(first.action, CompressAction::Refused);
assert!(first.notice.is_none(), "one poor pass is not yet thrash");
let second = run(&msgs, 100, None, None, &mut state).await;
let notice = second.notice.expect("second poor pass must notify");
assert!(notice.contains("disabled for this session"), "{notice}");
let third = run(&msgs, 100, None, None, &mut state).await;
assert_eq!(third.action, CompressAction::Refused);
assert!(!third.fired);
assert!(
third.notice.is_none(),
"the notice must be delivered exactly once"
);
let ok = run(&msgs, 100_000, None, None, &mut state).await;
assert_eq!(ok.action, CompressAction::Fit);
}
#[tokio::test]
async fn non_authoritative_budget_fails_open_instead_of_refusing() {
let mut msgs = vec![sys("small protected system"), user("task")];
for i in 0..3 {
msgs.push(user(&format!("note {i} {}", "x".repeat(4_000))));
}
let mut state = CompressState::new();
let first = run_non_authoritative(&msgs, 100, None, None, &mut state).await;
assert_ne!(first.action, CompressAction::Refused);
let _second = run_non_authoritative(&msgs, 100, None, None, &mut state).await;
assert!(state.disabled, "two poor passes must latch the breaker");
let third = run_non_authoritative(&msgs, 100, None, None, &mut state).await;
assert_eq!(third.action, CompressAction::DispatchedOverBudget);
assert!(!third.fired, "messages pass through unchanged");
assert_eq!(third.messages.len(), msgs.len(), "nothing dropped");
let notice = third.notice.expect("fail-open is surfaced once");
assert!(notice.contains("no authoritative window"), "{notice}");
let fourth = run_non_authoritative(&msgs, 100, None, None, &mut state).await;
assert_eq!(fourth.action, CompressAction::DispatchedOverBudget);
assert!(fourth.notice.is_none(), "notice delivered exactly once");
}
#[tokio::test]
async fn authoritative_budget_still_refuses_when_latched() {
let mut msgs = vec![sys("small protected system"), user("task")];
for i in 0..3 {
msgs.push(user(&format!("note {i} {}", "x".repeat(4_000))));
}
let mut state = CompressState::new();
run(&msgs, 100, None, None, &mut state).await;
run(&msgs, 100, None, None, &mut state).await;
assert!(state.disabled);
let third = run(&msgs, 100, None, None, &mut state).await;
assert_eq!(
third.action,
CompressAction::Refused,
"an authoritative ceiling must still refuse, not truncate"
);
}
#[tokio::test]
async fn authoritative_budget_refuses_irreducible_prompt_before_any_summary() {
let exact = format!("GIANT-EXACT-PROMPT {}", "z".repeat(20_000));
let messages = vec![sys("base"), active_prompt_card(), user(&exact)];
let prompts = Arc::new(Mutex::new(Vec::new()));
let summarizer = recording_summarizer(prompts.clone(), "must not run");
let mut state = CompressState::new();
let out = compress(
CompressRequest {
rewrites_history: true,
messages: &messages,
budget: 128,
max_messages: None,
replay_protected_tail_len: 0,
task: &exact,
hard_budget: true,
authoritative: true,
focus: None,
est: EST,
summary_input_cap_floor_chars: 8_192,
compaction_store: None,
compaction_stage: None,
},
Some(&*summarizer),
&mut state,
)
.await;
assert_eq!(out.action, CompressAction::Refused);
assert_eq!(out.messages, messages, "exact prompt is never truncated");
assert!(prompts.lock().unwrap().is_empty(), "no summary dispatch");
}
#[tokio::test]
async fn latched_authoritative_compacts_to_marker_instead_of_refusing() {
let mut msgs = vec![sys("sys"), user("task")];
for i in 0..24 {
msgs.push(user(&format!("middle note {i} {}", "m".repeat(200))));
}
msgs.push(user("recent tail"));
let mut state = CompressState::new();
state.latch_disabled_for_tests();
let budget = 300; let out = run(&msgs, budget, None, None, &mut state).await;
assert_ne!(
out.action,
CompressAction::Refused,
"a reducible middle must compact to a marker, not dead-end"
);
assert!(
out.tokens_after <= budget,
"forced marker compaction must fit the budget ({} > {budget})",
out.tokens_after
);
assert!(out.fired, "the marker compaction changed the working set");
}
#[tokio::test]
async fn effective_compressions_do_not_disable() {
let mut state = CompressState::new();
for _ in 0..4 {
let msgs = tool_heavy("task", 6, 4_000);
let before = estimate_tokens(&msgs, EST);
let out = run(&msgs, before / 3, None, None, &mut state).await;
assert_ne!(out.action, CompressAction::Refused);
assert!(out.notice.is_none());
}
assert!(!state.disabled);
}
#[test]
fn thrash_window_requires_consecutive_poor_savings() {
let mut state = CompressState::new();
state.record(1_000, 990, 500); state.record(1_000, 400, 500); state.record(1_000, 990, 500); assert!(!state.disabled, "non-consecutive poor passes never disable");
state.record(1_000, 950, 500); assert!(state.disabled);
}
#[test]
fn budget_aware_gap_progress_is_not_a_strike() {
let mut state = CompressState::new();
state.record(1_000, 920, 800);
state.record(1_000, 920, 800);
assert!(
!state.is_disabled(),
"gap-shrinking passes must not latch the disable"
);
let mut dead = CompressState::new();
dead.record(1_000, 995, 500);
dead.record(1_000, 996, 500);
assert!(dead.is_disabled(), "truly ineffective passes still latch");
}
#[test]
fn counters_snapshot_projects_state() {
let mut state = CompressState::new();
let c = state.counters();
assert_eq!((c.compressions, c.strikes, c.disabled), (0, 0, false));
assert_eq!(c.last_reclaim, None);
state.record(1_000, 400, 500); let c = state.counters();
assert_eq!((c.compressions, c.strikes, c.disabled), (1, 0, false));
assert!((c.last_reclaim.unwrap() - 0.6).abs() < 0.01);
state.record(1_000, 990, 500); let c = state.counters();
assert_eq!((c.compressions, c.strikes, c.disabled), (2, 1, false));
state.record(1_000, 950, 500); let c = state.counters();
assert_eq!((c.compressions, c.strikes, c.disabled), (3, 2, true));
assert!(c.last_reclaim.unwrap() < THRASH_MIN_SAVINGS);
}
#[test]
fn counters_first_poor_attempt_is_one_strike() {
let mut state = CompressState::new();
state.record(1_000, 990, 500);
assert_eq!(state.counters().strikes, 1);
}