-
Notifications
You must be signed in to change notification settings - Fork 47.3k
feat(mem): add config-driven allocator trim #63708
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aider4ryder
wants to merge
1
commit into
NousResearch:main
Choose a base branch
from
aider4ryder:fix/memory-trim-config
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """Rate-limited heap release for long-lived Hermes gateway processes. | ||
|
|
||
| On Linux/glibc, ``malloc_trim(0)`` can return pages from freed Python/C | ||
| allocations to the OS. Other platforms and allocators are safe no-ops. | ||
| Behavior is configured under ``context.memory_trim`` in ``config.yaml``. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ctypes | ||
| import gc | ||
| import logging | ||
| import platform | ||
| import sys | ||
| import threading | ||
| import time | ||
| from collections.abc import Callable | ||
| from typing import Any | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| _DEFAULT_COOLDOWN_SECONDS = 60.0 | ||
| _trim_lock = threading.Lock() | ||
| _last_trim_monotonic = 0.0 | ||
| _probe_done = False | ||
| _malloc_trim: Callable[[int], int] | None = None | ||
|
|
||
|
|
||
| def _config_settings() -> tuple[bool, float]: | ||
| """Return fail-open settings from the normal Hermes config path.""" | ||
| enabled = True | ||
| cooldown: Any = _DEFAULT_COOLDOWN_SECONDS | ||
| try: | ||
| from hermes_cli.config import load_config | ||
|
|
||
| config = load_config() or {} | ||
| context = config.get("context") if isinstance(config, dict) else None | ||
| settings = context.get("memory_trim") if isinstance(context, dict) else None | ||
| if isinstance(settings, dict): | ||
| configured_enabled = settings.get("enabled") | ||
| if isinstance(configured_enabled, bool): | ||
| enabled = configured_enabled | ||
| cooldown = settings.get("cooldown_seconds", _DEFAULT_COOLDOWN_SECONDS) | ||
| except Exception: | ||
| pass | ||
| return enabled, _cooldown_seconds(cooldown) | ||
|
|
||
|
|
||
| def _cooldown_seconds(value: Any) -> float: | ||
| if isinstance(value, bool): | ||
| return _DEFAULT_COOLDOWN_SECONDS | ||
| try: | ||
| return max(0.0, float(value)) | ||
| except (TypeError, ValueError): | ||
| return _DEFAULT_COOLDOWN_SECONDS | ||
|
|
||
|
|
||
| def _probe_glibc_malloc_trim() -> Callable[[int], int] | None: | ||
| """Resolve glibc's malloc_trim once; return None on unsupported systems.""" | ||
| global _malloc_trim, _probe_done | ||
| if _probe_done: | ||
| return _malloc_trim | ||
| _probe_done = True | ||
| if sys.platform != "linux": | ||
| return None | ||
| try: | ||
| if platform.libc_ver()[0].lower() != "glibc": | ||
| return None | ||
| libc = ctypes.CDLL(None) | ||
| trim = libc.malloc_trim | ||
| trim.argtypes = [ctypes.c_size_t] | ||
| trim.restype = ctypes.c_int | ||
| _malloc_trim = trim | ||
| except Exception as exc: | ||
| logger.debug("malloc_trim unavailable: %s", exc) | ||
| return _malloc_trim | ||
|
|
||
|
|
||
| def trim_memory( | ||
| *, | ||
| force: bool = False, | ||
| reason: str = "", | ||
| cooldown_seconds: float | None = None, | ||
| ) -> bool: | ||
| """Collect cycles and ask glibc to release free heap pages. | ||
|
|
||
| Returns ``True`` only when ``malloc_trim(0)`` ran and reported success. | ||
| Unsupported allocators, the config kill switch, cooldown suppression, and all | ||
| runtime errors return ``False`` without affecting the caller. | ||
| """ | ||
| enabled, configured_cooldown = _config_settings() | ||
| if not enabled: | ||
| return False | ||
|
|
||
| global _last_trim_monotonic | ||
| with _trim_lock: | ||
| trim = _probe_glibc_malloc_trim() | ||
| if trim is None: | ||
| return False | ||
| now = time.monotonic() | ||
| cooldown = ( | ||
| configured_cooldown | ||
| if cooldown_seconds is None | ||
| else _cooldown_seconds(cooldown_seconds) | ||
| ) | ||
| if not force and _last_trim_monotonic and now - _last_trim_monotonic < cooldown: | ||
| return False | ||
| # Record the attempt before calling into libc so repeated failures do not | ||
| # turn every turn boundary into an expensive full collection. | ||
| _last_trim_monotonic = now | ||
| try: | ||
| gc.collect() | ||
| released = bool(trim(0)) | ||
| if reason: | ||
| logger.debug("malloc_trim(0) after %s: released=%s", reason, released) | ||
| return released | ||
| except Exception as exc: | ||
| logger.debug("malloc_trim failed after %s: %s", reason or "cleanup", exc) | ||
| return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| """Tests for the long-lived gateway heap-trim helper.""" | ||
|
|
||
| from unittest.mock import Mock | ||
|
|
||
| import pytest | ||
|
|
||
| import hermes_cli.mem_trim as mem_trim | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def _reset_trim_state(monkeypatch): | ||
| monkeypatch.setattr(mem_trim, "_last_trim_monotonic", 0.0) | ||
| monkeypatch.setattr(mem_trim, "_probe_done", True) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", None) | ||
|
|
||
|
|
||
| def test_unsupported_allocator_is_noop_without_gc(monkeypatch): | ||
| collect = Mock() | ||
| monkeypatch.setattr(mem_trim.gc, "collect", collect) | ||
|
|
||
| assert mem_trim.trim_memory(force=True, reason="test") is False | ||
| collect.assert_not_called() | ||
|
|
||
|
|
||
| def test_config_kill_switch_overrides_force(monkeypatch): | ||
| trim = Mock(return_value=1) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", trim) | ||
| monkeypatch.setattr( | ||
| "hermes_cli.config.load_config", | ||
| lambda: {"context": {"memory_trim": {"enabled": False}}}, | ||
| ) | ||
|
|
||
| assert mem_trim.trim_memory(force=True) is False | ||
| trim.assert_not_called() | ||
|
|
||
|
|
||
| def test_default_config_declares_memory_trim_controls(): | ||
| from hermes_cli.config import DEFAULT_CONFIG | ||
|
|
||
| context = DEFAULT_CONFIG["context"] | ||
| assert isinstance(context, dict) | ||
| assert context["memory_trim"] == { | ||
| "enabled": True, | ||
| "cooldown_seconds": 60.0, | ||
| } | ||
|
|
||
|
|
||
| def test_success_collects_then_trims(monkeypatch): | ||
| calls = [] | ||
| monkeypatch.setattr(mem_trim.gc, "collect", lambda: calls.append("gc")) | ||
| monkeypatch.setattr( | ||
| mem_trim, "_malloc_trim", lambda pad: calls.append(("trim", pad)) or 1 | ||
| ) | ||
| monkeypatch.setattr(mem_trim.time, "monotonic", lambda: 100.0) | ||
|
|
||
| assert mem_trim.trim_memory(reason="turn", cooldown_seconds=60) is True | ||
| assert calls == ["gc", ("trim", 0)] | ||
| assert mem_trim._last_trim_monotonic == 100.0 | ||
|
|
||
|
|
||
| def test_cooldown_suppresses_repeated_collection(monkeypatch): | ||
| collect = Mock() | ||
| trim = Mock(return_value=1) | ||
| monkeypatch.setattr(mem_trim.gc, "collect", collect) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", trim) | ||
| monkeypatch.setattr(mem_trim, "_last_trim_monotonic", 95.0) | ||
| monkeypatch.setattr(mem_trim.time, "monotonic", lambda: 100.0) | ||
|
|
||
| assert mem_trim.trim_memory(cooldown_seconds=60) is False | ||
| collect.assert_not_called() | ||
| trim.assert_not_called() | ||
| assert mem_trim.trim_memory(force=True, cooldown_seconds=60) is True | ||
|
|
||
|
|
||
| def test_config_cooldown_controls_rate_limit(monkeypatch): | ||
| trim = Mock(return_value=1) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", trim) | ||
| monkeypatch.setattr(mem_trim, "_last_trim_monotonic", 1.0) | ||
| monkeypatch.setattr(mem_trim.time, "monotonic", lambda: 100.0) | ||
| monkeypatch.setattr( | ||
| "hermes_cli.config.load_config", | ||
| lambda: { | ||
| "context": { | ||
| "memory_trim": {"enabled": True, "cooldown_seconds": 120.0} | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| assert mem_trim.trim_memory() is False | ||
| trim.assert_not_called() | ||
|
|
||
|
|
||
| def test_legacy_environment_switch_does_not_control_behavior(monkeypatch): | ||
| trim = Mock(return_value=1) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", trim) | ||
| monkeypatch.setenv("HERMES_DISABLE_MEMORY_TRIM", "1") | ||
| monkeypatch.setattr( | ||
| "hermes_cli.config.load_config", | ||
| lambda: {"context": {"memory_trim": {"enabled": True}}}, | ||
| ) | ||
|
|
||
| assert mem_trim.trim_memory(force=True) is True | ||
| trim.assert_called_once_with(0) | ||
|
|
||
|
|
||
| def test_libc_failure_is_fail_open_and_rate_limited(monkeypatch): | ||
| trim = Mock(side_effect=RuntimeError("boom")) | ||
| monkeypatch.setattr(mem_trim, "_malloc_trim", trim) | ||
| monkeypatch.setattr(mem_trim.time, "monotonic", lambda: 100.0) | ||
|
|
||
| assert mem_trim.trim_memory(reason="test", cooldown_seconds=60) is False | ||
| assert mem_trim._last_trim_monotonic == 100.0 | ||
| assert mem_trim.trim_memory(cooldown_seconds=60) is False | ||
| assert trim.call_count == 1 | ||
|
|
||
|
|
||
| def test_agent_close_forces_memory_trim(monkeypatch): | ||
| """A hard agent teardown bypasses cooldown after releasing its history.""" | ||
| from run_agent import AIAgent | ||
|
|
||
| trim = Mock() | ||
| monkeypatch.setattr(mem_trim, "trim_memory", trim) | ||
| agent = AIAgent.__new__(AIAgent) | ||
|
|
||
| agent.close() | ||
|
|
||
| trim.assert_called_once_with(force=True, reason="agent close") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This resolves config at close time, but
AIAgenthas no profile-home input.tui_gateway/server.py:_teardown_sessioncallsagent.close()after the per-turn override has been reset, so a resumed profile that disables trimming can consult the default profile config. Move the decision into a profile-scoped caller (or carry profile/config state on the agent) and add a profile-isolation regression.