Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions contributors/emails/alex@odbo.co
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
alex107ivanov
# PR #71463
80 changes: 80 additions & 0 deletions plugins/memory/honcho/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import re
import logging
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, TYPE_CHECKING
Expand All @@ -23,6 +24,26 @@
_PEER_ID_HASH_LEN = 8
_PEER_ID_HASH_ESCALATION_LENGTHS = (_PEER_ID_HASH_LEN, 12, 16, 24, 32, 64)

# HonchoSession.messages is a local cache of a session Honcho already
# persists durably -- get_or_create() re-hydrates it from Honcho on a
# cache miss (see `existing_messages` below). Nothing here is the sole
# copy of anything, so both of these bounds are safe to enforce:
#
# - _SESSION_MESSAGE_RETENTION caps how many already-synced messages a
# live HonchoSession keeps locally. get_history() only ever reads a
# small recent window (default 50), so retaining unbounded history
# past that serves no purpose and grows without limit for any
# session that outlives a handful of turns.
# - _SESSION_IDLE_TTL_SECONDS / _SESSION_SWEEP_INTERVAL_SECONDS bound how
# long an idle session (and its peer/session/context cache entries) is
# kept in HonchoSessionManager's process-lifetime dicts, which
# otherwise have no eviction path short of an explicit /new reset.
# Eviction just costs one extra Honcho round-trip next time that key
# is used.
_SESSION_MESSAGE_RETENTION = 200
_SESSION_IDLE_TTL_SECONDS = 3600
_SESSION_SWEEP_INTERVAL_SECONDS = 300


@dataclass
class HonchoSession:
Expand Down Expand Up @@ -104,6 +125,7 @@ def __init__(
self._cache_lock = threading.RLock()
self._peers_cache: dict[str, Any] = {}
self._sessions_cache: dict[str, Any] = {}
self._last_idle_sweep_ts: float = 0.0

# Write frequency state
write_frequency = (config.write_frequency if config else "async")
Expand Down Expand Up @@ -360,6 +382,44 @@ def _resolve_user_peer_id(self, key: str) -> str:

return self._session_key_fallback_peer_id(key)

def _sweep_idle_sessions_locked(self) -> int:
"""Evict local cache entries idle beyond ``_SESSION_IDLE_TTL_SECONDS``.

Honcho is the source of truth for message history -- ``get_or_create``
re-fetches from Honcho on a cache miss -- so dropping an idle local
entry never loses data, it only costs one extra Honcho round-trip the
next time that session key is used. Must be called with
``_cache_lock`` held.
"""
cutoff = time.time() - _SESSION_IDLE_TTL_SECONDS
evicted = 0
for key, session in list(self._cache.items()):
if session.updated_at.timestamp() >= cutoff:
continue
del self._cache[key]
self._sessions_cache.pop(session.honcho_session_id, None)
self._context_cache.pop(key, None)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_context_cache is otherwise accessed under _prefetch_cache_lock (set_context_result() and pop_context_result() on main). Please acquire that lock for this removal as well; a background prefetch can otherwise race an idle sweep and repopulate stale context after eviction.

evicted += 1
return evicted

def _maybe_sweep_idle_sessions(self) -> None:
"""Rate-limited idle-session sweep, triggered opportunistically.

Called from ``get_or_create`` on every lookup rather than from a
dedicated background task, so this manager stays usable from both
the gateway's event loop and the plain-CLI path without any watcher
wiring. ``_SESSION_SWEEP_INTERVAL_SECONDS`` keeps the actual sweep
(an O(len(_cache)) scan) rare relative to lookup volume.
"""
now = time.time()
with self._cache_lock:
if now - self._last_idle_sweep_ts < _SESSION_SWEEP_INTERVAL_SECONDS:
return
self._last_idle_sweep_ts = now
evicted = self._sweep_idle_sessions_locked()
if evicted:
logger.info("Honcho session cache idle sweep: evicted %d session(s)", evicted)

def get_or_create(self, key: str) -> HonchoSession:
"""
Get an existing session or create a new one.
Expand All @@ -370,6 +430,8 @@ def get_or_create(self, key: str) -> HonchoSession:
Returns:
The session.
"""
self._maybe_sweep_idle_sessions()

with self._cache_lock:
if key in self._cache:
logger.debug("Local session cache hit: %s", key)
Expand Down Expand Up @@ -419,6 +481,23 @@ def get_or_create(self, key: str) -> HonchoSession:
self._cache[key] = session
return session

@staticmethod
def _trim_synced_messages(session: HonchoSession) -> None:
"""Drop already-synced messages beyond ``_SESSION_MESSAGE_RETENTION``.

``session.messages`` is chronologically ordered and only ever
appended to, so synced entries are always the oldest ones; trimming
from the front until back within the cap (or hitting an unsynced
message) preserves order and never touches a message that hasn't
made it to Honcho yet. Called right after a successful flush, so the
excess trimmed per call is small -- the O(n) ``pop(0)`` cost stays
negligible in practice.
"""
excess = len(session.messages) - _SESSION_MESSAGE_RETENTION
while excess > 0 and session.messages and session.messages[0].get("_synced"):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This stops at the first unsynced item, so it does not enforce the advertised retention bound: the added test's unsynced item at index 10 leaves 290 entries. Please define and test the intended persistent-sync-failure policy, or narrow the bound claim to histories that have successfully flushed.

session.messages.pop(0)
excess -= 1

def _flush_session(self, session: HonchoSession) -> bool:
"""Internal: write unsynced messages to Honcho synchronously."""
if not session.messages:
Expand Down Expand Up @@ -447,6 +526,7 @@ def _flush_session(self, session: HonchoSession) -> bool:
for msg in new_messages:
msg["_synced"] = True
logger.debug("Synced %d messages to Honcho for %s", len(honcho_messages), session.key)
self._trim_synced_messages(session)
with self._cache_lock:
self._cache[session.key] = session
return True
Expand Down
157 changes: 157 additions & 0 deletions tests/test_honcho_session_cache_bounds.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
"""Regression tests for bounded growth of the Honcho local session cache.

Covers the fix for unbounded RSS growth in long-running gateways: prior to
this, ``HonchoSession.messages`` grew forever (never trimmed after a sync),
and ``HonchoSessionManager``'s ``_cache``/``_sessions_cache``/``_context_cache``
had no eviction path short of an explicit ``/new`` reset.
"""

import threading
import time
from datetime import datetime, timedelta
from types import SimpleNamespace

from plugins.memory.honcho.session import (
HonchoSession,
HonchoSessionManager,
_SESSION_IDLE_TTL_SECONDS,
_SESSION_MESSAGE_RETENTION,
)


def _session(key="k", honcho_session_id=None):
return HonchoSession(
key=key,
user_peer_id="user",
assistant_peer_id="assistant",
honcho_session_id=honcho_session_id or f"hs-{key}",
)


def _manager():
cfg = SimpleNamespace(
write_frequency="turn",
dialectic_reasoning_level="low",
dialectic_dynamic=True,
dialectic_max_chars=600,
observation_mode="directional",
user_observe_me=True,
user_observe_others=True,
ai_observe_me=True,
ai_observe_others=True,
message_max_chars=25000,
dialectic_max_input_chars=10000,
)
return HonchoSessionManager(honcho=SimpleNamespace(), config=cfg)


def test_trim_synced_messages_caps_total_length():
session = _session()
for i in range(250):
session.add_message("user", f"msg{i}", _synced=True)
for i in range(250, 255):
session.add_message("user", f"msg{i}", _synced=False)
assert len(session.messages) == 255

HonchoSessionManager._trim_synced_messages(session)

assert len(session.messages) == _SESSION_MESSAGE_RETENTION
# oldest synced messages are the ones dropped; the unsynced tail survives intact
assert not any(m.get("_synced") is False for m in session.messages[:-5])
assert all(m.get("_synced") is False for m in session.messages[-5:])


def test_trim_synced_messages_never_drops_an_unsynced_message():
session = _session()
for i in range(300):
session.add_message("user", f"m{i}", _synced=(i != 10))

HonchoSessionManager._trim_synced_messages(session)

contents = [m["content"] for m in session.messages]
assert "m10" in contents
idx = contents.index("m10")
assert session.messages[idx].get("_synced") is False
# trimming stops at the first unsynced message from the front — it does
# not skip past it to keep reducing, so everything from there on survives
assert contents[idx:] == [f"m{i}" for i in range(10, 300)]


def test_trim_synced_messages_is_a_noop_under_the_cap():
session = _session()
for i in range(10):
session.add_message("user", f"m{i}", _synced=True)

HonchoSessionManager._trim_synced_messages(session)

assert len(session.messages) == 10


def test_sweep_idle_sessions_evicts_stale_entries_across_all_caches():
mgr = _manager()
stale = _session(key="stale", honcho_session_id="hs-stale")
stale.updated_at = datetime.now() - timedelta(seconds=_SESSION_IDLE_TTL_SECONDS + 1)
fresh = _session(key="fresh", honcho_session_id="hs-fresh")

mgr._cache = {"stale": stale, "fresh": fresh}
mgr._sessions_cache = {"hs-stale": object(), "hs-fresh": object()}
mgr._context_cache = {"stale": {"x": 1}, "fresh": {"x": 1}}

evicted = mgr._sweep_idle_sessions_locked()

assert evicted == 1
assert set(mgr._cache) == {"fresh"}
assert set(mgr._sessions_cache) == {"hs-fresh"}
assert set(mgr._context_cache) == {"fresh"}


def test_sweep_idle_sessions_keeps_fresh_entries():
mgr = _manager()
fresh = _session(key="fresh")
mgr._cache = {"fresh": fresh}
mgr._sessions_cache = {fresh.honcho_session_id: object()}
mgr._context_cache = {"fresh": {}}

evicted = mgr._sweep_idle_sessions_locked()

assert evicted == 0
assert "fresh" in mgr._cache


def test_maybe_sweep_idle_sessions_is_rate_limited():
mgr = _manager()
stale = _session(key="stale")
stale.updated_at = datetime.now() - timedelta(seconds=_SESSION_IDLE_TTL_SECONDS + 1)
mgr._cache = {"stale": stale}

mgr._last_idle_sweep_ts = time.time() # just swept — this call should no-op
mgr._maybe_sweep_idle_sessions()
assert "stale" in mgr._cache

mgr._last_idle_sweep_ts = 0.0 # force the interval to have elapsed
mgr._maybe_sweep_idle_sessions()
assert "stale" not in mgr._cache


def test_get_or_create_triggers_sweep_without_blocking_on_lock_reentrancy():
"""`_cache_lock` is an RLock specifically so a sweep triggered from inside
`get_or_create` (which also takes the lock) can't deadlock the manager's
own thread. Guard against that regressing silently.
"""
mgr = _manager()
stale = _session(key="stale")
stale.updated_at = datetime.now() - timedelta(seconds=_SESSION_IDLE_TTL_SECONDS + 1)
mgr._cache = {"stale": stale}
mgr._last_idle_sweep_ts = 0.0

done = threading.Event()

def call_it():
mgr._maybe_sweep_idle_sessions()
done.set()

t = threading.Thread(target=call_it)
t.start()
t.join(timeout=5)
assert done.is_set(), "sweep did not complete — possible deadlock"
assert "stale" not in mgr._cache
Loading