Skip to content

The agent that grows with you

fix(gateway): bound the model payload when hygiene has not landed (#111988)

finn7635ae06d38d3cd
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index ae69e6b99de..e8d2cbc7154 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -78,6 +78,38 @@ def is_context_overflow_failure_result(agent_result: dict, history_len: int) ->
return any(p in err for p in _CONTEXT_OVERFLOW_ERROR_PHRASES) or ("400" in err and history_len > 50)
+# Setup/prefix rows rather than conversation: the agent rebuilds its own system prompt, and a
+# transcript meta row is logging-only — neither reaches the model, but both are the head a
+# fail-closed payload keeps.
+_HYGIENE_SETUP_ROLES = ("system", "session_meta")
+
+
+def bound_model_input_without_hygiene(history: List[Any], limit: int) -> List[Any]:
+ """Fail-closed in-context bound for a turn where hygiene has not landed (#111988).
+
+ Keeps the leading ``system``/``session_meta`` setup rows plus the newest tail, total <= ``limit``.
+ Deterministic (the same transcript always yields the same cut) and payload-only: the stored
+ transcript is never touched, so the agent's durable-prefix slice (``history_offset``) is
+ unaffected. Returns ``history`` unchanged — same object — when nothing needs dropping, so the
+ landed-compression and below-the-limit paths stay byte-identical.
+ """
+ if not isinstance(history, list) or not isinstance(limit, int) or limit <= 0 or len(history) <= limit:
+ return history
+ head_end = 0
+ while (head_end < len(history) and isinstance(history[head_end], dict)
+ and history[head_end].get("role") in _HYGIENE_SETUP_ROLES):
+ head_end += 1
+ # Always leave room for the newest row: a setup-only payload would answer nothing.
+ head_end = min(head_end, limit - 1)
+ tail_start = len(history) - (limit - head_end)
+ # Never start the kept tail on a tool result: its parent assistant(tool_calls) row is dropped
+ # with it, and an orphaned tool result is an invalid sequence for every provider.
+ while (tail_start < len(history) and isinstance(history[tail_start], dict)
+ and history[tail_start].get("role") == "tool"):
+ tail_start += 1
+ return history[:head_end] + history[tail_start:]
+
+
class GatewayTurnMixin:
"""Agent-turn execution for GatewayRunner (see module docstring)."""
@@ -1237,11 +1269,14 @@ class GatewayTurnMixin:
return history
hs = await self._hmwa_hygiene_settings(source, session_key)
+ # Hygiene can never land with compression disabled; a sub-limit transcript is the identity (#111988).
if not hs.compression_enabled:
- return history
+ return self._bound_hygiene_payload(history, hs, session_entry)
plan = await self._hmwa_hygiene_plan(hs, history, session_entry, session_key)
+ # No compression this turn (under both thresholds, cooldown, or one already in flight): without
+ # the bound the model would get the full uncompressed transcript.
if not plan.needs_compress:
- return history
+ return self._bound_hygiene_payload(history, hs, session_entry)
attempt = self._HygieneAttempt(agent=None, meta=self._event_thread_metadata(event, source), history=history)
try:
@@ -1267,8 +1302,26 @@ class GatewayTurnMixin:
pass
except Exception as e:
logger.warning("Session hygiene auto-compress failed: %s", e)
+ # A landed compression published a NEW transcript on attempt.history: leave it byte-identical.
+ # Anything else (turn-hold, timeout, unwind, codex path) left the FULL uncompressed transcript
+ # there — that is the fail-closed case (#111988).
+ if attempt.history is history:
+ return self._bound_hygiene_payload(history, hs, session_entry)
return attempt.history
+ @staticmethod
+ def _bound_hygiene_payload(history, hs, session_entry):
+ """``bound_model_input_without_hygiene`` over ``hs.hard_msg_limit``, with one INFO line when the
+ cut is real. Below the limit this is the identity — no allocation, no behaviour change."""
+ bounded = bound_model_input_without_hygiene(history, hs.hard_msg_limit)
+ if bounded is not history:
+ logger.info(
+ "Session hygiene did not land for %s: bounding the model payload to %s of %s "
+ "messages (hard limit %s) — the stored transcript is unchanged",
+ session_entry.session_id, len(bounded), len(history), hs.hard_msg_limit,
+ )
+ return bounded
+
async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes):
"""First-ever-message onboarding note + one-time 'no home channel' prompt (both only when
the session has no history). Delivered on the user message (sidecar), NOT the ephemeral
diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.py
index bbe7d357521..cc2d6a6d7f5 100644
--- a/tests/gateway/test_session_hygiene.py
+++ b/tests/gateway/test_session_hygiene.py
@@ -1815,3 +1815,215 @@ async def test_hygiene_unwind_records_cooldown(monkeypatch, tmp_path):
await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)
finally:
db.close()
+
+
+# ---------------------------------------------------------------------------
+# Fail-closed in-context bound when hygiene has not landed (#111988)
+# ---------------------------------------------------------------------------
+
+_HARD_LIMIT = 20
+
+
+def _make_bound_probe_transcript(total: int = 60) -> list:
+ """Transcript with a setup prefix, a tool group straddling the tail cut, and a newest tail.
+
+ With ``_HARD_LIMIT`` = 20 and one setup row, the newest-19 cut starts at index 41 — the
+ first tool result of the group at 40/41/42.
+ """
+ rows = [{"role": "session_meta", "tools": [], "model": "m", "platform": "telegram", "timestamp": "t0"}]
+ while len(rows) < total - 20:
+ role = "user" if len(rows) % 2 else "assistant"
+ rows.append({"role": role, "content": f"old-{len(rows)}", "timestamp": f"t{len(rows)}"})
+ rows.append({"role": "assistant", "content": "", "tool_calls": [{"id": "c1", "function": {"name": "t"}}]})
+ rows.append({"role": "tool", "tool_call_id": "c1", "content": "old tool output 1"})
+ rows.append({"role": "tool", "tool_call_id": "c2", "content": "old tool output 2"})
+ rows.append({"role": "user", "content": "newest ask", "timestamp": "t-ask"})
+ rows.append({"role": "assistant", "content": "newest reply", "timestamp": "t-reply"})
+ while len(rows) < total:
+ role = "user" if len(rows) % 2 else "assistant"
+ rows.append({"role": role, "content": f"tail-{len(rows)}", "timestamp": f"t{len(rows)}"})
+ if total == 60:
+ assert rows[41].get("role") == "tool", "fixture must put the tail cut on a tool result"
+ return rows
+
+
+def _turn_payload(runner):
+ """The history the gateway handed the turn runner for the model (one turn)."""
+ assert runner._run_agent.await_count == 1
+ return runner._run_agent.call_args.kwargs["history"]
+
+
+def _make_bound_runner(monkeypatch, tmp_path, agent_cls, cfg_text, transcript):
+ """``_make_cooldown_runner`` with a >hard-limit transcript and a lowered hard limit."""
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("sess-bound", "telegram")
+ runner, adapter, event = _make_cooldown_runner(
+ monkeypatch, tmp_path, agent_cls, db, "sess-bound"
+ )
+ (tmp_path / "config.yaml").write_text(cfg_text, encoding="utf-8")
+ runner.session_store.load_transcript.return_value = transcript
+ return db, runner, adapter, event
+
+
+class _LandedCompressAgent:
+ """Rotating hygiene compressor that SUCCEEDS with a transcript longer than the hard limit."""
+
+ last_instance = None
+
+ def __init__(self, **kwargs):
+ self.session_id = kwargs.get("session_id", "fake-session")
+ self._session_db = kwargs.get("session_db")
+ self._last_compaction_in_place = False
+ self.context_compressor = SimpleNamespace(
+ bind_session_state=MagicMock(),
+ _last_compress_aborted=False,
+ _last_aux_model_failure_model=None,
+ )
+ self.shutdown_memory_provider = MagicMock()
+ self.close = MagicMock()
+ type(self).last_instance = self
+
+ def _compress_context(self, messages, *_args, **_kwargs):
+ # 25 rows: over the 20-message limit but far under the input's token count, so the
+ # adopted (landed) transcript must reach the model untouched.
+ compressed = [{"role": "assistant", "content": f"summary {i}"} for i in range(25)]
+ type(self).last_compressed = compressed
+ self.session_id = f"{self.session_id}_compressed"
+ return (compressed, None)
+
+
+def test_bound_model_input_without_hygiene_is_deterministic_and_fail_closed():
+ """The bound keeps the setup head + the newest tail, drops the middle, never mutates input."""
+ from gateway.run_turn import bound_model_input_without_hygiene
+
+ rows = _make_bound_probe_transcript()
+ snapshot = [dict(r) for r in rows]
+
+ bounded = bound_model_input_without_hygiene(rows, _HARD_LIMIT)
+
+ assert len(bounded) <= _HARD_LIMIT
+ assert len(bounded) < len(rows), "a >limit transcript must actually be bounded"
+ assert bounded[0] is rows[0], "the leading system/setup row must survive"
+ assert bounded[-1] is rows[-1], "the newest row must survive"
+ assert bounded[1].get("role") != "tool", "the kept tail must not start on an orphan tool result"
+ assert rows[:] == snapshot, "the source transcript must not be mutated in place"
+ # Same input, same cut — no randomness, no clock.
+ assert bound_model_input_without_hygiene(rows, _HARD_LIMIT) == bounded
+ # At or below the limit nothing is dropped, and the SAME list comes back.
+ assert bound_model_input_without_hygiene(rows, len(rows)) is rows
+ assert bound_model_input_without_hygiene(rows, len(rows) + 5) is rows
+
+
+async def test_hygiene_miss_bounds_the_model_payload(monkeypatch, tmp_path):
+ """Turn-hold expiry without a landed summary must not feed the model the whole transcript."""
+ worker_started = threading.Event()
+ release_worker = threading.Event()
+ cleanup_done = threading.Event()
+ session_id = "sess-bound"
+
+ class StreamingCompressAgent:
+ last_instance = None
+
+ def __init__(self, **kwargs):
+ self.session_id = kwargs.get("session_id", session_id)
+ self._session_db = kwargs.get("session_db")
+ self._last_compaction_in_place = False
+ self.context_compressor = SimpleNamespace(
+ bind_session_state=MagicMock(),
+ _last_compress_aborted=False,
+ _last_aux_model_failure_model=None,
+ )
+ self.shutdown_memory_provider = MagicMock()
+ self.close = MagicMock(side_effect=cleanup_done.set)
+ type(self).last_instance = self
+
+ def _compress_context(self, messages, *_args, commit_fence=None, **_kwargs):
+ worker_started.set()
+ release_worker.wait(timeout=10)
+ return (messages, None)
+
+ transcript = _make_bound_probe_transcript()
+ db, runner, _adapter, event = _make_bound_runner(
+ monkeypatch, tmp_path, StreamingCompressAgent,
+ "compression:\n"
+ " enabled: true\n"
+ f" hygiene_hard_message_limit: {_HARD_LIMIT}\n"
+ " hygiene_timeout_seconds: 60\n"
+ " hygiene_total_ceiling_seconds: 600\n"
+ " hygiene_max_turn_hold_seconds: 0.3\n",
+ transcript,
+ )
+ try:
+ assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok"
+ assert worker_started.wait(timeout=2)
+
+ payload = _turn_payload(runner)
+ assert len(payload) <= _HARD_LIMIT, (
+ f"hygiene never landed but the model got {len(payload)} messages "
+ f"(limit {_HARD_LIMIT}) — unbounded fail-open"
+ )
+ assert payload[0] is transcript[0], "the system/setup head must be preserved"
+ assert payload[-1] is transcript[-1], "the newest tail must be preserved"
+ assert payload[1].get("role") != "tool", "the kept tail must not start on an orphan tool result"
+
+ # History on disk untouched: the loaded transcript still holds every row and nothing
+ # rewrote it — only the payload about to be sent to the model was clipped.
+ assert len(transcript) == len(_make_bound_probe_transcript())
+ assert transcript[20]["content"].startswith("old-")
+ runner.session_store.rewrite_transcript.assert_not_called()
+
+ release_worker.set()
+ await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=3)
+ finally:
+ release_worker.set()
+ db.close()
+
+
+async def test_hygiene_landed_payload_is_byte_identical(monkeypatch, tmp_path):
+ """A landed hygiene commit is adopted as-is — the bound must not touch it."""
+ transcript = _make_bound_probe_transcript()
+ db, runner, _adapter, event = _make_bound_runner(
+ monkeypatch, tmp_path, _LandedCompressAgent,
+ "compression:\n"
+ " enabled: true\n"
+ f" hygiene_hard_message_limit: {_HARD_LIMIT}\n",
+ transcript,
+ )
+ try:
+ assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok"
+ payload = _turn_payload(runner)
+ assert payload is _LandedCompressAgent.last_compressed, (
+ "a landed hygiene commit must reach the model as the adopted transcript, "
+ f"unmodified; got {len(payload)} rows"
+ )
+ runner.session_store.rewrite_transcript.assert_called()
+ finally:
+ db.close()
+
+
+async def test_hygiene_not_needed_payload_is_the_loaded_transcript(monkeypatch, tmp_path):
+ """Below the limit the payload is the very list loaded from disk — zero behaviour change."""
+ transcript = _make_bound_probe_transcript(total=_HARD_LIMIT - 1)
+ db, runner, _adapter, event = _make_bound_runner(
+ monkeypatch, tmp_path, _LandedCompressAgent,
+ "compression:\n"
+ " enabled: true\n"
+ f" hygiene_hard_message_limit: {_HARD_LIMIT}\n",
+ transcript,
+ )
+ # A context window wide enough that the token threshold cannot fire either: hygiene is a
+ # no-op this turn, so the bound must be one too.
+ monkeypatch.setattr(
+ "agent.model_metadata.get_model_context_length", lambda *_args, **_kwargs: 1_000_000
+ )
+ try:
+ assert await asyncio.wait_for(runner._handle_message(event), timeout=15) == "ok"
+ payload = _turn_payload(runner)
+ assert payload is transcript, "a sub-limit transcript must pass through untouched"
+ finally:
+ db.close()