The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: bound oversized records and protect newest slice in lean summary sampling
joaomarcos723fc9ffb577
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 4f21d64c414..b0300acd2cf 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -3523,6 +3523,27 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb# Lean-mode sampling slice count: 8 keeps slices ~20K chars at the 160K cap._SAMPLED_INPUT_SLICES = 8+ @classmethod+ def _bound_oversized_record(cls, record: str, limit: int) -> str:+ """Bound an oversized record with an explicit intra-record truncation marker."""+ if len(record) <= limit:+ return record+ marker_template = "\n...[record truncated: {elided:,} chars elided — recover via session_search]...\n"+ marker_reserve = len(marker_template.format(elided=len(record)))+ if limit <= marker_reserve:+ return record[:limit]+ remaining = limit - marker_reserve+ head_len = int(remaining * 0.5)+ tail_len = remaining - head_len+ head = record[:head_len].rstrip("\n")+ tail = record[-tail_len:].lstrip("\n") if tail_len else ""+ elided = len(record) - len(head) - len(tail)+ marker = marker_template.format(elided=elided)+ res = head + marker + tail+ if len(res) > limit:+ res = head[:max(0, head_len - (len(res) - limit))] + marker + tail+ return res+@classmethoddef _sample_summary_input(cls, content: str) -> str:"""Sample complete serialized records while retaining the character bound."""@@ -3532,46 +3553,68 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbrecords = content.split("\n\n")separator = "\n\n"marker_template = "\n\n...[{elided:,} chars elided — recover via session_search]...\n\n"+ n = max(1, min(cls._SAMPLED_INPUT_SLICES, len(records)))marker_len = len(marker_template.format(elided=len(content)))- budget = max(cls._SUMMARY_INPUT_MAX_CHARS - marker_len * (cls._SAMPLED_INPUT_SLICES - 1), 1)- target = max(1, budget // cls._SAMPLED_INPUT_SLICES)- starts = [round(i * len(records) / cls._SAMPLED_INPUT_SLICES) for i in range(cls._SAMPLED_INPUT_SLICES)]+ budget = max(cls._SUMMARY_INPUT_MAX_CHARS - marker_len * (n - 1), 1)+ target = max(1, budget // n)++ # Oversized records are bounded to slice target with explicit intra-record truncation markers+ # so they cannot consume other regions' budget or evict the newest record.+ display_records = [cls._bound_oversized_record(r, target) for r in records]++ starts = [round(i * len(records) / n) for i in range(n)]selected: list[tuple[int, int]] = []for index, start in enumerate(starts):- end = start- size = 0- while end < len(records) and (size == 0 or size + len(records[end]) + len(separator) <= target):- size += len(records[end]) + (len(separator) if end > start else 0)- end += 1if index == len(starts) - 1:start = max(0, len(records) - 1)end = len(records)- selected.append((start, end))-- parts: list[str] = []- cursor = 0- for start, end in selected:- if start > cursor:- parts.append(marker_template.format(elided=sum(map(len, records[cursor:start])) + len(separator) * (start - cursor)))- parts.append(separator.join(records[start:end]))- cursor = end- if cursor < len(records):- parts.append(marker_template.format(elided=sum(map(len, records[cursor:])) + len(separator) * (len(records) - cursor - 1)))- result = "".join(parts)+ else:+ end = start+ size = 0+ while end < len(records) and (size == 0 or size + len(display_records[end]) + len(separator) <= target):+ size += len(display_records[end]) + (len(separator) if end > start else 0)+ end += 1+ if end > start:+ if selected and start <= selected[-1][1]:+ prev_start, prev_end = selected.pop()+ selected.append((prev_start, max(prev_end, end)))+ else:+ selected.append((start, end))++ def _render(slices: list[tuple[int, int]]) -> str:+ parts: list[str] = []+ cursor = 0+ for s, e in slices:+ if s > cursor:+ elided = sum(map(len, records[cursor:s])) + len(separator) * (s - cursor)+ parts.append(marker_template.format(elided=elided))+ parts.append(separator.join(display_records[s:e]))+ cursor = e+ if cursor < len(records):+ elided = sum(map(len, records[cursor:])) + len(separator) * (len(records) - cursor - 1)+ parts.append(marker_template.format(elided=elided))+ return "".join(parts)++ result = _render(selected)if len(result) <= cls._SUMMARY_INPUT_MAX_CHARS:return result- # Marker width varies with the omitted count; trim only at record boundaries.++ # Overflow trim: protect newest slice, trim or drop preceding slices first.while len(result) > cls._SUMMARY_INPUT_MAX_CHARS and selected:- index = max(range(len(selected)), key=lambda i: selected[i][1] - selected[i][0])- start, end = selected[index]- if end - start > 1:- selected[index] = (start, end - 1)+ if len(selected) > 1:+ idx = max(range(len(selected) - 1), key=lambda i: selected[i][1] - selected[i][0])+ s, e = selected[idx]+ if e - s > 1:+ selected[idx] = (s, e - 1)+ else:+ selected.pop(idx)else:- selected.pop(index)- parts = [separator.join(records[a:b]) for a, b in selected]- result = marker_template.format(- elided=max(0, len(content) - sum(len(p) for p in parts))- ).join(parts)+ s, e = selected[0]+ if e - s > 1:+ selected[0] = (s + 1, e)+ else:+ break+ result = _render(selected)return resultdef _fallback_to_main_for_compression(diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex e2dbf2d7218..5cfd584c4a2 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -3331,9 +3331,26 @@ class TestSummaryPromptBounding:assert "record-4000" in sampledassert "record-7999" in sampled+ def test_lean_sampling_preserves_oversized_last_record(self):+ cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARS+ records = [f"[USER]: record-{i:04d}" for i in range(100)]+ records.append("[USER]: newest-record-anchor " + ("z" * (cap + 5000)))+ sampled = ContextCompressor._sample_summary_input("\n\n".join(records))+ assert len(sampled) <= cap+ assert "newest-record-anchor" in sampled+ assert "...[record truncated:" in sampled--+ def test_lean_sampling_oversized_middle_record_does_not_evict_tail(self):+ cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARS+ records = [f"[USER]: record-{i:04d}" for i in range(50)]+ records.append("[TOOL RESULT oversized-mid]: " + ("y" * (cap + 5000)))+ records.extend([f"[USER]: record-{i:04d}" for i in range(51, 100)])+ records.append("[USER]: newest-tail-record")+ sampled = ContextCompressor._sample_summary_input("\n\n".join(records))+ assert len(sampled) <= cap+ assert "newest-tail-record" in sampled+ assert "oversized-mid" in sampled+ assert "...[record truncated:" in sampleddef test_iterative_update_path_is_bounded(self):"""The iterative prompt (previous summary + new turns) must be bounded