Skip to content

The agent that grows with you

feat(agent): record summary-input coverage telemetry (from #118390)

kshitijk4poor33a1d46dfca0
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 7e42142a089..dc2e00418cb 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -3548,20 +3548,50 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
res = head[:max(0, head_len - (len(res) - limit))] + marker + tail
return res
+ def _record_summary_input_coverage(self, coverage: Dict[str, int]) -> None:
+ """Expose lean sampling coverage without including transcript content in telemetry."""
+ telemetry = getattr(self, "_active_compression_telemetry", None)
+ if not isinstance(telemetry, dict):
+ return
+ telemetry.update({
+ "summary_input_chars": coverage["input_chars"],
+ "summary_input_sampled_chars": coverage["sampled_chars"],
+ "summary_input_omitted_chars": coverage["omitted_chars"],
+ "summary_input_record_count": coverage["record_count"],
+ "summary_input_sampled_record_count": coverage["sampled_record_count"],
+ "summary_input_elided_record_count": coverage["elided_record_count"],
+ })
+
@classmethod
- def _sample_summary_records(cls, records: Sequence[str]) -> str:
- """Sample complete serialized records while retaining the character bound."""
+ def _sample_summary_records(cls, records: Sequence[str]) -> Tuple[str, Dict[str, int]]:
+ """Sample complete serialized records while retaining the character bound.
+
+ Returns the bounded transcript and record-level coverage counters (chars count record
+ content only, not separators or elision markers) for compression telemetry.
+ """
+ input_chars = sum(len(r) for r in records)
+
+ def _coverage(sampled_chars: int, sampled_record_count: int) -> Dict[str, int]:
+ return {
+ "input_chars": input_chars, "sampled_chars": sampled_chars,
+ "omitted_chars": input_chars - sampled_chars, "record_count": len(records),
+ "sampled_record_count": sampled_record_count,
+ "elided_record_count": len(records) - sampled_record_count,
+ }
+
if not records:
- return ""
+ return "", _coverage(0, 0)
separator = "\n\n"
- total_len = sum(len(r) for r in records) + len(separator) * (len(records) - 1)
+ total_len = input_chars + len(separator) * (len(records) - 1)
if total_len <= cls._SUMMARY_INPUT_MAX_CHARS:
- return separator.join(records)
+ return separator.join(records), _coverage(input_chars, len(records))
n = max(1, min(cls._SAMPLED_INPUT_SLICES, len(records)))
- marker_template = "\n\n...[{elided:,} chars elided — recover via session_search]...\n\n"
- marker_len = len(marker_template.format(elided=total_len))
+ marker_template = (
+ "\n\n...[records {first:,}-{last:,}: {elided:,} chars elided — recover via session_search]...\n\n"
+ )
+ marker_len = len(marker_template.format(first=len(records), last=len(records), elided=total_len))
budget = max(cls._SUMMARY_INPUT_MAX_CHARS - marker_len * (n - 1), 1)
target = max(1, budget // n)
@@ -3600,18 +3630,22 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
if s > cursor:
sep_count = (s - cursor) if cursor == 0 else (s - cursor + 1)
elided = sum(len(records[i]) for i in range(cursor, s)) + len(separator) * sep_count
- parts.append(marker_template.format(elided=elided))
+ parts.append(marker_template.format(first=cursor + 1, last=s, elided=elided))
parts.append(separator.join(display_records[s:e]))
cursor = e
if cursor < len(records):
sep_count = len(records) - cursor
elided = sum(len(records[i]) for i in range(cursor, len(records))) + len(separator) * sep_count
- parts.append(marker_template.format(elided=elided))
+ parts.append(marker_template.format(first=cursor + 1, last=len(records), elided=elided))
return "".join(parts)
+ def _finish(text: str) -> Tuple[str, Dict[str, int]]:
+ shown = [i for s, e in selected for i in range(s, e)]
+ return text, _coverage(sum(len(display_records[i]) for i in shown), len(shown))
+
result = _render(selected)
if len(result) <= cls._SUMMARY_INPUT_MAX_CHARS:
- return result
+ return _finish(result)
# Overflow trim: protect newest slice, trim or drop preceding slices first.
while len(result) > cls._SUMMARY_INPUT_MAX_CHARS and selected:
@@ -3629,7 +3663,7 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
else:
break
result = _render(selected)
- return result
+ return _finish(result)
def _fallback_to_main_for_compression(
self, e: Exception, reason: str, failed_model: Optional[str] = None
@@ -3775,7 +3809,8 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
# Lean mode even-samples oversized input (one bounded request, never a second).
if getattr(self, "tail_mode", "lean") == "lean":
records = self._serialize_records_for_summary(turns_to_summarize)
- content_to_summarize = self._sample_summary_records(records)
+ content_to_summarize, coverage = self._sample_summary_records(records)
+ self._record_summary_input_coverage(coverage)
else:
content_to_summarize = self._bound_summary_input(self._serialize_for_summary(turns_to_summarize))
has_user_turn = getattr(self, "_summary_has_user_turn", None)
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 8fe4c00a1a6..5c44e50067a 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -3332,6 +3332,7 @@ class TestSummaryPromptBounding:
resp.choices = [MagicMock()]
resp.choices[0].message = MagicMock()
resp.choices[0].message.content = "## Historical Task Snapshot\nDone."
+ telemetry = compressor._begin_compression_telemetry(current_tokens=1_000_000)
with patch("agent.context_compressor.call_llm", return_value=resp) as mock_call:
assert compressor._generate_summary(messages) is not None
assert mock_call.call_count == 1
@@ -3348,6 +3349,14 @@ class TestSummaryPromptBounding:
# Newest record anchors the tail and both ends of the history are represented.
assert whole[-1].startswith("[USER]: record-1199 ")
assert whole[0].startswith("[USER]: record-0000 ")
+ # Coverage telemetry describes exactly what the prompt shows, in records and record chars.
+ assert telemetry["summary_input_record_count"] == 1200
+ assert telemetry["summary_input_sampled_record_count"] == len(whole)
+ assert telemetry["summary_input_elided_record_count"] == 1200 - len(whole)
+ assert telemetry["summary_input_sampled_chars"] == sum(map(len, whole))
+ assert telemetry["summary_input_chars"] == (
+ telemetry["summary_input_sampled_chars"] + telemetry["summary_input_omitted_chars"]
+ )
def test_lean_sampling_oversized_middle_record_does_not_evict_tail(self):
"""A record larger than one region's share is bounded inside itself, not allowed to consume
@@ -3357,7 +3366,7 @@ class TestSummaryPromptBounding:
records.append("[TOOL RESULT oversized-mid]: " + ("y" * (cap // 2)))
records.extend(f"[USER]: record-{i:04d} " + ("x" * 1200) for i in range(401, 800))
records.append("[USER]: newest-tail-record")
- sampled = ContextCompressor._sample_summary_records(records)
+ sampled, _coverage = ContextCompressor._sample_summary_records(records)
assert len(sampled) <= cap
assert sampled.rstrip().endswith("[USER]: newest-tail-record")
assert "[TOOL RESULT oversized-mid]: yyyy" in sampled
diff --git a/tests/agent/test_lean_single_aux_call.py b/tests/agent/test_lean_single_aux_call.py
index fd6ebb9c3a3..17a5bee1c1e 100644
--- a/tests/agent/test_lean_single_aux_call.py
+++ b/tests/agent/test_lean_single_aux_call.py
@@ -146,14 +146,14 @@ class TestLeanSingleAuxiliaryCall:
class TestSampledSummaryInput:
def test_small_input_passes_through(self):
records = ["[USER]: abc" * 100] * 3
- assert ContextCompressor._sample_summary_records(records) == "\n\n".join(records)
+ assert ContextCompressor._sample_summary_records(records)[0] == "\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.
records = [f"<seg{i:02d}>" + ("x" * 50_000) for i in range(10)]
content = "\n\n".join(records)
- out = ContextCompressor._sample_summary_records(records)
+ out, _coverage = ContextCompressor._sample_summary_records(records)
assert len(out) <= ContextCompressor._SUMMARY_INPUT_MAX_CHARS
assert "chars elided" in out
seen = [i for i in range(10) if f"<seg{i:02d}>" in out]