Skip to content

The agent that grows with you

fix(agent): persist the summary-overload budget in session state so fresh bindings inherit it

Yuan Li2305385042fa
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index bda2c51052e..bd9e7dc4b26 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -2260,6 +2260,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
self._load_fallback_compression_streak()
self._load_ineffective_compression_count()
self._load_anti_thrash_recovery_deadline()
+ self._load_consecutive_overload_aborts()
self._load_proactive_prune_rearm_tokens()
def on_session_start(self, session_id: str, **kwargs) -> None:
@@ -2270,6 +2271,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
session_db = kwargs.get("session_db", getattr(self, "_session_db", None))
previous_fallback_streak = self._fallback_compression_streak
previous_ineffective_count = self._ineffective_compression_count
+ previous_overload_aborts = self._consecutive_overload_aborts
if boundary_reason == "compression" and old_session_id:
# Parent row carries the streak/strike state across the rotation.
def _parent(method: str, label: str, current: int) -> int:
@@ -2282,6 +2284,9 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
previous_ineffective_count = _parent(
"get_compression_ineffective_count", "compression parent ineffective count", previous_ineffective_count,
)
+ previous_overload_aborts = _parent(
+ "get_compression_overload_streak", "compression parent overload streak", previous_overload_aborts,
+ )
self.bind_session_state(session_db, session_id)
if boundary_reason == "compression":
# Rotation creates a fresh child row first; carry the streak until boundary bookkeeping persists it.
@@ -2290,6 +2295,10 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
if self._ineffective_compression_count != previous_ineffective_count:
self._ineffective_compression_count = previous_ineffective_count
self._persist_ineffective_compression_count()
+ # Same for the sustained-overload budget: nothing else writes the child row at the boundary.
+ if self._consecutive_overload_aborts != previous_overload_aborts:
+ self._consecutive_overload_aborts = previous_overload_aborts
+ self._persist_consecutive_overload_aborts()
def _durable_read(
self, method: str, label: str, coerce, default, *args,
@@ -2351,6 +2360,14 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
def _persist_fallback_compression_streak(self) -> None:
self._durable_write("set_compression_fallback_streak", "compression fallback streak", self._fallback_compression_streak)
+ def _load_consecutive_overload_aborts(self) -> None:
+ """Restore the sustained-overload budget so a fresh compressor bound to a resumed session
+ inherits it (#123167 review P1; same contract as the fallback streak, #100185)."""
+ self._load_durable("_consecutive_overload_aborts", "get_compression_overload_streak", "compression overload streak", int, 0)
+
+ def _persist_consecutive_overload_aborts(self) -> None:
+ self._durable_write("set_compression_overload_streak", "compression overload streak", self._consecutive_overload_aborts)
+
def _load_ineffective_compression_count(self) -> None:
"""Load the durable anti-thrash strike count so a restart never disarms a guard."""
self._load_durable("_ineffective_compression_count", "get_compression_ineffective_count", "compression ineffective count", int, 0)
@@ -2426,6 +2443,12 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
elif self._fallback_compression_streak:
self._fallback_compression_streak = 0
self._persist_fallback_compression_streak()
+ # A completed boundary — healthy summary OR committed degraded fallback — settles the
+ # sustained-overload budget (#123167). Leaving it armed after the degraded fallback
+ # committed would keep the session in degraded mode even after the provider recovers,
+ # with no success path left to reset it (the next summary failure can be any class).
+ self._consecutive_overload_aborts = 0
+ self._persist_consecutive_overload_aborts()
def get_active_compression_failure_cooldown(self, *, refresh: bool = False) -> Optional[Dict[str, Any]]:
"""Return the live compression-failure cooldown for the bound session."""
@@ -2592,6 +2615,9 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
self._persist_fallback_compression_streak()
# Cooldowns are scoped to the failed model/provider; a switch gets an immediate attempt.
self._clear_compression_failure_cooldown()
+ # The overload budget rode those cooldowns; a new runtime restarts it too.
+ self._consecutive_overload_aborts = 0
+ self._persist_consecutive_overload_aborts()
self._verify_compaction_cleared_threshold = self._last_compression_made_progress = False
# Runway was computed against the previous model's trigger; clear the durable copy too.
self._reset_proactive_prune_rearm()
@@ -3919,6 +3945,7 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb
setattr(self, flag, False)
# The provider answered a summary again: the sustained-overload budget restarts (#123167).
self._consecutive_overload_aborts = 0
+ self._persist_consecutive_overload_aborts()
return self._with_summary_prefix(summary)
except Exception as e:
return self._on_summary_failure(e, turns_to_summarize, focus_topic, memory_context)
@@ -4134,10 +4161,13 @@ Write only the summary body. Do not include any preamble or prefix."""
self._last_summary_empty_content_failure = True
elif kind.overloaded:
self._consecutive_overload_aborts += 1
+ self._persist_consecutive_overload_aborts()
# Sustained-overload escalation (#123167): keep aborting only while a retry could still
# succeed soon (#115906); once every recent attempt has aborted, stop treating the
# overload as terminal so compress() commits the deterministic fallback instead of
# growing the transcript into a compression_exhausted auto-reset (total session wipe).
+ # The streak is durable: the gateway binds a fresh compressor to this session on every
+ # turn / cache eviction, and a memory-only budget restarted at zero each time (review P1).
self._last_summary_overload_failure = (
self._consecutive_overload_aborts < _CONSECUTIVE_OVERLOAD_ABORT_ESCALATION
)
diff --git a/hermes_cli/session_schema_history.py b/hermes_cli/session_schema_history.py
index 88aa10350b9..588485da3fe 100644
--- a/hermes_cli/session_schema_history.py
+++ b/hermes_cli/session_schema_history.py
@@ -204,6 +204,7 @@ SCHEMA_HISTORY: dict[str, _TableHistory] = {
)),
('26 2026-09-02T14:22Z 8e4366d358', (('+', 'tool_names', 'last_read_at'),)),
('27 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),
+ ('28 2026-09-25T23:25Z 2941aadffa', (('+', 'compression_overload_streak', 'compression_recovery_deadline'),)),
),
),
"messages": _TableHistory(
diff --git a/hermes_state_common.py b/hermes_state_common.py
index af40537e454..d302a47ae6f 100644
--- a/hermes_state_common.py
+++ b/hermes_state_common.py
@@ -400,6 +400,7 @@ CREATE TABLE IF NOT EXISTS sessions (
compression_fallback_streak INTEGER NOT NULL DEFAULT 0,
compression_ineffective_count INTEGER NOT NULL DEFAULT 0,
compression_recovery_deadline REAL,
+ compression_overload_streak INTEGER NOT NULL DEFAULT 0,
profile_name TEXT,
transport_profile TEXT,
rewind_count INTEGER NOT NULL DEFAULT 0,
diff --git a/hermes_state_compression.py b/hermes_state_compression.py
index 7ea1e4100c4..757099075a5 100644
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@ -436,6 +436,18 @@ class SessionCompressionMixin:
normalized = 0.0
self._write_session_column("compression_recovery_deadline", session_id, normalized or None)
+ def get_compression_overload_streak(self, session_id: str) -> int:
+ """Persisted sustained-overload abort streak (#123167). Durable for the same reason the
+ recovery deadline is (#100185): the gateway rebuilds the compressor on every turn /
+ cache eviction, so a memory-only budget restarts at zero on each rebuild and a sustained
+ summary-provider outage walks every fresh instance back into ``compression_exhausted``."""
+ return self._read_session_number("compression_overload_streak", session_id, int, 0)
+
+ def set_compression_overload_streak(self, session_id: str, streak: int) -> None:
+ """Persist the sustained-overload abort streak for one session."""
+ if session_id:
+ self._write_session_column("compression_overload_streak", session_id, max(0, int(streak)))
+
def refresh_compression_lock(self, session_id: str, holder: str, ttl_seconds: float = 300.0) -> bool:
"""Extend the compression lock lease if ``holder`` still owns it. Ownership is decided by ``holder``
alone, deliberately NOT ``expires_at``: a live owner whose refresher stalled past its TTL must be
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index e71ff311267..a968c3ddc26 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -1105,6 +1105,69 @@ class TestSustainedOverloadEscalation:
assert fresh_abort == msgs
assert c._last_compress_aborted is True
+ def test_overload_budget_survives_a_fresh_compressor_bound_to_the_same_session(self, tmp_path):
+ """Review P1: the N=3 budget must be session-scoped, not object-local.
+
+ The gateway binds a fresh compressor to the existing session on every turn /
+ cache eviction, and restart/resume constructs one too. Each of those used to
+ restart the budget at zero, so a sustained outage never escalated (#123167;
+ same contract as the durable fallback streak, #100185).
+ """
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ session_id = "OVERLOAD_FRESH_BIND"
+ db.create_session(session_id, source="telegram")
+ msgs = self._msgs(12)
+
+ first = self._compressor(abort_on_summary_failure=False)
+ first.bind_session_state(db, session_id)
+ with patch("agent.context_compressor.call_llm", side_effect=self._err()):
+ for _ in range(2): # exactly two aborts — one below the escalation threshold
+ assert first.compress(msgs, current_tokens=999999, force=True) == msgs
+ assert first._consecutive_overload_aborts == 2
+ assert db.get_compression_overload_streak(session_id) == 2
+
+ # Fresh agent, same session (eviction / restart / API-server request construction).
+ second = self._compressor(abort_on_summary_failure=False)
+ second.bind_session_state(db, session_id)
+ assert second._consecutive_overload_aborts == 2 # inherited, not restarted
+ with patch("agent.context_compressor.call_llm", side_effect=self._err()):
+ third = second.compress(msgs, current_tokens=999999, force=True)
+ # Third consecutive abort IN THE SESSION escalates even though this object saw one.
+ # (A fresh object's first overload may burn the aux→main one-shot retry first, which
+ # claims telemetry failure_class=aux_model_fallback; the escalation contract is the
+ # committed fallback + settled budget, not which telemetry label won the race.)
+ assert third != msgs
+ assert second._last_summary_fallback_used is True
+ assert second._last_summary_overload_degraded is True
+ # The committed degraded fallback settles the budget so recovery gets a fresh run
+ # (the boundary caller records the completed compaction, as compress_context does).
+ second.record_completed_compaction(used_fallback=True)
+ assert db.get_compression_overload_streak(session_id) == 0
+
+ def test_overload_budget_follows_compression_rotation_to_the_child_row(self, tmp_path):
+ """A mid-outage compression rotation must not restart the budget either."""
+ from hermes_state import SessionDB
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ parent, child = "OVERLOAD_ROT_PARENT", "OVERLOAD_ROT_CHILD"
+ db.create_session(parent, source="telegram")
+
+ compressor = self._compressor(abort_on_summary_failure=False)
+ compressor.bind_session_state(db, parent)
+ with patch("agent.context_compressor.call_llm", side_effect=self._err()):
+ for _ in range(2):
+ assert compressor.compress(self._msgs(12), current_tokens=999999, force=True) == self._msgs(12)
+ assert db.get_compression_overload_streak(parent) == 2
+
+ db.create_session(child, source="telegram", parent_session_id=parent)
+ compressor.on_session_start(
+ child, session_db=db, boundary_reason="compression", old_session_id=parent,
+ )
+ assert compressor._consecutive_overload_aborts == 2
+ assert db.get_compression_overload_streak(child) == 2
+
def _msgs(self, n=10):
return [
{"role": "user" if i % 2 == 0 else "assistant", "content": f"msg {i}"}