From bf9b193d7cbe97a3fa299f559e6d9b052bfb25be Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:54:24 -0800 Subject: [PATCH] refactor(caching): one owner per helper, no cross-module private imports - Keep-alive totals go through turn_usage.add_session_usage, the same fold a response uses (it now also counts reasoning tokens, as a response does). - PromptCacheWarmer._with_aux_hooks is auxiliary_hooks.run_with_aux_hooks with a lazy normalized= view; _rough_tokens is conversation_compression_manual.estimate_request_tokens. - prompt_cache_is_cold lives in prompt_cache_clock (its only inputs), ending the turn_proactive_prune -> turn_preflight -> turn_proactive_prune circle; the read-dedup reset after a committed prune happens once, in _proactive_tool_result_prune, not at three call sites. - Public names for the helpers other modules import: turn_usage.cache_clock_column / agent_session_source, context_compressor_summary.accepts_keyword_argument. - archive_pruned_originals / archive_compaction_drops lose the never-passed skip= parameter. Co-authored-by: kshitijk4poor <82637225+kshitijk4poor@users.noreply.github.com> --- agent/auxiliary_hooks.py | 9 +++- agent/codex_runtime.py | 4 +- agent/context_compressor_summary.py | 4 +- agent/conversation_compression.py | 6 +-- agent/prompt_cache_clock.py | 21 +++++++++ agent/prompt_cache_lifecycle.py | 47 +++++++------------ agent/turn_preflight.py | 25 +++++----- agent/turn_proactive_prune.py | 43 +++-------------- agent/turn_usage.py | 34 +++++++++----- .../test_proactive_prune_plugin_engine.py | 2 +- .../test_proactive_prune_round_guards.py | 2 +- .../test_prompt_cache_budget_and_caps.py | 2 +- .../test_prompt_cache_clock_retention.py | 2 +- tests/agent/test_prompt_cache_lifecycle.py | 4 +- tests/agent/test_prompt_cache_openai_spec.py | 4 +- tests/agent/test_prompt_cache_rulings.py | 2 +- tests/agent/test_prompt_cache_warmer.py | 2 +- tools/tool_result_storage.py | 15 +++--- 18 files changed, 109 insertions(+), 119 deletions(-) diff --git a/agent/auxiliary_hooks.py b/agent/auxiliary_hooks.py index d16eb792f7..c972ee198f 100644 --- a/agent/auxiliary_hooks.py +++ b/agent/auxiliary_hooks.py @@ -236,9 +236,11 @@ def finish_aux_call_hooks( def run_with_aux_hooks( call: Callable[[], Any], *, aux_task: str, metadata: dict[str, Any], client: Any, kwargs: dict[str, Any], provider: str, model: str, api_mode: str, streaming: bool = False, + normalized: Optional[Callable[[Any], Any]] = None, ) -> Any: """Run one synchronous provider attempt between ``pre_auxiliary_call`` and - ``post_auxiliary_call``; the exception (if any) is reported in ``post`` and re-raised.""" + ``post_auxiliary_call``; the exception (if any) is reported in ``post`` and re-raised. + ``normalized(response)``, when given, builds the hooks' normalized view only when a hook listens.""" hooks = start_aux_call_hooks(aux_task=aux_task, metadata=metadata, client=client, kwargs=kwargs, provider=provider, model=model, api_mode=api_mode, streaming=streaming) try: @@ -246,7 +248,10 @@ def run_with_aux_hooks( except BaseException as exc: finish_aux_call_hooks(hooks, error=exc) raise - finish_aux_call_hooks(hooks, response=response) + if hooks is not None and normalized is not None: + finish_aux_call_hooks(hooks, response, normalized=normalized(response)) + else: + finish_aux_call_hooks(hooks, response=response) return response diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py index 60d0a95237..0b2cd772a4 100644 --- a/agent/codex_runtime.py +++ b/agent/codex_runtime.py @@ -216,8 +216,8 @@ def _record_codex_app_server_usage(agent, turn, messages=None) -> dict[str, Any] # The app-server builds its own requests (cache options included), so Hermes cannot know the # window: an explicit unknown keeps an older window from outliving this cache activity. from agent.prompt_cache_clock import record_unobserved_cache_response - from agent.turn_usage import _cache_clock_column - clock = _cache_clock_column(record_unobserved_cache_response(agent, canonical_usage, reason="codex_app_server")) + from agent.turn_usage import cache_clock_column + clock = cache_clock_column(record_unobserved_cache_response(agent, canonical_usage, reason="codex_app_server")) _queue_token_counts( agent, "Codex app-server token persistence failed (session=%s, tokens=%d): %s", total_tokens, counts=lambda: billing(**token_counts, **cost_fields, **clock, diff --git a/agent/context_compressor_summary.py b/agent/context_compressor_summary.py index 98cd03ce73..2b0df6d701 100644 --- a/agent/context_compressor_summary.py +++ b/agent/context_compressor_summary.py @@ -11,7 +11,7 @@ if TYPE_CHECKING: from agent.context_compressor import _HandoffScan -def _accepts_keyword_argument(callable_obj: Any, name: str) -> bool: +def accepts_keyword_argument(callable_obj: Any, name: str) -> bool: """Return whether an inspectable callable accepts ``name`` as a keyword.""" try: parameters = inspect.signature(callable_obj).parameters @@ -89,7 +89,7 @@ class SummaryDispatchMixin: "focus_topic": focus_topic or self._derive_auto_focus_topic(messages), "memory_context": memory_context, } - if _accepts_keyword_argument(self._generate_summary, "bypass_cooldown"): + if accepts_keyword_argument(self._generate_summary, "bypass_cooldown"): summary_kwargs["bypass_cooldown"] = bypass_cooldown try: return self._generate_summary(turns_to_summarize, **summary_kwargs) diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py index b517d233bb..afc24244a6 100644 --- a/agent/conversation_compression.py +++ b/agent/conversation_compression.py @@ -28,7 +28,7 @@ from pathlib import Path from typing import Any, Callable, Dict, List, Literal, Optional, Tuple from agent.auxiliary_client import AuxiliaryExplicitCancellation -from agent.context_compressor_summary import _accepts_keyword_argument +from agent.context_compressor_summary import accepts_keyword_argument from agent.context_engine import CompactionProgressText, automatic_compaction_status_message, sanitize_memory_context from agent.conversation_compression_codex import _compress_context_via_codex_app_server from agent.conversation_compression_deadline import resolve_context_compression_timeouts @@ -1420,14 +1420,14 @@ def _automatic_compression_gate_blocks( blocked = getattr(type(compressor), "_automatic_compression_blocked", None) if not callable(blocked): return None - ignore = bypass_cooldown and _accepts_keyword_argument(blocked, "ignore_cooldown") + ignore = bypass_cooldown and accepts_keyword_argument(blocked, "ignore_cooldown") if not (blocked(compressor, ignore_cooldown=True) if ignore else blocked(compressor)): return None reason, reason_fn = None, getattr(compressor, "_compression_block_reason", None) if callable(reason_fn): # engines predating it name no reason with _swallow('compression block-reason read failed', exc_info=True): reason = ( - reason_fn(ignore_cooldown=True) if ignore and _accepts_keyword_argument(reason_fn, "ignore_cooldown") + reason_fn(ignore_cooldown=True) if ignore and accepts_keyword_argument(reason_fn, "ignore_cooldown") else reason_fn() ) reason = reason if isinstance(reason, str) and reason else "unknown" diff --git a/agent/prompt_cache_clock.py b/agent/prompt_cache_clock.py index 0e03c0a9d1..c06e885034 100644 --- a/agent/prompt_cache_clock.py +++ b/agent/prompt_cache_clock.py @@ -743,3 +743,24 @@ def _cache_line(window: dict[str, Any], estimated: Any, now: Optional[float]) -> return t("gateway.context.cache_maybe_warm", until=_clock(estimated), remaining=_duration(float(estimated) - now), **facts) return t("gateway.context.cache_expired", ago=_duration(now - float(estimated)), **facts) + + +def prompt_cache_is_cold(agent: Any, *, now: float | None = None) -> bool: + """Whether the provider prompt cache has certainly expired, so a history rewrite breaks nothing. + + The prune's ONLY cold-cache reading (both call sites), from the shared cache clock: past the + window's estimated end only. An unknown window (no cache touched yet, an unreadable store, a + route switch, or a compaction or prune since the last response) or one that may still be warm + answers False. The clock restores a resumed session's window from the store itself. + + Only a proven or declared window prunes. An assumed one includes the window the clock rebuilds for a + pre-clock session from TODAY's TTL and route: a session cached for 1h (or on another route) then + reads cold while still warm. The /context line keeps showing that estimate. + + A route switch (``/model``, a fallback, any change of provider, endpoint or model since the last + response) is cold too: the new route has never seen this prefix, so the first request there writes + it whole and an offload before it breaks nothing.""" + window = cache_window(agent) + if window is not None and window.reason == "route_changed": + return True + return window is not None and window.confidence in (PROVEN, DECLARED) and cache_certainly_cold(window, now=now) diff --git a/agent/prompt_cache_lifecycle.py b/agent/prompt_cache_lifecycle.py index d4fedc53ed..0bd59740a8 100644 --- a/agent/prompt_cache_lifecycle.py +++ b/agent/prompt_cache_lifecycle.py @@ -785,22 +785,13 @@ class PromptCacheWarmer: """One keep-alive attempt between ``pre_auxiliary_call`` and ``post_auxiliary_call`` (``aux_task="cache_warm"``), so observers that meter auxiliary spend see every refresh. The observers read the request; the bytes sent are unchanged.""" - from agent.auxiliary_hooks import finish_aux_call_hooks, start_aux_call_hooks + from agent.auxiliary_hooks import run_with_aux_hooks - b = run.billing - hooks = start_aux_call_hooks( - aux_task="cache_warm", metadata={"api_request_id": f"cache-warm-{uuid.uuid4().hex}"}, client=client, - kwargs=kwargs, provider=str(b["provider"] or ""), model=str(run.model or ""), api_mode=run.api_mode, - streaming=False, + return run_with_aux_hooks( + call, aux_task="cache_warm", metadata={"api_request_id": f"cache-warm-{uuid.uuid4().hex}"}, + client=client, kwargs=kwargs, provider=str(run.billing["provider"] or ""), model=str(run.model or ""), + api_mode=run.api_mode, normalized=lambda message: self._hook_view(run, message), ) - try: - message = call() - except BaseException as exc: - finish_aux_call_hooks(hooks, error=exc) - raise - if hooks is not None: - finish_aux_call_hooks(hooks, message, normalized=self._hook_view(run, message)) - return message @staticmethod def _hook_view(run: _Run, message: Any) -> tuple[Any, Any, Optional[dict[str, Any]]]: @@ -896,7 +887,7 @@ class PromptCacheWarmer: event is stamped with the arm-time witness, so a rewrite committing even now leaves the clock unknown rather than vouching for the new prefix.""" from agent.prompt_cache_clock import attempt_facts, record_cache_response - from agent.turn_usage import _cache_clock_column + from agent.turn_usage import cache_clock_column agent, b = self.agent, run.billing with self._lock: @@ -906,20 +897,17 @@ class PromptCacheWarmer: event = record_cache_response(agent, canonical, model=b["model"], provider=b["provider"], base_url=b["base_url"], api_mode=b["api_mode"], attempt=attempt, witness=run.witness) - return _cache_clock_column(event) + return cache_clock_column(event) def _add_to_session_totals(self, canonical: Any, amount: Optional[float]) -> None: # Not session_api_calls: that counter is the conversation's request sequence (and the # warmer's own currency token); a replay is accounted, not a turn. + from agent.turn_usage import add_session_usage + agent = self.agent agent.session_cache_warm_calls = getattr(agent, "session_cache_warm_calls", 0) + 1 - agent.session_prompt_tokens += canonical.prompt_tokens - agent.session_completion_tokens += canonical.output_tokens - agent.session_total_tokens += canonical.total_tokens - agent.session_input_tokens += canonical.input_tokens - agent.session_output_tokens += canonical.output_tokens - agent.session_cache_read_tokens += canonical.cache_read_tokens - agent.session_cache_write_tokens += canonical.cache_write_tokens + add_session_usage(agent, canonical, prompt_tokens=canonical.prompt_tokens, + completion_tokens=canonical.output_tokens, total_tokens=canonical.total_tokens) if amount is not None: agent.session_estimated_cost_usd += amount @@ -988,10 +976,10 @@ class PromptCacheWarmer: def _billing_snapshot(self) -> dict[str, Any]: agent = self.agent - from agent.turn_usage import _agent_session_source + from agent.turn_usage import agent_session_source return { - "session_id": getattr(agent, "session_id", None), "source": _agent_session_source(agent), + "session_id": getattr(agent, "session_id", None), "source": agent_session_source(agent), "provider": agent.provider, "base_url": agent.base_url, "model": agent.model, "api_mode": agent.api_mode, "api_key": getattr(agent, "api_key", ""), "reset_epoch": getattr(agent, "_session_reset_epoch", 0), @@ -1042,11 +1030,10 @@ def _compressor_blocked(agent: Any) -> Optional[str]: def _rough_tokens(agent: Any, messages: Optional[list] = None) -> int: - from agent.model_metadata import estimate_request_tokens_rough + from agent.conversation_compression_manual import estimate_request_tokens - msgs = list(getattr(agent, "_session_messages", None) or ()) if messages is None else messages - return estimate_request_tokens_rough(msgs, system_prompt=getattr(agent, "_cached_system_prompt", "") or "", - tools=getattr(agent, "tools", None) or None) + return estimate_request_tokens(agent, list(getattr(agent, "_session_messages", None) or ()) + if messages is None else messages) def _compaction_baseline(agent: Any) -> int: @@ -1133,7 +1120,7 @@ def _offload_reason(agent: Any, warmer: PromptCacheWarmer, now: float) -> str: """Why step 3's offload does not run now (``"due"`` when it does): the chat is idle and its cache is over (past the clock's proven/declared end, or its route changed). Once per stretch; the cold prune applies its own gates (protected tail, >= 16k reclaim). Caller holds ``warmer._lock``.""" - from agent.turn_proactive_prune import prompt_cache_is_cold + from agent.prompt_cache_clock import prompt_cache_is_cold if warmer._offloaded: return "offloaded_this_stretch" diff --git a/agent/turn_preflight.py b/agent/turn_preflight.py index d7289f4db2..42fad05d0b 100644 --- a/agent/turn_preflight.py +++ b/agent/turn_preflight.py @@ -13,7 +13,7 @@ import logging from dataclasses import dataclass from typing import Any, Dict, List, Optional -from agent.context_compressor_summary import _accepts_keyword_argument +from agent.context_compressor_summary import accepts_keyword_argument from agent.context_engine import automatic_compaction_status_message from agent.conversation_compression import ( PRE_API_COMPRESSION_STATUS_TEMPLATE, _reset_read_dedup_caches, compression_blocked_transiently, @@ -372,19 +372,15 @@ def compress_after_tool_results( agent._warn_context_overflow_blocked( _block_reason, _real_tokens, int(getattr(_compressor, "threshold_tokens", 0) or 0) ) - _pruned_msgs = _proactive_tool_result_prune( - agent, _compressor, messages, _real_tokens, turn_start=current_turn_user_idx) - if _pruned_msgs is not messages: - messages = _pruned_msgs - # A committed prune is a content-loss boundary like compaction: demoted skill_view / - # read_file bodies survive only as one-line markers, so the repeat-read dedup must - # stop answering "unchanged" for them or the reload the marker asks for is refused. - _reset_read_dedup_caches(effective_task_id, session_id=agent.session_id or "") + messages = _proactive_tool_result_prune( + agent, _compressor, messages, _real_tokens, turn_start=current_turn_user_idx, + effective_task_id=effective_task_id) return _verdict(False) def _proactive_tool_result_prune( agent: Any, compressor: Any, messages: list, current_tokens: int, *, turn_start: int | None = None, + effective_task_id: Any = None, ) -> list: """Proactive tool-result prune (deterministic, no LLM, keeps tail): the pruned list when one committed, else the same ``messages`` object. No-op unless proactive_prune_tokens is exceeded; @@ -412,11 +408,11 @@ def _proactive_tool_result_prune( getattr(compressor, "_session_db", None) is not None and getattr(compressor, "_session_id", "")): return messages kwargs: dict[str, Any] = {"current_tokens": current_tokens} - if _accepts_keyword_argument(prune, "cold_cache"): # older plugin engines keep their signature - from agent.turn_proactive_prune import prompt_cache_is_cold + if accepts_keyword_argument(prune, "cold_cache"): # older plugin engines keep their signature + from agent.prompt_cache_clock import prompt_cache_is_cold kwargs["cold_cache"] = prompt_cache_is_cold(agent) - if isinstance(turn_start, int) and _accepts_keyword_argument(prune, "turn_start"): + if isinstance(turn_start, int) and accepts_keyword_argument(prune, "turn_start"): kwargs["turn_start"] = turn_start # the running turn is never shortened try: pruned_msgs, pruned_n = prune(messages, **kwargs) @@ -431,4 +427,9 @@ def _proactive_tool_result_prune( from agent.compaction_events import publish_prune publish_prune(agent, messages, pruned_msgs, pruned_n) + if effective_task_id is not None: + # A committed prune is a content-loss boundary like compaction: demoted skill_view / read_file + # bodies survive only as one-line markers, so the repeat-read dedup must stop answering + # "unchanged" for them or the reload the marker asks for is refused. + _reset_read_dedup_caches(effective_task_id, session_id=agent.session_id or "") return pruned_msgs diff --git a/agent/turn_proactive_prune.py b/agent/turn_proactive_prune.py index 3a510d3fc7..cca696f323 100644 --- a/agent/turn_proactive_prune.py +++ b/agent/turn_proactive_prune.py @@ -10,47 +10,20 @@ from dataclasses import dataclass from typing import Any from agent.context_compressor import _DB_PERSISTED_MARKER -from agent.conversation_compression import _reset_read_dedup_caches -from agent.prompt_cache_clock import DECLARED, PROVEN, cache_certainly_cold, cache_window +from agent.prompt_cache_clock import cache_window, prompt_cache_is_cold logger = logging.getLogger("agent.conversation_loop") -def prompt_cache_is_cold(agent: Any, *, now: float | None = None) -> bool: - """Whether the provider prompt cache has certainly expired, so a history rewrite breaks nothing. - - The prune's ONLY cold-cache reading (both call sites), from the shared cache clock: past the - window's estimated end only. An unknown window (no cache touched yet, an unreadable store, a - route switch, or a compaction or prune since the last response) or one that may still be warm - answers False. The clock restores a resumed session's window from the store itself. - - Only a proven or declared window prunes. An assumed one includes the window the clock rebuilds for a - pre-clock session from TODAY's TTL and route: a session cached for 1h (or on another route) then - reads cold while still warm. The /context line keeps showing that estimate. - - A route switch (``/model``, a fallback, any change of provider, endpoint or model since the last - response) is cold too: the new route has never seen this prefix, so the first request there writes - it whole and an offload before it breaks nothing.""" - window = cache_window(agent) - if window is not None and window.reason == "route_changed": - return True - return window is not None and window.confidence in (PROVEN, DECLARED) and cache_certainly_cold(window, now=now) - - def run_proactive_prune( agent: Any, messages: list[dict[str, Any]], current_tokens: int, effective_task_id: Any, ) -> list[dict[str, Any]]: """Run the post-tool prune helper once (same gates, suppression accounting and commit contract); - reset the read dedup on a commit. Returns the list the loop continues with.""" + the read dedup resets on a commit. Returns the list the loop continues with.""" from agent.turn_preflight import _proactive_tool_result_prune - pruned = _proactive_tool_result_prune(agent, agent.context_compressor, messages, current_tokens) - if pruned is not messages: - # A committed prune is a content-loss boundary like compaction: demoted skill_view / read_file bodies - # survive only as one-line markers, so the repeat-read dedup must stop answering "unchanged" for them - # or the reload the marker asks for is refused. - _reset_read_dedup_caches(effective_task_id, session_id=agent.session_id or "") - return pruned + return _proactive_tool_result_prune(agent, agent.context_compressor, messages, current_tokens, + effective_task_id=effective_task_id) def turn_start_cold_prune(agent: Any, out: Any, effective_task_id: Any) -> None: @@ -110,15 +83,13 @@ def route_change_offload( tokens = _tc._preflight_request_tokens(agent, messages, active_system_prompt or "") pruned = _proactive_tool_result_prune(agent, agent.context_compressor, messages, tokens, - turn_start=current_turn_user_idx) - if pruned is messages: - return RouteOffloadVerdict("fallthrough", messages) - _reset_read_dedup_caches(effective_task_id, session_id=agent.session_id or "") + turn_start=current_turn_user_idx, effective_task_id=effective_task_id) return RouteOffloadVerdict("fallthrough", pruned) def offload_cold_history(agent: Any, messages: list[dict[str, Any]], task_id: Any = None) -> list[dict[str, Any]]: - """Step 3's offload on an idle chat whose cache is over (``prompt_cache_lifecycle.claim_offload``): + """Step 3's offload on an idle chat whose cache is over (``PromptCacheWarmer.claim_edge`` answered + ``"offload"``): the same cold prune a return after expiry runs (byte-exact archive + pointer, protected tail, the 16k reclaim gate), run by the surface that owns the chat so it is already small when the person comes back. Returns the history to keep (the input object when nothing committed).""" diff --git a/agent/turn_usage.py b/agent/turn_usage.py index d33c79e73f..82c668aeaa 100644 --- a/agent/turn_usage.py +++ b/agent/turn_usage.py @@ -22,14 +22,28 @@ from agent.usage_pricing import estimate_usage_cost, normalize_usage, with_serve logger = logging.getLogger("agent.conversation_loop") -def _agent_session_source(agent: Any) -> str: +def add_session_usage(agent: Any, usage: Any, *, prompt_tokens: int, completion_tokens: int, + total_tokens: int) -> None: + """Fold one reply's tokens into the agent's running session totals (the caller holds + ``session_totals_lock``): a conversation response and a cache keep-alive alike.""" + agent.session_prompt_tokens += prompt_tokens + agent.session_completion_tokens += completion_tokens + agent.session_total_tokens += total_tokens + agent.session_input_tokens += usage.input_tokens + agent.session_output_tokens += usage.output_tokens + agent.session_cache_read_tokens += usage.cache_read_tokens + agent.session_cache_write_tokens += usage.cache_write_tokens + agent.session_reasoning_tokens += usage.reasoning_tokens + + +def agent_session_source(agent: Any) -> str: """The surface the agent's own row create would stamp (``_ensure_db_session``), so an accounting guard that wins the row-creation race never mints an anonymous session.""" from agent.session_source import session_source_for return session_source_for(getattr(agent, "platform", None)) -def _cache_clock_column(event: Any) -> dict[str, str]: +def cache_clock_column(event: Any) -> dict[str, str]: """``prompt_cache_clock`` kwarg for the token batch: only when this response moved the clock.""" if event is None: return {} @@ -42,14 +56,14 @@ def _queue_usage(agent: Any, **counts: Any) -> None: from agent.agent_init_session import agent_interface store = agent_interface(agent) if store is None: - agent._session_db.queue_token_counts(agent.session_id, source=_agent_session_source(agent), **counts) + agent._session_db.queue_token_counts(agent.session_id, source=agent_session_source(agent), **counts) return from persistence.conversation.usage import BillingRoute, TokenCounts, UsageDelta tokens = TokenCounts(**{key: counts.pop(key, 0) for key in ( "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens")}) route = {key: counts.pop(key, None) for key in ("model", "billing_provider", "billing_base_url", "billing_mode")} delta = UsageDelta(tokens=tokens, route=BillingRoute(**route) if route["model"] else None, - source=_agent_session_source(agent), **counts) + source=agent_session_source(agent), **counts) store.usage.queue_usage(agent.session_id, delta) @@ -233,14 +247,8 @@ def record_response_usage( from agent.prompt_cache_lifecycle import session_totals_lock with session_totals_lock(agent): # a keep-alive reply landing now adds to these too - agent.session_prompt_tokens += prompt_tokens - agent.session_completion_tokens += completion_tokens - agent.session_total_tokens += total_tokens - agent.session_input_tokens += canonical_usage.input_tokens - agent.session_output_tokens += canonical_usage.output_tokens - agent.session_cache_read_tokens += canonical_usage.cache_read_tokens - agent.session_cache_write_tokens += canonical_usage.cache_write_tokens - agent.session_reasoning_tokens += canonical_usage.reasoning_tokens + add_session_usage(agent, canonical_usage, prompt_tokens=prompt_tokens, + completion_tokens=completion_tokens, total_tokens=total_tokens) # Rolling history for status-bar averages (last 10). with suppress(Exception): hist = getattr(agent, "_api_latency_history", None) @@ -336,7 +344,7 @@ def record_response_usage( model=agent.model, api_call_count=1, task=getattr(agent, "_turn_route_task", "") or "", - **_cache_clock_column(_cache_event), + **cache_clock_column(_cache_event), ) except Exception as e: # silent loss here undercounts analytics logger.debug( diff --git a/tests/agent/test_proactive_prune_plugin_engine.py b/tests/agent/test_proactive_prune_plugin_engine.py index b626c15348..3c24c38bf8 100644 --- a/tests/agent/test_proactive_prune_plugin_engine.py +++ b/tests/agent/test_proactive_prune_plugin_engine.py @@ -49,7 +49,7 @@ def _drive_route(engine, route): turn_start = len(messages) messages.append({"role": "user", "content": "next question"}) original = deepcopy(messages) - with patch("agent.turn_proactive_prune.prompt_cache_is_cold", return_value=True): + with patch("agent.prompt_cache_clock.prompt_cache_is_cold", return_value=True): if route == "after_tool": out = compress_after_tool_results( agent, messages=messages, system_message="sys", user_message="next question", diff --git a/tests/agent/test_proactive_prune_round_guards.py b/tests/agent/test_proactive_prune_round_guards.py index d6b3b9997f..0425ebc546 100644 --- a/tests/agent/test_proactive_prune_round_guards.py +++ b/tests/agent/test_proactive_prune_round_guards.py @@ -123,7 +123,7 @@ def test_a_resumed_session_reads_the_stored_cache_clock(home): from types import SimpleNamespace from agent.prompt_cache_clock import CacheEvent, _route_key, event_to_json - from agent.turn_proactive_prune import prompt_cache_is_cold + from agent.prompt_cache_clock import prompt_cache_is_cold from hermes_state import SessionDB route = ("openrouter", "https://openrouter.ai/api/v1", "anthropic/claude-sonnet-4.6") diff --git a/tests/agent/test_prompt_cache_budget_and_caps.py b/tests/agent/test_prompt_cache_budget_and_caps.py index 3b6661b0a7..75c86532f7 100644 --- a/tests/agent/test_prompt_cache_budget_and_caps.py +++ b/tests/agent/test_prompt_cache_budget_and_caps.py @@ -82,7 +82,7 @@ def _chat(client=None, tokens=150_000, **over): _interrupt_requested=False, _anthropic_client=client or _Client(), model="claude-opus-4-7", provider="anthropic", base_url="https://api.anthropic.com", api_key="", session_api_calls=7, session_prompt_tokens=0, session_completion_tokens=0, session_total_tokens=0, session_input_tokens=0, - session_output_tokens=0, session_cache_read_tokens=0, session_cache_write_tokens=0, + session_output_tokens=0, session_cache_read_tokens=0, session_cache_write_tokens=0, session_reasoning_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", log_prefix="", platform="cli", compression_enabled=True, _user_turn_count=1, context_compressor=SimpleNamespace( diff --git a/tests/agent/test_prompt_cache_clock_retention.py b/tests/agent/test_prompt_cache_clock_retention.py index 82d3185a05..6b061a6ed7 100644 --- a/tests/agent/test_prompt_cache_clock_retention.py +++ b/tests/agent/test_prompt_cache_clock_retention.py @@ -11,7 +11,7 @@ import pytest from agent.prompt_cache_clock import cache_certainly_warm, cache_window, record_attempt_sent, record_cache_response from agent.transports.codex import _default_prompt_cache_retention_for_request -from agent.turn_proactive_prune import prompt_cache_is_cold +from agent.prompt_cache_clock import prompt_cache_is_cold from agent.usage_pricing import normalize_usage T0 = 1_000.0 diff --git a/tests/agent/test_prompt_cache_lifecycle.py b/tests/agent/test_prompt_cache_lifecycle.py index 1dc63da5f4..0b4a8e4879 100644 --- a/tests/agent/test_prompt_cache_lifecycle.py +++ b/tests/agent/test_prompt_cache_lifecycle.py @@ -71,7 +71,7 @@ def _chat(*, platform="cli", client=None, tokens=150_000, provider="anthropic", _interrupt_requested=False, _anthropic_client=client or _Client(), model="claude-opus-4-7", provider=provider, base_url=base_url, api_key="", session_api_calls=7, session_prompt_tokens=0, session_completion_tokens=0, session_total_tokens=0, session_input_tokens=0, session_output_tokens=0, - session_cache_read_tokens=0, session_cache_write_tokens=0, session_estimated_cost_usd=0.0, + session_cache_read_tokens=0, session_cache_write_tokens=0, session_reasoning_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", log_prefix="", platform=platform, compression_enabled=True, context_compressor=SimpleNamespace( compression_count=0, last_prompt_tokens=tokens, threshold_tokens=200_000, summary_target_ratio=0.2, @@ -245,7 +245,7 @@ def test_a_machine_session_warms_only_while_its_tool_runs(over): def test_an_unknown_clock_makes_nothing_act(): - from agent.turn_proactive_prune import prompt_cache_is_cold + from agent.prompt_cache_clock import prompt_cache_is_cold agent = _chat() warmer = pcl.get_prompt_cache_warmer(agent) diff --git a/tests/agent/test_prompt_cache_openai_spec.py b/tests/agent/test_prompt_cache_openai_spec.py index 31175661d3..c1f5922907 100644 --- a/tests/agent/test_prompt_cache_openai_spec.py +++ b/tests/agent/test_prompt_cache_openai_spec.py @@ -59,7 +59,7 @@ def _agent(model): client=client, model=model, provider="nous", base_url="https://inference-api.nousresearch.com/v1", api_key="", session_api_calls=3, session_prompt_tokens=0, session_completion_tokens=0, session_total_tokens=0, session_input_tokens=0, session_output_tokens=0, session_cache_read_tokens=0, - session_cache_write_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", + session_cache_write_tokens=0, session_reasoning_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", log_prefix="", platform="cli", compression_enabled=True, _user_turn_count=1, context_compressor=SimpleNamespace(compression_count=0, last_prompt_tokens=40_000, threshold_tokens=60_000, summary_target_ratio=0.2, last_compression_rough_tokens=0, @@ -96,7 +96,7 @@ def test_an_openai_spec_route_is_warmed_at_25_minutes_and_replayed_with_the_smal def test_a_mid_chat_route_switch_makes_the_next_request_offload_first(): """/model or a fallback moves the chat to a route that never saw its prefix: the cache is cold there, so the turn-start offload runs before the first request on the new route.""" - from agent.turn_proactive_prune import prompt_cache_is_cold + from agent.prompt_cache_clock import prompt_cache_is_cold agent = _agent("deepseek/deepseek-v4-flash") _respond(agent, {"model": agent.model, "messages": [{"role": "user", "content": "hi"}]}) diff --git a/tests/agent/test_prompt_cache_rulings.py b/tests/agent/test_prompt_cache_rulings.py index f4aca34429..b36686d7c3 100644 --- a/tests/agent/test_prompt_cache_rulings.py +++ b/tests/agent/test_prompt_cache_rulings.py @@ -77,7 +77,7 @@ def _chat(client=None, **over): _interrupt_requested=False, _anthropic_client=client or _Client(), model="claude-opus-4-7", provider="anthropic", base_url="https://api.anthropic.com", api_key="", session_api_calls=7, session_prompt_tokens=0, session_completion_tokens=0, session_total_tokens=0, session_input_tokens=0, - session_output_tokens=0, session_cache_read_tokens=0, session_cache_write_tokens=0, + session_output_tokens=0, session_cache_read_tokens=0, session_cache_write_tokens=0, session_reasoning_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", log_prefix="", platform="cli", compression_enabled=True, _user_turn_count=1, _executing_tools=False, context_compressor=SimpleNamespace( diff --git a/tests/agent/test_prompt_cache_warmer.py b/tests/agent/test_prompt_cache_warmer.py index 8f2ec2339c..e07c9acb6b 100644 --- a/tests/agent/test_prompt_cache_warmer.py +++ b/tests/agent/test_prompt_cache_warmer.py @@ -53,7 +53,7 @@ def _agent(**over): model="claude-opus-4-7", provider="anthropic", base_url="https://api.anthropic.com", api_key="", session_api_calls=7, session_prompt_tokens=0, session_completion_tokens=0, session_total_tokens=0, session_input_tokens=0, session_output_tokens=0, session_cache_read_tokens=0, - session_cache_write_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", + session_cache_write_tokens=0, session_reasoning_tokens=0, session_estimated_cost_usd=0.0, _session_db=None, session_id="s", log_prefix="", ) base.update(over) diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.py index 5d2d6b3f1d..9e6c441368 100644 --- a/tools/tool_result_storage.py +++ b/tools/tool_result_storage.py @@ -15,7 +15,7 @@ import shlex import tempfile import threading import time -from typing import Any, Container +from typing import Any from session_rules.media import PRUNED_SUBDIR, SPILLOVER_SUBDIR, archive_refs_in_text from tools.budget_config import DEFAULT_PREVIEW_SIZE_CHARS, BudgetConfig, DEFAULT_BUDGET @@ -355,22 +355,20 @@ def _with_pointer(content: Any, display_path: str) -> Any: def archive_pruned_originals( - messages: list[dict[str, Any]], pruned: list[dict[str, Any]], session_id: str, *, - skip: Container[int] = frozenset(), + messages: list[dict[str, Any]], pruned: list[dict[str, Any]], session_id: str, ) -> tuple[list[dict[str, Any]], list[str], int]: """Write the original of every tool row *pruned* changed; returns ``(rows, written host paths, reverted)``. A changed row whose archive write fails is put back to its original (``reverted`` counts them), so the caller re-checks its reclaim gate and never commits a stub without a file behind it. A row - that already names its archive is left as the prune made it: its original is on disk. Rows at - *skip* indices are left as they are (another pass already archived what replaces them). + that already names its archive is left as the prune made it: its original is on disk. """ from agent.context_compressor import _tool_calls_by_id call_id_to_tool = _tool_calls_by_id(messages) rows, written, reverted = list(pruned), [], 0 for i, (original, replacement) in enumerate(zip(messages, pruned)): - if (i in skip or not isinstance(original, dict) or original.get("role") != "tool" + if (not isinstance(original, dict) or original.get("role") != "tool" or not isinstance(replacement, dict) or replacement.get("content") == original.get("content")): continue body = original.get("content") @@ -389,8 +387,7 @@ def archive_pruned_originals( def archive_compaction_drops( - messages: list[dict[str, Any]], dropped: list[dict[str, Any]], session_id: str, *, - skip: Container[int] = frozenset(), + messages: list[dict[str, Any]], dropped: list[dict[str, Any]], session_id: str, ) -> tuple[list[dict[str, Any]], list[str], int]: """:func:`archive_pruned_originals` for a compaction's tool-result drops (window prune, lean tail). @@ -400,7 +397,7 @@ def archive_compaction_drops( """ if not _backend_reads_host_files(): return dropped, [], 0 - return archive_pruned_originals(messages, dropped, session_id, skip=skip) + return archive_pruned_originals(messages, dropped, session_id) ARCHIVE_LIST_HEADING = "Archived tool output (exact originals; read_file a path to recover one):"