use supercode_harness::reduce::rehydrate::{expand_reduction, sidecar_search};
use supercode_harness::reduce::{
invert, project, project_messages, stub, ReductionKind, ReductionLog, ReductionPolicy,
};
use supercode_harness::session::Session;
use supercode_harness::{ChatMessage, FunctionCall, Role, ToolCall};
fn session_of(msgs: Vec<ChatMessage>) -> Session {
let mut session = Session::from_claude_code_str("").unwrap();
session.messages = msgs;
session
}
fn filler(len: usize) -> String {
(0..len).map(|i| (b'a' + (i % 26) as u8) as char).collect()
}
fn transcript(contents: &[&str]) -> Vec<ChatMessage> {
let mut msgs = vec![ChatMessage::user("please investigate")];
for (i, c) in contents.iter().enumerate() {
msgs.push(ChatMessage::assistant(format!("running check {i}")));
msgs.push(ChatMessage::tool_result(
format!("call_{i}"),
"bash",
c.to_string(),
));
}
msgs
}
fn no_protection_policy() -> ReductionPolicy {
ReductionPolicy {
protect_last_n_tool_results: 0,
..ReductionPolicy::default()
}
}
fn wire_bytes(msgs: &[ChatMessage]) -> usize {
msgs.iter()
.map(|m| serde_json::to_string(m).map(|s| s.len()).unwrap_or(0))
.sum()
}
#[test]
fn three_identical_outputs_dedup_to_one_full_and_two_stubs_and_invert_restores_all() {
let body = "git status\n".repeat(40); let msgs = transcript(&[&body, &body, &body]);
let session = session_of(msgs.clone());
let (view, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
let dups: Vec<_> = log
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.collect();
assert_eq!(
dups.len(),
2,
"three identical outputs must yield exactly two DuplicateOutput reductions: {:?}",
log.reductions
);
let tool_idxs = [2usize, 4, 6];
assert_eq!(
view[tool_idxs[0]].content.as_deref(),
Some(body.as_str()),
"the canonical (first) instance must remain full"
);
for &idx in &tool_idxs[1..] {
let content = view[idx].content.as_deref().unwrap();
assert!(
content.starts_with("[sc-reduced duplicate"),
"message {idx} must carry a `duplicate` stub: {content}"
);
let (kind, _, summary) = stub::parse(content).expect("stub must parse");
assert_eq!(kind, stub::Kind::Duplicate);
assert!(
summary.contains(&format!("msg #{}", tool_idxs[0])),
"stub must name the canonical address: {summary}"
);
}
for r in &dups {
match &r.kind {
ReductionKind::DuplicateOutput {
canonical,
original_bytes,
} => {
assert_eq!(canonical.index, tool_idxs[0]);
assert_eq!(canonical.role, Role::Tool);
assert_eq!(*original_bytes, body.len());
}
_ => unreachable!(),
}
}
let full_bytes = wire_bytes(&session.messages);
let reduced_bytes = wire_bytes(&view);
assert!(
reduced_bytes < full_bytes,
"reduced {reduced_bytes} must be < full {full_bytes}"
);
let inverted = invert(&view, &log, &session).unwrap();
assert_eq!(inverted.len(), session.messages.len());
for &idx in &tool_idxs {
assert_eq!(
inverted[idx].content.as_deref(),
Some(body.as_str()),
"invert must restore message {idx} byte-exact"
);
}
}
#[test]
fn near_duplicate_one_byte_different_is_never_deduped() {
let a = filler(500);
let mut b = a.clone();
unsafe {
let bytes = b.as_bytes_mut();
bytes[250] = b'Z';
}
assert_ne!(a, b);
assert_eq!(a.len(), b.len());
let msgs = transcript(&[&a, &b]);
let session = session_of(msgs.clone());
let (view, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
assert!(
!log.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. })),
"a 1-byte difference must never be deduped: {:?}",
log.reductions
);
assert_eq!(view[2].content.as_deref(), Some(a.as_str()));
assert_eq!(view[4].content.as_deref(), Some(b.as_str()));
}
#[test]
fn outputs_below_the_savings_floor_are_never_deduped_across_a_range_of_sizes() {
let threshold = ReductionPolicy::default().duplicate_output_min_bytes;
for size in [
0usize,
1,
threshold / 2,
threshold - 1,
threshold,
threshold + 1,
threshold * 3,
] {
let body = filler(size);
let msgs = transcript(&[&body, &body]);
let session = session_of(msgs);
let (_, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
let deduped = log
.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }));
if size < threshold {
assert!(
!deduped,
"size {size} is below the {threshold}B floor and must never be deduped"
);
} else {
assert!(
deduped,
"size {size} is at/above the {threshold}B floor and must be deduped"
);
}
}
}
#[test]
fn dedup_runs_before_a7_truncation_so_duplicates_are_never_independently_truncated() {
let body = filler(50_000);
let msgs = transcript(&[&body, &body, &body]);
let session = session_of(msgs.clone());
let (view, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
assert_eq!(
log.reductions.len(),
3,
"canonical (truncated by A7) + two duplicates: {:?}",
log.reductions
);
let tool_idxs = [2usize, 4, 6];
let canonical_kind = &log
.reductions
.iter()
.find(|r| r.ptr.addr.index == tool_idxs[0])
.expect("canonical must have its own reduction")
.kind;
assert!(
matches!(canonical_kind, ReductionKind::ToolOutputTruncated { .. }),
"canonical must be independently truncated by A7: {canonical_kind:?}"
);
for &idx in &tool_idxs[1..] {
let r = log
.reductions
.iter()
.find(|r| r.ptr.addr.index == idx)
.unwrap_or_else(|| panic!("message {idx} must have a reduction: {:?}", log.reductions));
assert!(
matches!(r.kind, ReductionKind::DuplicateOutput { .. }),
"message {idx} must be deduped (TR-2), not independently truncated (A7): {:?}",
r.kind
);
}
let inverted = invert(&view, &log, &session).unwrap();
for &idx in &tool_idxs {
assert_eq!(inverted[idx].content.as_deref(), Some(body.as_str()));
}
}
#[test]
fn duplicate_still_resolves_after_the_canonical_is_later_truncated_by_a7() {
let body = filler(2_000); let others = "ok";
let msgs = transcript(&[&body, &body, others, others, others, others]);
let session = session_of(msgs.clone());
let (_, log1) = project(
&session,
&ReductionPolicy::default(),
&ReductionLog::default(),
);
let dup = log1
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.expect("turn 1 must produce a DuplicateOutput reduction");
let dup_id = dup.id.clone();
assert!(
!log1
.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::ToolOutputTruncated { .. })),
"nothing should be independently truncated yet: {:?}",
log1.reductions
);
let policy2 = ReductionPolicy {
tool_output_trigger_bytes: 100,
tool_output_keep_bytes: 32,
protect_last_n_tool_results: 0,
..ReductionPolicy::default()
};
let (view2, log2) = project(&session, &policy2, &log1);
let canonical_reduction = log2
.reductions
.iter()
.find(
|r| r.ptr.addr.index == 2,
)
.expect("canonical must now have its own reduction");
assert!(
matches!(
canonical_reduction.kind,
ReductionKind::ToolOutputTruncated { .. }
),
"canonical must now be A7-truncated: {:?}",
canonical_reduction.kind
);
let dup2 = log2
.reductions
.iter()
.find(|r| r.id == dup_id)
.expect("the duplicate reduction must still be present");
assert_eq!(dup2, dup, "the duplicate reduction must reproduce verbatim");
let outcome = expand_reduction(&log2, &session.messages, None, &dup_id, None).unwrap();
assert_eq!(
outcome.content, body,
"expand_reduction must return the full original bytes"
);
assert_eq!(outcome.total_bytes, body.len());
let inverted = invert(&view2, &log2, &session).unwrap();
assert_eq!(inverted[4].content.as_deref(), Some(body.as_str()));
}
#[test]
fn duplicate_still_resolves_after_the_canonical_is_later_cleared_by_a10() {
let body = filler(500);
let mut msgs = vec![ChatMessage::user("investigate")];
msgs.push(ChatMessage::assistant("run 1"));
msgs.push(ChatMessage::tool_result("c0", "bash", body.clone())); for i in 0..10 {
msgs.push(ChatMessage::user(format!("follow-up {i}")));
msgs.push(ChatMessage::assistant(format!("reply {i}")));
}
msgs.push(ChatMessage::assistant("run 2"));
let dup_idx = msgs.len();
msgs.push(ChatMessage::tool_result("c1", "bash", body.clone())); assert_eq!(
dup_idx, 24,
"test layout assumption -- update the math below if this changes"
);
let session = session_of(msgs.clone());
let (_, log1) = project(&session, &no_protection_policy(), &ReductionLog::default());
let dup = log1
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.expect("turn 1 must dedup the identical pair");
let dup_id = dup.id.clone();
match dup.kind {
ReductionKind::DuplicateOutput { canonical, .. } => assert_eq!(canonical.index, 2),
_ => unreachable!(),
}
assert_eq!(dup.ptr.addr.index, dup_idx);
let policy2 = ReductionPolicy {
clear_turns_older_than: Some(6),
protect_last_n_tool_results: 0,
..ReductionPolicy::default()
};
let (view2, log2) = project(&session, &policy2, &log1);
let cleared = log2
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::TurnsCleared { .. }))
.expect("turn 2 must have established a TurnsCleared range");
match cleared.kind {
ReductionKind::TurnsCleared { first, last, .. } => {
assert_eq!(first, 0);
assert!(
last >= 2 && last < dup_idx,
"the cleared range must cover the canonical (2) but not the duplicate ({dup_idx}): last={last}"
);
}
_ => unreachable!(),
}
let dup2 = log2
.reductions
.iter()
.find(|r| r.id == dup_id)
.expect("the duplicate reduction must survive A10 clearing the canonical");
assert_eq!(dup2, dup);
let outcome = expand_reduction(&log2, &session.messages, None, &dup_id, None).unwrap();
assert_eq!(outcome.content, body);
let needle = &body[..24]; let pre = sidecar_search(&log1, &session.messages, None, needle).unwrap();
assert_eq!(
pre.total_matches, 0,
"canonical fully visible -> nothing reported: {pre:?}"
);
let post = sidecar_search(&log2, &session.messages, None, needle).unwrap();
assert!(
post.matches.iter().any(|m| m.reduction_id == dup_id),
"canonical cleared -> the duplicate must be searchable: {post:?}"
);
let inverted = invert(&view2, &log2, &session).unwrap();
assert_eq!(inverted[dup_idx].content.as_deref(), Some(body.as_str()));
}
#[test]
fn dedup_is_deterministic_and_prefix_stable() {
let body = filler(1000);
let msgs = transcript(&[&body, &body, &body]);
let session = session_of(msgs);
let policy = no_protection_policy();
let (view1, log1) = project(&session, &policy, &ReductionLog::default());
let (view2, log2) = project(&session, &policy, &ReductionLog::default());
assert_eq!(log1, log2, "project() must be deterministic for TR-2 too");
assert_eq!(
view1.iter().map(|m| m.content.clone()).collect::<Vec<_>>(),
view2.iter().map(|m| m.content.clone()).collect::<Vec<_>>()
);
let mut grown = session.clone();
grown.messages.push(ChatMessage::user("one more thing"));
grown.messages.push(ChatMessage::assistant("sure"));
let (_, log3) = project(&grown, &policy, &log1);
assert_eq!(
log3.reductions.len(),
log1.reductions.len(),
"re-projecting with a stable prior log must not invent new reductions"
);
for r in &log1.reductions {
let r3 = log3
.reductions
.iter()
.find(|x| x.id == r.id)
.expect("prior reduction id must survive re-projection");
assert_eq!(r3, r, "reduction {} must reproduce verbatim", r.id);
}
}
#[test]
fn dedup_works_through_project_messages_directly() {
let body = filler(300);
let msgs = transcript(&[&body, &body]);
let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
assert_eq!(log.reductions.len(), 1);
assert!(matches!(
log.reductions[0].kind,
ReductionKind::DuplicateOutput { .. }
));
assert_eq!(view[2].content.as_deref(), Some(body.as_str()));
assert!(view[4]
.content
.as_deref()
.unwrap()
.starts_with("[sc-reduced duplicate"));
}
fn transcript_named(contents: &[&str], name: &str) -> Vec<ChatMessage> {
let mut msgs = vec![ChatMessage::user("please investigate")];
for (i, c) in contents.iter().enumerate() {
msgs.push(ChatMessage::assistant(format!("running check {i}")));
msgs.push(ChatMessage::tool_result(
format!("call_{i}"),
name,
c.to_string(),
));
}
msgs
}
#[test]
fn long_tool_name_near_the_floor_never_mints_a_negative_savings_stub() {
let body = filler(300);
let long_name = "x".repeat(400);
let msgs = transcript_named(&[&body, &body], &long_name);
let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
assert!(
!log.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. })),
"a stub longer than the content it replaces must never be minted: {:?}",
log.reductions
);
assert_eq!(view[2].content.as_deref(), Some(body.as_str()));
assert_eq!(view[4].content.as_deref(), Some(body.as_str()));
let msgs_short = transcript_named(&[&body, &body], "bash");
let (_, log_short) = project_messages(
&msgs_short,
&no_protection_policy(),
&ReductionLog::default(),
);
let dup = log_short
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.expect("the same pair with a short name must be minted");
assert!(
dup.placeholder.len() < body.len(),
"every minted duplicate stub must be strictly smaller than what it replaces"
);
}
#[test]
fn search_skips_duplicates_whose_canonical_is_fully_visible() {
let body = format!("{}UNIQUE-NEEDLE-42{}", filler(200), filler(200));
let msgs = transcript(&[&body, &body, &body]);
let (_, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
let dup_ids: Vec<String> = log
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.map(|r| r.id.clone())
.collect();
assert_eq!(dup_ids.len(), 2, "{:?}", log.reductions);
let hits = sidecar_search(&log, &msgs, None, "UNIQUE-NEEDLE-42").unwrap();
assert_eq!(
hits.total_matches, 0,
"content visible in the view (via the unreduced canonical) must not \
be reported: {hits:?}"
);
assert_eq!(hits.unresolvable, 0, "skipped-as-visible is not an error");
for id in &dup_ids {
let outcome = expand_reduction(&log, &msgs, None, id, None).unwrap();
assert_eq!(outcome.content, body);
}
}
#[test]
fn search_reports_duplicates_once_the_canonical_is_itself_reduced() {
let body = format!("{}HIDDEN-NEEDLE-77{}", filler(200), filler(1800));
let msgs = transcript(&[&body, &body, "ok-a", "ok-b", "ok-c", "ok-d"]);
let session = session_of(msgs.clone());
let (_, log1) = project(
&session,
&ReductionPolicy::default(),
&ReductionLog::default(),
);
let dup_id = log1
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.expect("turn 1 must dedup the identical pair")
.id
.clone();
let hits1 = sidecar_search(&log1, &session.messages, None, "HIDDEN-NEEDLE-77").unwrap();
assert_eq!(hits1.total_matches, 0, "{hits1:?}");
let policy2 = ReductionPolicy {
tool_output_trigger_bytes: 100,
tool_output_keep_bytes: 32,
protect_last_n_tool_results: 0,
..ReductionPolicy::default()
};
let (_, log2) = project(&session, &policy2, &log1);
assert!(log2
.reductions
.iter()
.any(|r| r.ptr.addr.index == 2
&& matches!(r.kind, ReductionKind::ToolOutputTruncated { .. })));
let hits2 = sidecar_search(&log2, &session.messages, None, "HIDDEN-NEEDLE-77").unwrap();
assert!(
hits2.matches.iter().any(|m| m.reduction_id == dup_id),
"the duplicate must be searchable once its canonical is reduced: {hits2:?}"
);
let out1 = expand_reduction(&log1, &session.messages, None, &dup_id, None).unwrap();
assert_eq!(out1.content, body);
let out2 = expand_reduction(&log2, &session.messages, None, &dup_id, None).unwrap();
assert_eq!(out2.content, body);
}
#[test]
fn hostile_tool_name_never_panics_and_mints_a_parseable_stub() {
let body = filler(400);
let msgs = transcript_named(&[&body, &body], "weird]name\nx");
let (view, log) = project_messages(&msgs, &no_protection_policy(), &ReductionLog::default());
let dup = log
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.expect("the hostile-named pair must still dedup");
let (kind, id, summary) =
stub::parse(&dup.placeholder).expect("the minted stub must satisfy the grammar");
assert_eq!(kind, stub::Kind::Duplicate);
assert_eq!(id, dup.id);
assert!(
summary.contains("weird_name_x"),
"hostile characters must be visibly replaced, not dropped: {summary}"
);
let session = session_of(msgs.clone());
let inverted = invert(&view, &log, &session).unwrap();
assert_eq!(inverted[4].content.as_deref(), Some(body.as_str()));
assert_eq!(inverted[4].name.as_deref(), Some("weird]name\nx"));
let big = filler(20_000);
let msgs_a7 = transcript_named(&[&big], "weird]name\nx");
let (_, log_a7) = project_messages(&msgs_a7, &no_protection_policy(), &ReductionLog::default());
let trunc = log_a7
.reductions
.iter()
.find(|r| matches!(r.kind, ReductionKind::ToolOutputTruncated { .. }))
.expect("the oversized output must truncate");
assert!(
stub::parse(&trunc.placeholder).is_some(),
"A7's stub must satisfy the grammar too: {}",
trunc.placeholder
);
}
fn read_call(id: &str, path: &str) -> ChatMessage {
ChatMessage {
role: Role::Assistant,
content: None,
content_parts: None,
tool_calls: Some(vec![ToolCall {
id: id.to_string(),
kind: "function".to_string(),
function: FunctionCall {
name: "read_file".to_string(),
arguments: serde_json::json!({ "path": path }).to_string(),
},
}]),
tool_call_id: None,
name: None,
metadata: Default::default(),
}
}
#[test]
fn tr2_still_dedups_identical_content_reads_of_different_paths() {
let body = filler(500); let msgs = vec![
ChatMessage::user("read two files"),
read_call("c1", "src/a.rs"),
ChatMessage::tool_result("c1", "read_file", body.clone()),
ChatMessage::user("read the other one"),
read_call("c2", "src/b.rs"),
ChatMessage::tool_result("c2", "read_file", body.clone()),
];
let idx_a = 2;
let idx_b = 5;
let session = session_of(msgs.clone());
let (view, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
let dups: Vec<_> = log
.reductions
.iter()
.filter(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. }))
.collect();
assert_eq!(
dups.len(),
1,
"cross-path identical reads must still dedup under TR-2: {:?}",
log.reductions
);
assert_eq!(
dups[0].ptr.addr.index, idx_b,
"the later (path b) read becomes the DuplicateOutput"
);
match dups[0].kind {
ReductionKind::DuplicateOutput { canonical, .. } => {
assert_eq!(
canonical.index, idx_a,
"the earlier (path a) read is canonical"
)
}
_ => unreachable!(),
}
assert_eq!(
view[idx_a].content.as_deref(),
Some(body.as_str()),
"the canonical (first) read stays full"
);
assert!(
view[idx_b]
.content
.as_deref()
.unwrap()
.starts_with("[sc-reduced duplicate"),
"the second (different-path) read must carry a `duplicate` stub: {:?}",
view[idx_b].content
);
let inverted = invert(&view, &log, &session).unwrap();
assert_eq!(inverted[idx_a].content.as_deref(), Some(body.as_str()));
assert_eq!(
inverted[idx_b].content.as_deref(),
Some(body.as_str()),
"invert must restore the cross-path duplicate byte-exact"
);
}
#[test]
fn tr2_never_dedups_identical_content_reads_of_the_same_path() {
let body = filler(500);
let msgs = vec![
ChatMessage::user("read the file twice"),
read_call("c1", "src/a.rs"),
ChatMessage::tool_result("c1", "read_file", body.clone()),
ChatMessage::user("read it again"),
read_call("c2", "src/a.rs"),
ChatMessage::tool_result("c2", "read_file", body.clone()),
];
let session = session_of(msgs.clone());
let (_, log) = project(&session, &no_protection_policy(), &ReductionLog::default());
assert!(
!log.reductions
.iter()
.any(|r| matches!(r.kind, ReductionKind::DuplicateOutput { .. })),
"same-path identical re-reads belong to A8/TR-3, never TR-2: {:?}",
log.reductions
);
assert!(
log.reductions.is_empty(),
"no reduction at all is expected here: {:?}",
log.reductions
);
}