The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): tell an unreadable session-ownership lookup from a lost one
mnajafian-nv490f4e439717
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex 32bd96da68a..00eee132049 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -2847,12 +2847,13 @@ def _acquire_compression_lease(def _adopt_if_parent_rotated(- agent: Any, lease: _CompressionLease, messages: list, system_message: str+ agent: Any, lease: _CompressionLease, messages: list, system_message: str, *, started_at: float,+ approx_tokens: Optional[int],) -> Optional[tuple[list, str]]:"""Sit out (or adopt the live child) when the parent was already rotated.A late contender can take the parent lock after the winner released it and rotated; holding the lock doesnot prove this agent still owns a live parent. Returns the ``compress_context`` result to hand back, or- None to proceed."""+ None to proceed. Each returning exit logs its own attempt record."""if lease.db is None or not lease.sid:return Nonetry:@@ -2863,11 +2864,18 @@ def _adopt_if_parent_rotated(lease.sid, type(_session_err).__name__, _session_err,)lease.release()+ _emit_bypassed_attempt_telemetry(+ agent, started_at, commit_status="aborted", failure_class="session_ownership_unreadable",+ approx_tokens=approx_tokens,+ )return messages, _existing_system_prompt(agent, system_message)if not _parent_already_rotated:return Nonerecovered_messages = _adopt_live_compression_child(agent, lease.db, lease.sid)lease.release()+ _emit_bypassed_attempt_telemetry(+ agent, started_at, commit_status="skipped", failure_class="session_ownership_lost", approx_tokens=approx_tokens,+ )_existing_sp = _existing_system_prompt(agent, system_message)if recovered_messages is not None:logger.warning("compression recovery: stale session=%s adopted live child=%s", lease.sid, agent.session_id)@@ -4192,12 +4200,10 @@ def compress_context(_emit_aborted_attempt_telemetry(agent, attempt.started_at, "snapshot_stale")lease.release()return messages, _existing_system_prompt(agent, system_message)- _adopted = _adopt_if_parent_rotated(agent, lease, messages, system_message)+ _adopted = _adopt_if_parent_rotated(+ agent, lease, messages, system_message, started_at=attempt.started_at, approx_tokens=approx_tokens,+ )if _adopted is not None:- _emit_bypassed_attempt_telemetry(- agent, attempt.started_at, commit_status="skipped", failure_class="session_ownership_lost",- approx_tokens=approx_tokens,- )return _adopted# Snapshot durable cooldown only once we own the lease. Runs for force=Truediff --git a/tests/agent/test_compression_attempt_effect.py b/tests/agent/test_compression_attempt_effect.pyindex 52b1e941bf3..d0bd8ce44fb 100644--- a/tests/agent/test_compression_attempt_effect.py+++ b/tests/agent/test_compression_attempt_effect.py@@ -277,3 +277,39 @@ def test_aborted_record_after_a_commit_describes_its_own_attempt(caplog, abort,assert aborted["method"] == "none" and not aborted["fallback_used"]assert [aborted.get(key) for key in ("tokens_before", "tokens_after", "tokens_reclaimed")] == [None] * 3++def _adopt_child(agent, _db, _parent_sid):+ agent.session_id = "adopted-child"+ return [{"role": "user", "content": "child transcript"}]+++def _unreadable_ownership(_db, _sid):+ raise OSError("database is locked")+++ ("ownership_patch", "expected"),+ [+ # The lease found the parent already rotated and adopted the live child.+ ({"_session_was_rotated_by_compression": lambda _db, _sid: True, "_adopt_live_compression_child": _adopt_child},+ ("skipped", "session_ownership_lost")),+ # The ownership lookup itself failed: ownership is unknown, not lost.+ ({"_session_was_rotated_by_compression": _unreadable_ownership}, ("aborted", "session_ownership_unreadable")),+ ],+)+def test_ownership_exit_records_the_session_the_attempt_ran_in(caplog, tmp_path, ownership_patch, expected):+ from hermes_state import SessionDB++ agent = _Agent(_compressor())+ agent._session_db = SessionDB(db_path=tmp_path / "state.db")+ agent._session_db.create_session(agent.session_id, "cli", model="test/main-model")++ with patch.multiple("agent.conversation_compression", **ownership_patch), \+ patch.object(agent.context_compressor, "_generate_summary") as summary:+ with caplog.at_level(logging.INFO, logger="agent.conversation_compression"):+ compress_context(agent, _messages(), "system prompt", approx_tokens=80_000, trigger="post_tool")++ summary.assert_not_called()+ [record] = _attempt_records(caplog)+ assert (record["commit_status"], record["failure_class"]) == expected+ assert (record["session_id"], record["trigger_source"]) == ("session-effect-test", "post_tool")diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex de113ba028e..02cc207ed04 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -243,11 +243,14 @@ text, the focus topic or error messages.- `commit_status` is `committed`, `aborted`, `failed`, `skipped` or `blocked`.A `blocked` attempt was refused by an automatic guard; its `failure_class`names the guard (`blocked:cooldown`, `blocked:structural_backoff`,- `blocked:ineffective`).+ `blocked:ineffective`). Under the session lease, `session_ownership_lost`+ (`skipped`) means another path already rotated the session, and+ `session_ownership_unreadable` / `cooldown_state_unreadable` (`aborted`)+ mean that state could not be read.- `attempt_id` names this attempt and `session_id` the session it started- in. An attempt that stops before the compressor runs, or rolls its state- back, logs `method: none` and no token counts, never an earlier attempt's- numbers.+ in, even when the attempt then adopts a rotated child session. An attempt+ that stops before the compressor runs, or rolls its state back, logs+ `method: none` and no token counts, never an earlier attempt's numbers.- `method` says how the summary was produced: `llm_summary`,`aux_fallback_main` (the summary model failed and the main model wrote it),`deterministic_fallback` (static anchors summary; `items_dropped` counts the