The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): compact the live codex thread instead of no-op mirror rewrites (#73503)
Tekniumff3835a630de
diff --git a/gateway/run.py b/gateway/run.pyindex 2a6a54f96cd..a7a6191bf7f 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -314,6 +314,135 @@ def _hygiene_compression_timeout_message()+async def run_codex_hygiene_compaction(+ gateway,+ session_key: str,+ session_id: str,+ *,+ auto_mode: str,+ history: list,+ approx_tokens: int,+ timeout_seconds: float,+ failure_cooldown_seconds: float = 300.0,+) -> str:+ """Session hygiene for ``codex_app_server`` sessions (#73503).++ On this runtime the model's real working context is the app-server's+ server-side thread, not Hermes' transcript: ``CodexAppServerSession`` is+ constructed with no history and each turn submits only the new user+ message (agent/codex_runtime.py), so the persisted transcript is a mirror+ that is never replayed into a thread. Two consequences drive this path:++ * Rewriting the local mirror (the detached hygiene agent's normal+ compression) shrinks nothing the model actually carries — it was a+ permanent no-op ("compressed 150 -> 150 msgs").+ * Evicting the cached live agent afterwards destroys the only real+ context: the next turn spawns an EMPTY thread and the model starts+ blank while Hermes still mirrors a full history (abrupt amnesia — the+ user-facing damage documented on #73503).++ So hygiene must compact the LIVE cached agent's thread via the+ app-server's own ``thread/compact/start`` (through+ ``_compress_context_via_codex_app_server``) and KEEP that agent cached.+ Never build a detached compressor and never evict here.++ Mode contract (``compression.codex_app_server_auto``): only ``hermes``+ lets Hermes' threshold initiate app-server compaction; ``native`` leaves+ the schedule to codex itself and ``off`` disables Hermes-initiated+ automatic compaction entirely — both return without touching the thread+ or the transcript, and neither may fall back to the local compressor.++ Returns an outcome tag for logging/tests: ``compacted``,+ ``skipped:<reason>`` or ``failed:<reason>``.+ """+ mode = str(auto_mode or "native").lower()+ if mode not in {"native", "hermes", "off"}:+ mode = "native"+ if mode != "hermes":+ # native: the app-server compacts on its own schedule; off: the+ # operator disabled Hermes-initiated automatic compaction. A local+ # transcript fallback is wrong in EVERY mode here (it cannot shrink+ # the thread), so both modes are a clean skip — crucially without+ # the detached-compressor path's cache eviction.+ return f"skipped:mode={mode}"++ agent = None+ lock = getattr(gateway, "_agent_cache_lock", None)+ cache = getattr(gateway, "_agent_cache", None)+ if cache is not None:+ try:+ if lock:+ with lock:+ entry = cache.get(session_key)+ else:+ entry = cache.get(session_key)+ except Exception:+ entry = None+ agent = entry[0] if isinstance(entry, tuple) and entry else entry+ if agent is None or agent is _AGENT_PENDING_SENTINEL:+ # No live agent → no live thread → nothing real to compact. The+ # mirror-only rewrite the detached path would perform is exactly the+ # no-op this function exists to remove, so skip honestly instead.+ return "skipped:no-cached-agent"+ if getattr(agent, "_codex_session", None) is None:+ return "skipped:no-live-thread"++ loop = asyncio.get_running_loop()+ compressor = getattr(agent, "context_compressor", None)+ count_before = getattr(compressor, "compression_count", 0)+ try:+ await asyncio.wait_for(+ loop.run_in_executor(+ None,+ lambda: agent._compress_context(+ history,+ "",+ approx_tokens=approx_tokens,+ ),+ ),+ timeout=max(float(timeout_seconds), 1.0),+ )+ except asyncio.TimeoutError:+ # The executor thread keeps running (compact_thread has its own RPC+ # timeouts); brake per-turn retries so a wedged app-server does not+ # re-trigger a compaction attempt on every message.+ if failure_cooldown_seconds >= 0:+ _record_hygiene_cooldown(+ gateway,+ session_id,+ failure_cooldown_seconds,+ "codex app-server thread compaction timed out",+ )+ logger.warning(+ "Session hygiene: codex app-server thread compaction for "+ "session %s timed out after %.1fs; continuing without compaction",+ session_id,+ timeout_seconds,+ )+ return "failed:timeout"+ except Exception as exc:+ logger.warning(+ "Session hygiene: codex app-server thread compaction for "+ "session %s failed: %s",+ session_id,+ exc,+ )+ return f"failed:{exc}"++ count_after = getattr(compressor, "compression_count", 0)+ if count_after > count_before:+ # A native compaction boundary was recorded on the live agent+ # (thread compacted server-side; transcript intentionally NOT+ # rewritten — state.db records the boundary, the mirror stays+ # intact and the agent stays cached).+ _reset_hygiene_failure_streak(gateway, session_key)+ return "compacted"+ # compress_context returned without recording a boundary: an internal+ # skip (its own failure cooldown) or a compaction error — the codex+ # route already persisted its own failure cooldown in that case.+ return "failed:no-boundary"++def _record_hygiene_cooldown(gateway,session_id: str,@@ -20512,7 +20641,51 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewsession_key=session_key,user_config=_hyg_data if isinstance(_hyg_data, dict) else None,)- if _hyg_runtime.get("api_key"):+ _hyg_api_mode = str(+ _hyg_runtime.get("api_mode") or ""+ ).lower()+ if _hyg_api_mode == "codex_app_server":+ # codex app-server runtime: the model's real+ # context is the app-server's server-side thread,+ # not the transcript mirror. The detached-agent+ # block below could only rewrite the mirror (a+ # guaranteed no-op for the thread) and its+ # finally-clause eviction would destroy the live+ # thread — the next turn then starts blank+ # (#73503). Route to the live cached agent's+ # thread/compact/start instead and KEEP it cached.+ _hyg_codex_auto = "native"+ _hyg_comp_cfg = (+ _hyg_data.get("compression")+ if isinstance(_hyg_data, dict)+ else None+ )+ if isinstance(_hyg_comp_cfg, dict):+ _hyg_codex_auto = str(+ _hyg_comp_cfg.get(+ "codex_app_server_auto", "native"+ )+ or "native"+ )+ _hyg_codex_outcome = await run_codex_hygiene_compaction(+ self,+ session_key,+ session_entry.session_id,+ auto_mode=_hyg_codex_auto,+ history=history,+ approx_tokens=_approx_tokens,+ timeout_seconds=_hyg_total_ceiling_seconds,+ failure_cooldown_seconds=_hyg_failure_cooldown_seconds,+ )+ logger.info(+ "Session hygiene (codex app-server): %s "+ "(session=%s, mode=%s, ~%s tokens)",+ _hyg_codex_outcome,+ session_entry.session_id,+ _hyg_codex_auto,+ f"{_approx_tokens:,}",+ )+ elif _hyg_runtime.get("api_key"):# Pass the FULL transcript (tool results included).# Filtering to user/assistant-only starved the# compressor: tool results are usually the bulk ofdiff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex bd86f0d96d5..2bf7e557976 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -4449,6 +4449,67 @@ class GatewaySlashCommandsMixin:with _profile_runtime_scope(profile_home):return await self._handle_compress_command_inner(event)+ async def _compress_codex_app_server_session(+ self, session_key: str, session_id: str+ ) -> str:+ """Manual /compress for codex_app_server sessions (#73503).++ Compacts the LIVE cached agent's app-server thread via+ ``thread/compact/start`` (through ``_compress_context``'s codex route+ with ``force=True``, which bypasses the automatic-mode gate in every+ ``compression.codex_app_server_auto`` mode — a manual /compress is an+ explicit user decision) and keeps that agent cached, so the compacted+ thread is what the next turn continues from. Never builds a temporary+ compression agent and never rewrites the transcript mirror: neither+ can shrink the server-side thread that is the model's real context.+ """+ agent = None+ lock = getattr(self, "_agent_cache_lock", None)+ cache = getattr(self, "_agent_cache", None)+ if cache is not None:+ if lock:+ with lock:+ entry = cache.get(session_key)+ else:+ entry = cache.get(session_key)+ agent = entry[0] if isinstance(entry, tuple) and entry else entry+ from gateway.run import _AGENT_PENDING_SENTINEL++ if (+ agent is None+ or agent is _AGENT_PENDING_SENTINEL+ or getattr(agent, "_codex_session", None) is None+ ):+ return (+ "🗜️ Nothing to compact: this session runs on the Codex "+ "app-server runtime, whose context lives in a Codex-owned "+ "thread that only exists while the agent is active. Send a "+ "message first, then /compress — or /reset to start fresh."+ )++ compressor = getattr(agent, "context_compressor", None)+ count_before = getattr(compressor, "compression_count", 0)+ try:+ await self._run_in_executor_with_context(+ lambda: agent._compress_context(+ [], "", force=True,+ )+ )+ except Exception as exc:+ return t("gateway.compress.failed", error=exc)+ count_after = getattr(compressor, "compression_count", 0)+ if count_after > count_before:+ return (+ "🗜️ Codex app-server thread compacted (thread/compact). "+ "The transcript mirror is unchanged by design — the "+ "app-server now carries the compacted context."+ )+ return (+ "⚠️ Codex app-server compaction did not complete — the thread "+ "is unchanged. Check the app-server logs, retry /compress, or "+ "/reset for a clean session."+ )+async def _handle_compress_command_inner(self, event: MessageEvent) -> str:"""Handle /compress command -- manually compress conversation context.@@ -4538,6 +4599,23 @@ class GatewaySlashCommandsMixin:source=source,session_key=session_key,)+ if str(runtime_kwargs.get("api_mode") or "").lower() == "codex_app_server":+ # codex app-server runtime (#73503): the model's working+ # context is the app-server's server-side thread, owned by the+ # LIVE cached agent (agent/codex_runtime.py — one+ # CodexAppServerSession per AIAgent, spawned lazily on first+ # turn). A temporary compression agent has no thread, so the+ # codex route in _compress_context_via_codex_app_server bailed+ # at its "no active codex thread" guard, the transcript came+ # back unchanged, and the finally-clause eviction below then+ # destroyed the only real context. Compact the live agent's+ # thread via thread/compact/start instead — and KEEP the agent+ # cached so the compacted thread survives to the next turn.+ # No local transcript fallback in any mode: rewriting the+ # mirror cannot shrink the thread.+ return await self._compress_codex_app_server_session(+ session_key, session_entry.session_id+ )if not runtime_kwargs.get("api_key"):return t("gateway.compress.no_provider")diff --git a/tests/gateway/test_codex_hygiene_compaction.py b/tests/gateway/test_codex_hygiene_compaction.pynew file mode 100644index 00000000000..71dd907f3be--- /dev/null+++ b/tests/gateway/test_codex_hygiene_compaction.py@@ -0,0 +1,338 @@+"""Regression tests for #73503 — codex_app_server compression must not be a no-op.++On the codex_app_server runtime the model's real working context is the+app-server's server-side thread (CodexAppServerSession is constructed with no+history and each turn submits only the new user message), so:++* the old detached-agent hygiene path could only rewrite the transcript+ mirror — a guaranteed no-op ("compressed 150 -> 150 msgs") — and then+ evicted the live cached agent, destroying the thread that held the only+ real context;+* the fix routes hygiene and manual /compress to the LIVE cached agent's+ ``thread/compact/start`` (asserted here at the compact_thread RPC-stub+ boundary) and keeps that agent cached;+* ``compression.codex_app_server_auto`` semantics hold: only ``hermes``+ lets Hermes' threshold start a compaction; ``native``/``off`` skip+ cleanly, and no mode ever runs the local transcript compressor.+"""++import asyncio+from types import SimpleNamespace++import pytest++from agent.conversation_compression import compress_context+from agent.transports.codex_app_server_session import TurnResult+from gateway.run import run_codex_hygiene_compaction+++class FakeCodexSession:+ """RPC-stub boundary: stands in for the app-server thread client."""++ def __init__(self, result=None):+ self.result = result or TurnResult(+ thread_id="thread-1", turn_id="compact-1", compacted=True+ )+ self.compact_calls = 0+ self.closed = False++ def compact_thread(self):+ self.compact_calls += 1+ return self.result++ def close(self):+ self.closed = True+++class LiveCodexAgent:+ """Minimal live cached agent whose _compress_context is the REAL routing.++ The forwarder mirrors run_agent.AIAgent._compress_context: it calls the+ module-level compress_context(), so these tests exercise the genuine+ codex route (mode gate, cooldown, compact_thread RPC) rather than a stub+ of the code under test.+ """++ def __init__(self, mode="hermes", session=None):+ self.api_mode = "codex_app_server"+ self.codex_app_server_auto_compaction = mode+ self.session_id = "sess-1"+ self.platform = "telegram"+ self._cached_system_prompt = "cached prompt"+ self._codex_session = session if session is not None else FakeCodexSession()+ self.context_compressor = SimpleNamespace(+ compression_count=0,+ last_compression_rough_tokens=0,+ last_prompt_tokens=100,+ last_completion_tokens=10,+ awaiting_real_usage_after_compression=False,+ )+ self.local_compress_calls = 0+ self.warnings = []++ # -- surface used by compress_context --------------------------------+ def _touch_activity(self, *a, **k):+ pass++ def _emit_status(self, m):+ pass++ def _emit_warning(self, m):+ self.warnings.append(m)++ def _build_system_prompt(self, s):+ return "built prompt"++ def _compress_context(self, messages, system_message, **kwargs):+ return compress_context(self, messages, system_message, **kwargs)+++def _history(n=150):+ return [+ {"role": "user" if i % 2 == 0 else "assistant", "content": f"m{i}" * 50}+ for i in range(n)+ ]+++def _gateway(tmp_path, session_key="tg:123", agent=None):+ from hermes_state import SessionDB++ db = SessionDB(db_path=tmp_path / "state.db")+ gw = SimpleNamespace(+ _agent_cache={} if agent is None else {session_key: (agent, 0.0)},+ _agent_cache_lock=None,+ _session_db=db,+ )+ return gw, db+++# ---------------------------------------------------------------------------+# Core no-op regression: hermes mode + live thread => thread/compact runs+# ---------------------------------------------------------------------------++def test_hermes_mode_compacts_live_thread_at_rpc_boundary(tmp_path):+ agent = LiveCodexAgent(mode="hermes")+ key = "tg:123"+ gw, db = _gateway(tmp_path, key, agent)+ # Pre-arm a persisted failure streak so success provably resets it+ # through the REAL SessionDB (hygiene path involves the DB).+ assert db.increment_hygiene_failure_streak(key) == 1++ outcome = asyncio.run(+ run_codex_hygiene_compaction(+ gw,+ key,+ agent.session_id,+ auto_mode="hermes",+ history=_history(),+ approx_tokens=345_000,+ timeout_seconds=30.0,+ )+ )++ assert outcome == "compacted"+ # The no-op is gone: the thread genuinely shrank via the app-server's own+ # mechanism — asserted at the RPC-stub boundary.+ assert agent._codex_session.compact_calls == 1+ # A compaction boundary was recorded on the live agent's compressor.+ assert agent.context_compressor.compression_count == 1+ # The live agent is STILL cached — hygiene must not evict the thread owner.+ assert gw._agent_cache[key][0] is agent+ # Success reset the persisted hygiene failure streak.+ assert db.increment_hygiene_failure_streak(key) == 1 # was cleared to 0+++def test_hermes_mode_without_cached_agent_skips_without_local_compression(tmp_path):+ # Detached case: no live agent → no thread → nothing real to compact.+ # The old behavior "compressed" the mirror (a no-op) and then evicted;+ # the new behavior is an honest skip with the transcript untouched.+ gw, _ = _gateway(tmp_path, agent=None)+ history = _history()+ before = [dict(m) for m in history]++ outcome = asyncio.run(+ run_codex_hygiene_compaction(+ gw,+ "tg:123",+ "sess-1",+ auto_mode="hermes",+ history=history,+ approx_tokens=345_000,+ timeout_seconds=5.0,+ )+ )++ assert outcome == "skipped:no-cached-agent"+ assert history == before+++# ---------------------------------------------------------------------------+# Mode semantics: native / off never touch the thread nor run local fallback+# ---------------------------------------------------------------------------+[email protected]("mode", ["native", "off"])+def test_native_and_off_modes_skip_cleanly(tmp_path, mode):+ agent = LiveCodexAgent(mode=mode)+ key = "tg:123"+ gw, _ = _gateway(tmp_path, key, agent)++ outcome = asyncio.run(+ run_codex_hygiene_compaction(+ gw,+ key,+ agent.session_id,+ auto_mode=mode,+ history=_history(),+ approx_tokens=345_000,+ timeout_seconds=5.0,+ )+ )++ assert outcome == f"skipped:mode={mode}"+ # off must not silently compress; native leaves scheduling to codex.+ assert agent._codex_session.compact_calls == 0+ assert agent.context_compressor.compression_count == 0+ # And the agent stays cached in every skip path.+ assert gw._agent_cache[key][0] is agent+++def test_unknown_mode_falls_back_to_native_semantics(tmp_path):+ agent = LiveCodexAgent(mode="banana")+ gw, _ = _gateway(tmp_path, "tg:123", agent)+ outcome = asyncio.run(+ run_codex_hygiene_compaction(+ gw,+ "tg:123",+ agent.session_id,+ auto_mode="banana",+ history=_history(),+ approx_tokens=345_000,+ timeout_seconds=5.0,+ )+ )+ assert outcome == "skipped:mode=native"+ assert agent._codex_session.compact_calls == 0+++# ---------------------------------------------------------------------------+# force=True (manual /compress) must never violate the "no local fallback"+# contract: it compacts the THREAD in every mode, and never rewrites the+# transcript mirror.+# ---------------------------------------------------------------------------+[email protected]("mode", ["native", "hermes", "off"])+def test_force_compacts_thread_never_local_fallback(mode):+ agent = LiveCodexAgent(mode=mode)+ messages = _history()+ before = [dict(m) for m in messages]++ returned, prompt = compress_context(+ agent, messages, "system", approx_tokens=345_000, force=True+ )++ # Thread compaction ran (manual force is an explicit user decision)...+ assert agent._codex_session.compact_calls == 1+ # ...and the local transcript mirror was NOT rewritten in any mode.+ assert returned is messages+ assert returned == before+ assert prompt == "cached prompt"++[email protected]("mode", ["native", "off"])+def test_force_without_live_thread_does_not_run_local_compressor(mode):+ # The #73715 branch let force=True fall through to the local Hermes+ # compressor in native/off when no thread existed. That is wrong on this+ # runtime in every mode: rewriting the mirror cannot shrink the thread.+ agent = LiveCodexAgent(mode=mode, session=None)+ agent._codex_session = None+ messages = _history()+ before = [dict(m) for m in messages]++ returned, _ = compress_context(+ agent, messages, "system", approx_tokens=345_000, force=True+ )++ assert returned is messages+ assert returned == before+ assert agent.context_compressor.compression_count == 0+++# ---------------------------------------------------------------------------+# Failure handling: a wedged compaction records a DB cooldown (real SessionDB)+# ---------------------------------------------------------------------------++def test_timeout_records_persistent_cooldown(tmp_path):+ class HangingSession(FakeCodexSession):+ def compact_thread(self):+ self.compact_calls += 1+ import time++ time.sleep(3.0)+ return self.result++ agent = LiveCodexAgent(mode="hermes", session=HangingSession())+ key = "tg:123"+ gw, db = _gateway(tmp_path, key, agent)+ db.create_session(agent.session_id, "gateway")++ outcome = asyncio.run(+ run_codex_hygiene_compaction(+ gw,+ key,+ agent.session_id,+ auto_mode="hermes",+ history=_history(),+ approx_tokens=345_000,+ timeout_seconds=1.0,+ failure_cooldown_seconds=300.0,+ )+ )++ assert outcome == "failed:timeout"+ state = db.get_compression_failure_cooldown(agent.session_id)+ assert state is not None and state.get("remaining_seconds", 0) > 0+ # Even on failure the live agent stays cached — its thread still holds+ # the only real context.+ assert gw._agent_cache[key][0] is agent+++# ---------------------------------------------------------------------------+# Manual /compress gateway surface+# ---------------------------------------------------------------------------++def _slash_host(agent, session_key="tg:123"):+ from gateway.slash_commands import GatewaySlashCommandsMixin++ host = SimpleNamespace(+ _agent_cache={session_key: (agent, 0.0)} if agent is not None else {},+ _agent_cache_lock=None,+ )++ async def _run_in_executor_with_context(fn):+ return await asyncio.get_running_loop().run_in_executor(None, fn)++ host._run_in_executor_with_context = _run_in_executor_with_context+ host._compress_codex_app_server_session = (+ GatewaySlashCommandsMixin._compress_codex_app_server_session.__get__(host)+ )+ return host+++def test_manual_compress_routes_to_live_thread():+ agent = LiveCodexAgent(mode="off") # even 'off': manual is a user decision+ host = _slash_host(agent)++ reply = asyncio.run(+ host._compress_codex_app_server_session("tg:123", agent.session_id)+ )++ assert agent._codex_session.compact_calls == 1+ assert "compacted" in reply+++def test_manual_compress_without_live_thread_reports_honestly():+ host = _slash_host(None)+ reply = asyncio.run(+ host._compress_codex_app_server_session("tg:123", "sess-1")+ )+ assert "Nothing to compact" in reply