Skip to content

The agent that grows with you

refactor(compression): move attempt telemetry helpers and the Codex route into siblings

mnajafian-nv104e5186aa7e
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index dce3fc77889..d122165d8ec 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -10,7 +10,6 @@ import logging
import sqlite3
import re
import time
-import uuid
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
@@ -34,6 +33,7 @@ from agent.auxiliary_client import (
from agent.context_engine import ContextEngine, sanitize_memory_context
from agent.context_compressor_prellm import PreLlmSkipMixin
from agent.context_compressor_summary import SummaryDispatchMixin
+from agent.context_compressor_telemetry import CompressionTelemetryMixin, _safe_int
from agent.error_classifier import FailoverReason, classify_api_error
from agent.micro_compaction import MicroCompactionMixin
from agent.prompt_builder import STEER_DISPLAY_KIND
@@ -48,14 +48,6 @@ from tools.todo_tool import TODO_INJECTION_HEADER
logger = logging.getLogger(__name__)
-def _safe_int(value: Any) -> int | None:
- """Best-effort integer coercion for telemetry fields."""
- try:
- return int(value)
- except (TypeError, ValueError):
- return None
-
-
# Summary-route pin lives in a ContextVar (not on the shared compressor) so the retry after a stalled
# summary sees it while the detached stalled worker does not. A stall raises nothing, so the aux client's
# exception-path fallback never fires; the host pins a fallback route for exactly ONE retry (the sole aux
@@ -2174,7 +2166,9 @@ Describe agent/tool work only as completed actions, state, or historical work.]"
}
-class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMixin, ContextEngine):
+class ContextCompressor(
+ SummaryDispatchMixin, PreLlmSkipMixin, CompressionTelemetryMixin, MicroCompactionMixin, ContextEngine,
+):
"""Default context engine: prune tool results, protect head/tail, summarize the middle
with an LLM, and iteratively update the previous summary on later compactions."""
@@ -2196,75 +2190,6 @@ class ContextCompressor(SummaryDispatchMixin, PreLlmSkipMixin, MicroCompactionMi
self._micro_compact_consecutive_failures = 0
self._micro_compact_last_failure_cursor = -1
- def _begin_compression_telemetry(
- self, *, current_tokens: int | None, attempt_id: str | None = None, session_id: str | None = None,
- trigger_source: str | None = None,
- ) -> dict[str, Any]:
- """Initialize content-free per-attempt compression telemetry."""
- seed = getattr(self, "_compression_telemetry_seed", None)
- seed = seed if isinstance(seed, dict) else {}
- attempt_id = attempt_id or seed.get("attempt_id")
- session_id = session_id or seed.get("session_id")
- trigger_source = trigger_source or seed.get("trigger_source")
- telemetry: dict[str, Any] = {
- "event": "compression_attempt", "attempt_id": attempt_id or uuid.uuid4().hex,
- "session_id": session_id or "", "trigger_source": trigger_source or "unknown",
- "main_provider": self.provider or "", "main_model": self.model or "",
- "main_context_limit": _safe_int(self.context_length),
- "current_estimated_tokens": _safe_int(current_tokens),
- "effective_threshold": _safe_int(self.threshold_tokens), "protected_head_tokens": None,
- "protected_tail_tokens": None, "middle_window_tokens": None, "prellm_skip_count": 0,
- "aux_prompt_tokens": None, "aux_output_reservation": None, "aux_provider": "", "aux_model": "",
- "effective_aux_context": None, "fit_margin": None, "chunking": False, "chunk_count": 0,
- "total_duration_ms": None, "aux_call_duration_ms": None, "queue_wait_ms": None, "prompt_build_ms": None,
- "time_to_first_progress_ms": None, "summary_generation_ms": None, "commit_ms": None,
- "fallback_used": False, "commit_status": "unknown", "split_status": "unknown", "failure_class": None,
- # Lean-sampling coverage (filled by _record_summary_input_coverage; None on the legacy path).
- "summary_input_chars": None, "summary_input_sampled_chars": None, "summary_input_omitted_chars": None,
- "summary_input_record_count": None, "summary_input_sampled_record_count": None,
- "summary_input_elided_record_count": None,
- }
- self._active_compression_telemetry = self._last_compression_telemetry = telemetry
- return telemetry
-
- def _record_compression_regions(
- self, *, head_messages: list[dict[str, Any]], middle_messages: list[dict[str, Any]],
- tail_messages: list[dict[str, Any]],
- ) -> None:
- telemetry = getattr(self, "_active_compression_telemetry", None)
- if isinstance(telemetry, dict):
- telemetry["protected_head_tokens"] = estimate_messages_tokens_rough(head_messages)
- telemetry["middle_window_tokens"] = estimate_messages_tokens_rough(middle_messages)
- telemetry["protected_tail_tokens"] = estimate_messages_tokens_rough(tail_messages)
-
- def _record_aux_compression_call(
- self, *, prompt_messages: list[dict[str, Any]], max_tokens: int | None, duration_ms: int,
- aux_provider: str | None = None, aux_model: str | None = None,
- effective_aux_context: int | None = None, phase_timings: dict[str, Any] | None = None,
- ) -> None:
- telemetry = getattr(self, "_active_compression_telemetry", None)
- if not isinstance(telemetry, dict):
- return
- telemetry["aux_prompt_tokens"] = estimate_messages_tokens_rough(prompt_messages)
- telemetry["aux_output_reservation"] = _safe_int(max_tokens)
- if aux_provider:
- telemetry["aux_provider"] = aux_provider
- if aux_model:
- telemetry["aux_model"] = aux_model
- if effective_aux_context is not None:
- telemetry["effective_aux_context"] = _safe_int(effective_aux_context)
- if telemetry["effective_aux_context"] is not None and telemetry["aux_prompt_tokens"] is not None:
- telemetry["fit_margin"] = (telemetry["effective_aux_context"] - telemetry["aux_prompt_tokens"]
- - (telemetry["aux_output_reservation"] or 0))
- telemetry["aux_call_duration_ms"] = (telemetry.get("aux_call_duration_ms") or 0) + max(0, int(duration_ms))
- for key in ("queue_wait_ms", "prompt_build_ms", "time_to_first_progress_ms", "summary_generation_ms", "commit_ms"):
- if not isinstance(phase_timings, dict) or key not in phase_timings:
- continue
- value = _safe_int(phase_timings[key])
- # Wait and generation phases accumulate across retries; the rest are point readings.
- accumulate = key in {"queue_wait_ms", "summary_generation_ms"} and value is not None
- telemetry[key] = (telemetry.get(key) or 0) + value if accumulate else value
-
def _emit_init_summary_once(self) -> None:
"""Emit the init log line once, on first context-length resolution (keeps __init__ non-blocking)."""
if not getattr(self, "_log_init_summary", False):
diff --git a/agent/context_compressor_telemetry.py b/agent/context_compressor_telemetry.py
new file mode 100644
index 00000000000..52f4d84dae4
--- /dev/null
+++ b/agent/context_compressor_telemetry.py
@@ -0,0 +1,94 @@
+"""Content-free per-attempt compression telemetry for ContextCompressor.
+
+Split from ``agent/context_compressor.py`` (file size cap), which imports it at module level; this module
+must never import that module at module level (import cycle).
+"""
+
+from __future__ import annotations
+
+import uuid
+from typing import Any
+
+from agent.model_metadata import estimate_messages_tokens_rough
+
+
+def _safe_int(value: Any) -> int | None:
+ """Best-effort integer coercion for telemetry fields."""
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
+class CompressionTelemetryMixin:
+ """Per-attempt telemetry dict: seeded at attempt start, filled by each compression phase."""
+
+ def _begin_compression_telemetry(
+ self, *, current_tokens: int | None, attempt_id: str | None = None, session_id: str | None = None,
+ trigger_source: str | None = None,
+ ) -> dict[str, Any]:
+ """Initialize content-free per-attempt compression telemetry."""
+ seed = getattr(self, "_compression_telemetry_seed", None)
+ seed = seed if isinstance(seed, dict) else {}
+ attempt_id = attempt_id or seed.get("attempt_id")
+ session_id = session_id or seed.get("session_id")
+ trigger_source = trigger_source or seed.get("trigger_source")
+ telemetry: dict[str, Any] = {
+ "event": "compression_attempt", "attempt_id": attempt_id or uuid.uuid4().hex,
+ "session_id": session_id or "", "trigger_source": trigger_source or "unknown",
+ "main_provider": self.provider or "", "main_model": self.model or "",
+ "main_context_limit": _safe_int(self.context_length),
+ "current_estimated_tokens": _safe_int(current_tokens),
+ "effective_threshold": _safe_int(self.threshold_tokens), "protected_head_tokens": None,
+ "protected_tail_tokens": None, "middle_window_tokens": None, "prellm_skip_count": 0,
+ "aux_prompt_tokens": None, "aux_output_reservation": None, "aux_provider": "", "aux_model": "",
+ "effective_aux_context": None, "fit_margin": None, "chunking": False, "chunk_count": 0,
+ "total_duration_ms": None, "aux_call_duration_ms": None, "queue_wait_ms": None, "prompt_build_ms": None,
+ "time_to_first_progress_ms": None, "summary_generation_ms": None, "commit_ms": None,
+ "fallback_used": False, "commit_status": "unknown", "split_status": "unknown", "failure_class": None,
+ # Lean-sampling coverage (filled by _record_summary_input_coverage; None on the legacy path).
+ "summary_input_chars": None, "summary_input_sampled_chars": None, "summary_input_omitted_chars": None,
+ "summary_input_record_count": None, "summary_input_sampled_record_count": None,
+ "summary_input_elided_record_count": None,
+ }
+ self._active_compression_telemetry = self._last_compression_telemetry = telemetry
+ return telemetry
+
+ def _record_compression_regions(
+ self, *, head_messages: list[dict[str, Any]], middle_messages: list[dict[str, Any]],
+ tail_messages: list[dict[str, Any]],
+ ) -> None:
+ telemetry = getattr(self, "_active_compression_telemetry", None)
+ if isinstance(telemetry, dict):
+ telemetry["protected_head_tokens"] = estimate_messages_tokens_rough(head_messages)
+ telemetry["middle_window_tokens"] = estimate_messages_tokens_rough(middle_messages)
+ telemetry["protected_tail_tokens"] = estimate_messages_tokens_rough(tail_messages)
+
+ def _record_aux_compression_call(
+ self, *, prompt_messages: list[dict[str, Any]], max_tokens: int | None, duration_ms: int,
+ aux_provider: str | None = None, aux_model: str | None = None,
+ effective_aux_context: int | None = None, phase_timings: dict[str, Any] | None = None,
+ ) -> None:
+ telemetry = getattr(self, "_active_compression_telemetry", None)
+ if not isinstance(telemetry, dict):
+ return
+ telemetry["aux_prompt_tokens"] = estimate_messages_tokens_rough(prompt_messages)
+ telemetry["aux_output_reservation"] = _safe_int(max_tokens)
+ if aux_provider:
+ telemetry["aux_provider"] = aux_provider
+ if aux_model:
+ telemetry["aux_model"] = aux_model
+ if effective_aux_context is not None:
+ telemetry["effective_aux_context"] = _safe_int(effective_aux_context)
+ if telemetry["effective_aux_context"] is not None and telemetry["aux_prompt_tokens"] is not None:
+ telemetry["fit_margin"] = (telemetry["effective_aux_context"] - telemetry["aux_prompt_tokens"]
+ - (telemetry["aux_output_reservation"] or 0))
+ telemetry["aux_call_duration_ms"] = (telemetry.get("aux_call_duration_ms") or 0) + max(0, int(duration_ms))
+ for key in ("queue_wait_ms", "prompt_build_ms", "time_to_first_progress_ms", "summary_generation_ms", "commit_ms"):
+ if not isinstance(phase_timings, dict) or key not in phase_timings:
+ continue
+ value = _safe_int(phase_timings[key])
+ # Wait and generation phases accumulate across retries; the rest are point readings.
+ accumulate = key in {"queue_wait_ms", "summary_generation_ms"} and value is not None
+ telemetry[key] = (telemetry.get(key) or 0) + value if accumulate else value
+
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 2631d76cd5a..640e6cc727f 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -30,7 +30,7 @@ from typing import Any, Callable, Dict, List, Literal, Optional, Tuple
from agent.auxiliary_client import AuxiliaryExplicitCancellation
from agent.context_engine import automatic_compaction_status_message, sanitize_memory_context
-from agent.conversation_compression_codex import _codex_compaction_cooldown_remaining
+from agent.conversation_compression_codex import _compress_context_via_codex_app_server
from agent.conversation_compression_telemetry import _emit_aborted_attempt_telemetry, _emit_compression_attempt_telemetry
from agent.memory_provider import PRE_COMPRESS_CHECKPOINT_API_VERSION
from agent.model_metadata import estimate_messages_tokens_rough, estimate_request_tokens_rough
@@ -4324,90 +4324,6 @@ def compress_context(
commit_fence.finish_commit()
-def _record_codex_compaction_failure(agent: Any, error: str) -> None:
- """Arm the shared compression-failure cooldown after a failed codex compaction.
- The codex path returns the transcript unchanged, so without a cooldown the still-over-threshold session
- would retry every turn."""
- from agent.context_compressor import _SUMMARY_FAILURE_COOLDOWN_SECONDS
- compressor = getattr(agent, "context_compressor", None)
- recorder = getattr(compressor, "_record_compression_failure_cooldown", None)
- if not callable(recorder):
- return
- with _swallow('codex compaction cooldown persist failed', exc_info=True):
- recorder(_SUMMARY_FAILURE_COOLDOWN_SECONDS, error)
-
-
-def _compress_context_via_codex_app_server(
- agent: Any, messages: list, system_message: Optional[str], *, approx_tokens: Optional[int] = None,
- task_id: str = "default", force: bool = False,
-) -> tuple[list, str]:
- """Route compaction to Codex app-server for Codex-owned threads.
- Rewriting the local transcript would not shrink the Codex thread, so Codex compacts its own thread and
- Hermes' transcript is left unchanged."""
- _sid = getattr(agent, "session_id", None) or "none"
- _tokens = f"{approx_tokens:,}" if approx_tokens else "unknown"
- auto_mode = str(getattr(agent, "codex_app_server_auto_compaction", "native") or "native").lower()
- if auto_mode not in {"native", "hermes", "off"}:
- auto_mode = "native"
- skip_reason = None
- if not force and auto_mode != "hermes":
- skip_reason = f"mode={auto_mode} force=false"
- elif not force:
- # Automatic entrypoints honor the compressor-owned cooldown: a recent compaction
- # failed, and retrying every turn is what thrashes.
- _cooldown_remaining = _codex_compaction_cooldown_remaining(agent)
- if _cooldown_remaining > 0:
- skip_reason = f"failure cooldown active for {_cooldown_remaining:.0f}s"
- codex_session = getattr(agent, "_codex_session", None)
- if skip_reason is None and codex_session is None:
- skip_reason = "no active codex thread"
- if skip_reason is not None:
- logger.info(
- "codex app-server compaction skipped: %s (session=%s messages=%d tokens=~%s)", skip_reason, _sid,
- len(messages), _tokens,
- )
- return messages, _existing_system_prompt(agent, system_message)
- logger.info("codex app-server compaction started: session=%s messages=%d tokens=~%s", _sid, len(messages), _tokens)
- with contextlib.suppress(Exception):
- agent._emit_status(COMPACTION_STATUS)
- _activity_heartbeat = _CompressionActivityHeartbeat(agent, emit_client_status=True).start()
- try:
- result = codex_session.compact_thread()
- except BaseException:
- _activity_heartbeat.stop("context compression failed")
- raise
- failed = bool(getattr(result, "interrupted", False) or getattr(result, "error", None))
- _activity_heartbeat.stop("context compression failed" if failed else "context compression completed")
- if getattr(result, "should_retire", False):
- with contextlib.suppress(Exception):
- codex_session.close()
- agent._codex_session = None
- if failed:
- with contextlib.suppress(Exception):
- agent._emit_warning(f"⚠ Codex app-server compaction failed: {result.error}")
- # The transcript is returned unchanged, so the session is still over
- # threshold. Without a brake the next turn retries immediately.
- _record_codex_compaction_failure(agent, str(getattr(result, "error", None) or "compaction interrupted"))
- return messages, _existing_system_prompt(agent, system_message)
- with _swallow('codex compaction bookkeeping failed', exc_info=True):
- from agent.codex_runtime import _record_codex_app_server_compaction, _record_codex_app_server_usage
- _record_codex_app_server_compaction(agent, result, approx_tokens=approx_tokens, force=True)
- # An empty usage report must consume the pending verdict, not leave deferral
- # armed until a later turn; minimal test engines may lack update_from_response.
- if hasattr(agent.context_compressor, "update_from_response"):
- _record_codex_app_server_usage(agent, result, messages=messages)
- _reset_read_dedup_caches(task_id, session_id=agent.session_id or "")
- logger.info(
- "codex app-server compaction done: session=%s thread=%s turn=%s", _sid,
- getattr(result, "thread_id", None) or "", getattr(result, "turn_id", None) or "",
- )
- existing_prompt = _existing_system_prompt(agent, system_message)
- # Terminal edge only on success — failure/interrupt paths above return
- # without it, matching the main compress_context() gating.
- _emit_compaction_done(agent)
- return messages, existing_prompt
-
-
# 4 MB leaves headroom under Anthropic's 5 MB; shrinking loses quality but only
# runs after a confirmed provider rejection, so the alternative is failure.
_IMAGE_SHRINK_TARGET_BYTES = 4 * 1024 * 1024
diff --git a/agent/conversation_compression_codex.py b/agent/conversation_compression_codex.py
index b1700cfae93..75091028358 100644
--- a/agent/conversation_compression_codex.py
+++ b/agent/conversation_compression_codex.py
@@ -1,14 +1,16 @@
-"""Codex app-server compaction cooldown lookup.
+"""Codex app-server compaction: the route ``compress_context`` takes for Codex-owned threads.
Split from ``agent/conversation_compression.py`` (facade size cap), which imports it at module level;
-this module must never import the facade (import cycle). It logs under the facade's logger name so log
-consumers keep one source.
+this module must never import the facade at module level (import cycle), so it late-imports the
+facade's shared helpers inside functions. It logs under the facade's logger name so log consumers keep
+one source.
"""
from __future__ import annotations
+import contextlib
import logging
-from typing import Any
+from typing import Any, Optional
logger = logging.getLogger("agent.conversation_compression")
@@ -28,3 +30,92 @@ def _codex_compaction_cooldown_remaining(agent: Any) -> float:
return max(0.0, float(state.get("remaining_seconds") or 0.0)) if state else 0.0
except (TypeError, ValueError):
return 0.0
+
+
+def _record_codex_compaction_failure(agent: Any, error: str) -> None:
+ """Arm the shared compression-failure cooldown after a failed codex compaction.
+ The codex path returns the transcript unchanged, so without a cooldown the still-over-threshold session
+ would retry every turn."""
+ from agent.context_compressor import _SUMMARY_FAILURE_COOLDOWN_SECONDS
+ from agent.conversation_compression import _swallow
+ compressor = getattr(agent, "context_compressor", None)
+ recorder = getattr(compressor, "_record_compression_failure_cooldown", None)
+ if not callable(recorder):
+ return
+ with _swallow('codex compaction cooldown persist failed', exc_info=True):
+ recorder(_SUMMARY_FAILURE_COOLDOWN_SECONDS, error)
+
+
+def _compress_context_via_codex_app_server(
+ agent: Any, messages: list, system_message: Optional[str], *, approx_tokens: Optional[int] = None,
+ task_id: str = "default", force: bool = False,
+) -> tuple[list, str]:
+ """Route compaction to Codex app-server for Codex-owned threads.
+ Rewriting the local transcript would not shrink the Codex thread, so Codex compacts its own thread and
+ Hermes' transcript is left unchanged."""
+ from agent.conversation_compression import (
+ COMPACTION_STATUS, _CompressionActivityHeartbeat, _emit_compaction_done, _existing_system_prompt,
+ _reset_read_dedup_caches, _swallow,
+ )
+ _sid = getattr(agent, "session_id", None) or "none"
+ _tokens = f"{approx_tokens:,}" if approx_tokens else "unknown"
+ auto_mode = str(getattr(agent, "codex_app_server_auto_compaction", "native") or "native").lower()
+ if auto_mode not in {"native", "hermes", "off"}:
+ auto_mode = "native"
+ skip_reason = None
+ if not force and auto_mode != "hermes":
+ skip_reason = f"mode={auto_mode} force=false"
+ elif not force:
+ # Automatic entrypoints honor the compressor-owned cooldown: a recent compaction
+ # failed, and retrying every turn is what thrashes.
+ _cooldown_remaining = _codex_compaction_cooldown_remaining(agent)
+ if _cooldown_remaining > 0:
+ skip_reason = f"failure cooldown active for {_cooldown_remaining:.0f}s"
+ codex_session = getattr(agent, "_codex_session", None)
+ if skip_reason is None and codex_session is None:
+ skip_reason = "no active codex thread"
+ if skip_reason is not None:
+ logger.info(
+ "codex app-server compaction skipped: %s (session=%s messages=%d tokens=~%s)", skip_reason, _sid,
+ len(messages), _tokens,
+ )
+ return messages, _existing_system_prompt(agent, system_message)
+ logger.info("codex app-server compaction started: session=%s messages=%d tokens=~%s", _sid, len(messages), _tokens)
+ with contextlib.suppress(Exception):
+ agent._emit_status(COMPACTION_STATUS)
+ _activity_heartbeat = _CompressionActivityHeartbeat(agent, emit_client_status=True).start()
+ try:
+ result = codex_session.compact_thread()
+ except BaseException:
+ _activity_heartbeat.stop("context compression failed")
+ raise
+ failed = bool(getattr(result, "interrupted", False) or getattr(result, "error", None))
+ _activity_heartbeat.stop("context compression failed" if failed else "context compression completed")
+ if getattr(result, "should_retire", False):
+ with contextlib.suppress(Exception):
+ codex_session.close()
+ agent._codex_session = None
+ if failed:
+ with contextlib.suppress(Exception):
+ agent._emit_warning(f"⚠ Codex app-server compaction failed: {result.error}")
+ # The transcript is returned unchanged, so the session is still over
+ # threshold. Without a brake the next turn retries immediately.
+ _record_codex_compaction_failure(agent, str(getattr(result, "error", None) or "compaction interrupted"))
+ return messages, _existing_system_prompt(agent, system_message)
+ with _swallow('codex compaction bookkeeping failed', exc_info=True):
+ from agent.codex_runtime import _record_codex_app_server_compaction, _record_codex_app_server_usage
+ _record_codex_app_server_compaction(agent, result, approx_tokens=approx_tokens, force=True)
+ # An empty usage report must consume the pending verdict, not leave deferral
+ # armed until a later turn; minimal test engines may lack update_from_response.
+ if hasattr(agent.context_compressor, "update_from_response"):
+ _record_codex_app_server_usage(agent, result, messages=messages)
+ _reset_read_dedup_caches(task_id, session_id=agent.session_id or "")
+ logger.info(
+ "codex app-server compaction done: session=%s thread=%s turn=%s", _sid,
+ getattr(result, "thread_id", None) or "", getattr(result, "turn_id", None) or "",
+ )
+ existing_prompt = _existing_system_prompt(agent, system_message)
+ # Terminal edge only on success — failure/interrupt paths above return
+ # without it, matching the main compress_context() gating.
+ _emit_compaction_done(agent)
+ return messages, existing_prompt