The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): sampler takes serialized records only
kshitijk4poora3a03d48d4aa
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex cb9509fc0f1..7e42142a089 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -12,7 +12,7 @@ import reimport timeimport uuidfrom dataclasses import dataclass-from typing import Any, Dict, List, Optional, Sequence, Tuple, Union+from typing import Any, Dict, List, Optional, Sequence, Tuplefrom agent.image_eviction_policy import outbound_image_retire_countfrom agent.auxiliary_client import (@@ -991,7 +991,7 @@ def _build_recovery_footer(session_id: str, region_len: int) -> str:# identifier-preserving session log is produced by the SAME single summary request as the narrative summary# (one auxiliary LLM call per compaction attempt, total — #96603: the earlier per-chunk digest loop made up# to 28 extra aux calls and pushed compactions to 7-11 minutes on slow aux routes). Coverage over oversized-# regions comes from even input sampling (see ``_sample_summary_input``), and exact-needle defense comes+# regions comes from even record sampling (see ``_sample_summary_records``), and exact-needle defense comes# from the LLM-free anchor index below._LEAN_SESSION_LOG_HEADING = "## Detailed Session Log (oldest first)"# Extra output-token guidance for the session-log section (single response).@@ -3631,29 +3631,6 @@ Summary generation was unavailable, so this is a best-effort deterministic fallbresult = _render(selected)return result- @classmethod- def _sample_summary_input(- cls,- content: Union[str, Sequence[str]],- records: Optional[Sequence[str]] = None,- ) -> str:- """Sample complete serialized records while retaining the character bound.-- Accepts either a sequence of serialized records (preserving record boundaries structurally)- or a flat string for backward compatibility.- """- if records is not None:- return cls._sample_summary_records(records)- if not isinstance(content, str):- return cls._sample_summary_records(content)- if len(content) <= cls._SUMMARY_INPUT_MAX_CHARS:- return content- # Discard empty trailing fragments so an empty pseudo-record cannot become the tail anchor.- records_list = [r for r in content.split("\n\n") if r.strip()]- if not records_list:- return content[:cls._SUMMARY_INPUT_MAX_CHARS]- return cls._sample_summary_records(records_list)-def _fallback_to_main_for_compression(self, e: Exception, reason: str, failed_model: Optional[str] = None) -> None:diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.pyindex f71dce10fa5..7136ba7b208 100644--- a/tests/agent/test_context_compressor.py+++ b/tests/agent/test_context_compressor.py@@ -3319,7 +3319,7 @@ class TestSummaryPromptBounding:def test_lean_sampling_keeps_record_boundaries(self):cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARSrecords = [f"[USER]: record-{i:04d} " + ("x" * 1200) for i in range(1200)]- sampled = ContextCompressor._sample_summary_input("\n\n".join(records))+ sampled = ContextCompressor._sample_summary_records(records)assert len(sampled) <= capfor record in sampled.split("\n\n"):if record.startswith("["):@@ -3327,7 +3327,7 @@ class TestSummaryPromptBounding:def test_lean_sampling_covers_multiple_regions(self):records = [f"[USER]: record-{i:04d} " + ("x" * 40) for i in range(8000)]- sampled = ContextCompressor._sample_summary_input("\n\n".join(records))+ sampled = ContextCompressor._sample_summary_records(records)assert "record-0000" in sampledassert "record-4000" in sampledassert "record-7999" in sampled@@ -3336,7 +3336,7 @@ class TestSummaryPromptBounding:cap = ContextCompressor._SUMMARY_INPUT_MAX_CHARSrecords = [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))+ sampled = ContextCompressor._sample_summary_records(records)assert len(sampled) <= capassert "newest-record-anchor" in sampledassert "...[record truncated:" in sampled@@ -3347,7 +3347,7 @@ class TestSummaryPromptBounding: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))+ sampled = ContextCompressor._sample_summary_records(records)assert len(sampled) <= capassert "newest-tail-record" in sampledassert "oversized-mid" in sampleddiff --git a/tests/agent/test_lean_single_aux_call.py b/tests/agent/test_lean_single_aux_call.pyindex 57597dbcc42..fd6ebb9c3a3 100644--- a/tests/agent/test_lean_single_aux_call.py+++ b/tests/agent/test_lean_single_aux_call.py@@ -145,16 +145,15 @@ class TestLeanSingleAuxiliaryCall:class TestSampledSummaryInput:def test_small_input_passes_through(self):- content = "abc" * 100- assert ContextCompressor._sample_summary_input(content) == content+ records = ["[USER]: abc" * 100] * 3+ assert ContextCompressor._sample_summary_records(records) == "\n\n".join(records)def test_sampling_is_bounded_ordered_and_marked(self):# Distinct decade markers let us verify oldest-to-newest order and# uniform coverage across the whole region.- content = "".join(- f"<seg{i:02d}>" + ("x" * 50_000) for i in range(10)- )- out = ContextCompressor._sample_summary_input(content)+ records = [f"<seg{i:02d}>" + ("x" * 50_000) for i in range(10)]+ content = "\n\n".join(records)+ out = ContextCompressor._sample_summary_records(records)assert len(out) <= ContextCompressor._SUMMARY_INPUT_MAX_CHARSassert "chars elided" in outseen = [i for i in range(10) if f"<seg{i:02d}>" in out]