The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(agent): a closed agent's message bodies leave the token-estimate memo
kshitijk4poor1b6877e2aaaa
diff --git a/agent/model_metadata_token_memo.py b/agent/model_metadata_token_memo.pynew file mode 100644index 00000000000..24e328d752f--- /dev/null+++ b/agent/model_metadata_token_memo.py@@ -0,0 +1,36 @@+"""Release a closed conversation's entries from the per-message token-estimate memo.++``agent.model_metadata._MSG_TOKENS_CACHE`` pins every string it fingerprints (the pin keeps the ``id()``+key sound), so a long-lived process kept each closed session's message bodies resident until 4096 newer+messages pushed them out.+"""++from __future__ import annotations++from typing import Any+++def forget_message_token_memo(messages: Any) -> int:+ """Evict memo entries pinning any long string value of ``messages``; return how many.++ Eviction never changes an estimate: a later lookup recomputes the same value.+ """+ from agent.model_metadata import _MSG_TOKENS_CACHE++ owned: set[int] = set()+ stack = [messages]+ while stack:+ value = stack.pop()+ if type(value) is dict:+ stack.extend(value.values())+ elif type(value) is list or type(value) is tuple:+ stack.extend(value)+ elif type(value) is str and len(value) > 64: # short values ("assistant", tool names) are shared+ owned.add(id(value))+ if not owned:+ return 0+ stale = [key for key, (pins, _text, _images) in list(_MSG_TOKENS_CACHE.items())+ if any(id(pin) in owned for pin in pins)]+ for key in stale:+ _MSG_TOKENS_CACHE.pop(key, None)+ return len(stale)diff --git a/run_agent.py b/run_agent.pyindex 86fa471ed1a..d6c409ac0ba 100644--- a/run_agent.py+++ b/run_agent.py@@ -953,6 +953,10 @@ class AIAgent(self._session_messages = []self._db_flush_scan_prefix = Noneself._streamed_assistant_text_parts = []+ if isinstance(session_messages, list):+ # The token-estimate memo pins message strings; a closed conversation's can never hit again.+ from agent.model_metadata_token_memo import forget_message_token_memo+ _quietly(forget_message_token_memo, session_messages)_quietly(self._trim_process_memory)_quietly(self._finalize_owned_session_row)diff --git a/tests/agent/test_token_memo_release_on_close.py b/tests/agent/test_token_memo_release_on_close.pynew file mode 100644index 00000000000..d7c984e3ee5--- /dev/null+++ b/tests/agent/test_token_memo_release_on_close.py@@ -0,0 +1,44 @@+"""A closed agent's message bodies leave the token-estimate memo.++``_MSG_TOKENS_CACHE`` pins every string it fingerprints, so after ``AIAgent.close()`` a long-lived+``hermes serve`` kept each closed session's message bodies resident until 4096 newer messages evicted+them (~50 MB after 20 sessions x 10 turns of 256 KB replies on macOS).+"""++import threading++from agent.model_metadata import _MSG_TOKENS_CACHE, estimate_messages_tokens_rough+from run_agent import AIAgent+++def _pinned_ids() -> set[int]:+ return {id(pin) for pins, _text, _images in _MSG_TOKENS_CACHE.values() for pin in pins}+++def _closing_agent(messages: list) -> AIAgent:+ agent = AIAgent.__new__(AIAgent)+ agent.session_id = "memo-release"+ agent.client = None+ agent._active_children_lock = threading.Lock()+ agent._active_children = set()+ agent._end_session_on_close = False+ agent._session_messages = messages+ return agent+++def test_close_evicts_the_conversations_memo_entries_and_keeps_others():+ reply = "closed-session reply " * 5000+ other = "another live session's reply " * 5000+ closed = [{"role": "user", "content": "hi there, a long enough opening question for the memo key?"},+ {"role": "assistant", "content": reply}]+ live = [{"role": "assistant", "content": other}]+ before = estimate_messages_tokens_rough(closed)+ estimate_messages_tokens_rough(live)+ assert id(reply) in _pinned_ids() and id(other) in _pinned_ids()++ _closing_agent(closed).close()++ assert id(reply) not in _pinned_ids()+ assert id(other) in _pinned_ids()+ # Eviction only drops a pure-function memo: the estimate is unchanged when recomputed.+ assert estimate_messages_tokens_rough(closed) == before