Skip to content

The agent that grows with you

fix(hardware): use MemAvailable for Linux RAM

brooklyn!687ca6ed88f7
diff --git a/hermes_cli/local_runtime/hardware.py b/hermes_cli/local_runtime/hardware.py
index 0f8e2c1ce38..e35d6a8f620 100644
--- a/hermes_cli/local_runtime/hardware.py
+++ b/hermes_cli/local_runtime/hardware.py
@@ -61,6 +61,52 @@ def _stdout(*argv: str) -> str:
).stdout
+_LINUX_RAM_KEYS = frozenset({"MemTotal", "MemAvailable", "MemFree"})
+
+
+def _linux_meminfo_text() -> str | None:
+ """Raw /proc/meminfo, or None when procfs cannot be read."""
+ try:
+ return Path("/proc/meminfo").read_text(encoding="utf-8")
+ except OSError:
+ return None
+
+
+def _linux_ram_from_meminfo(text: str) -> tuple[int, int] | None:
+ """(total, available) from meminfo text, or None if it cannot be trusted.
+
+ MemAvailable includes reclaimable page cache, which ``getconf _AVPHYS_PAGES``
+ counts as used. Kernels that omit MemAvailable fall back to MemFree. Zero is
+ a real available value — a missing-field check must not treat it as absent.
+ """
+ fields: dict[str, int] = {}
+ try:
+ for line in text.splitlines():
+ name, separator, value = line.partition(":")
+ if not separator or name not in _LINUX_RAM_KEYS:
+ continue
+ parts = value.split()
+ if len(parts) != 2 or parts[1] != "kB":
+ continue
+ fields[name] = int(parts[0]) * 1024
+ total = fields.get("MemTotal")
+ # Key presence, not truthiness: MemAvailable 0 must not fall through to MemFree.
+ if "MemAvailable" in fields:
+ available = fields["MemAvailable"]
+ else:
+ available = fields.get("MemFree")
+ if (
+ total is None
+ or total <= 0
+ or available is None
+ or not 0 <= available <= total
+ ):
+ return None
+ return total, available
+ except (AttributeError, TypeError, ValueError):
+ return None
+
+
def _ram_bytes() -> tuple[int, int]:
"""(total, available) physical memory, cross-platform stdlib."""
try:
@@ -98,6 +144,12 @@ def _ram_bytes() -> tuple[int, int]:
if pages > 0:
avail = pages * page
return total, avail
+ if sys.platform.startswith("linux"):
+ meminfo = _linux_meminfo_text()
+ if meminfo is not None:
+ linux_ram = _linux_ram_from_meminfo(meminfo)
+ if linux_ram is not None:
+ return linux_ram
# POSIX
page = int(_stdout("getconf", "PAGE_SIZE") or 4096)
total = int(_stdout("getconf", "_PHYS_PAGES") or 0) * page
diff --git a/tests/hermes_cli/test_linux_ram_probe.py b/tests/hermes_cli/test_linux_ram_probe.py
new file mode 100644
index 00000000000..eb4250fc5c1
--- /dev/null
+++ b/tests/hermes_cli/test_linux_ram_probe.py
@@ -0,0 +1,107 @@
+"""Linux RAM availability must include reclaimable page cache (#102252).
+
+``getconf _AVPHYS_PAGES`` counts only free pages, so the Desktop statusbar
+treats page cache as used. ``MemAvailable`` is the reclaimable-aware figure.
+A reported ``0`` is a real available value, not a missing field.
+"""
+
+from __future__ import annotations
+
+import ctypes
+
+import hermes_cli.local_runtime.hardware as hw
+
+GIB = 1 << 30
+
+
+def _as_linux(monkeypatch) -> None:
+ """Reach the Linux branch on every host without editing the Windows probe."""
+ monkeypatch.delattr(ctypes, "windll", raising=False)
+ monkeypatch.setattr(hw.sys, "platform", "linux")
+
+
+def test_memavailable_is_used_when_present():
+ text = (
+ "MemTotal: 67108864 kB\n"
+ "MemFree: 12582912 kB\n"
+ "MemAvailable: 56623104 kB\n"
+ "Cached: 44040192 kB\n"
+ )
+
+ assert hw._linux_ram_from_meminfo(text) == (64 * GIB, 54 * GIB)
+
+
+def test_zero_memavailable_is_a_real_value():
+ text = (
+ "MemTotal: 8388608 kB\n"
+ "MemFree: 2097152 kB\n"
+ "MemAvailable: 0 kB\n"
+ )
+
+ assert hw._linux_ram_from_meminfo(text) == (8 * GIB, 0)
+
+
+def test_missing_memavailable_falls_back_to_memfree():
+ text = "MemTotal: 8388608 kB\nMemFree: 2097152 kB\n"
+
+ assert hw._linux_ram_from_meminfo(text) == (8 * GIB, 2 * GIB)
+
+
+def test_unusable_meminfo_is_not_a_reading():
+ assert hw._linux_ram_from_meminfo("MemAvailable: 1048576 kB\n") is None
+ assert hw._linux_ram_from_meminfo(
+ "MemTotal: 1048576 kB\nMemAvailable: 2097152 kB\n"
+ ) is None
+
+
+def test_ram_bytes_uses_injected_meminfo_including_zero(monkeypatch):
+ _as_linux(monkeypatch)
+ monkeypatch.setattr(
+ hw,
+ "_linux_meminfo_text",
+ lambda: (
+ "MemTotal: 8388608 kB\n"
+ "MemFree: 2097152 kB\n"
+ "MemAvailable: 0 kB\n"
+ ),
+ )
+
+ def _getconf_must_not_run(*_args, **_kwargs):
+ raise AssertionError("getconf must not run when MemAvailable is present")
+
+ monkeypatch.setattr(hw, "_stdout", _getconf_must_not_run)
+
+ assert hw._ram_bytes() == (8 * GIB, 0)
+
+
+def test_ram_bytes_falls_back_when_memavailable_is_absent(monkeypatch):
+ _as_linux(monkeypatch)
+ monkeypatch.setattr(
+ hw,
+ "_linux_meminfo_text",
+ lambda: "MemTotal: 8388608 kB\nMemFree: 2097152 kB\n",
+ )
+
+ def _getconf_must_not_run(*_args, **_kwargs):
+ raise AssertionError("MemFree is a valid fallback; getconf must not run")
+
+ monkeypatch.setattr(hw, "_stdout", _getconf_must_not_run)
+
+ assert hw._ram_bytes() == (8 * GIB, 2 * GIB)
+
+
+def test_ram_bytes_falls_back_to_getconf_when_meminfo_unusable(monkeypatch):
+ _as_linux(monkeypatch)
+ monkeypatch.setattr(hw, "_linux_meminfo_text", lambda: None)
+ values = {
+ "PAGE_SIZE": "4096\n",
+ "_PHYS_PAGES": "2097152\n",
+ "_AVPHYS_PAGES": "524288\n",
+ }
+
+ def fake_stdout(*argv):
+ return values[argv[-1]]
+
+ monkeypatch.setattr(hw, "_stdout", fake_stdout)
+
+ assert hw._ram_bytes() == (8 * GIB, 2 * GIB)