Skip to content

The agent that grows with you

fix(logging): preserve log ownership across a rollover

WYSTAF2ba97b01d432
diff --git a/hermes_logging.py b/hermes_logging.py
index 174a1b25550..2fff2f2d4f7 100644
--- a/hermes_logging.py
+++ b/hermes_logging.py
@@ -17,7 +17,7 @@ import sys
import threading
from logging.handlers import QueueHandler, QueueListener
from pathlib import Path
-from typing import Optional, Sequence
+from typing import Optional, Sequence, Tuple
from hermes_constants import get_config_path, get_hermes_home, mkdir_under_hermes_home
@@ -430,6 +430,35 @@ def _quietly(fn) -> None:
pass
+def _stat_owner(path: str) -> Optional[Tuple[int, int, int]]:
+ """``(uid, gid, mode)`` of *path*, or ``None`` when unavailable (Windows, missing file)."""
+ try:
+ st = os.stat(path)
+ except OSError:
+ return None
+ uid = getattr(st, "st_uid", None)
+ gid = getattr(st, "st_gid", None)
+ if uid is None or gid is None:
+ return None # Windows (and any POSIX without the fields): nothing to preserve
+ return int(uid), int(gid), int(st.st_mode)
+
+
+def _restore_owner(path: str, owner: Tuple[int, int, int]) -> None:
+ """Give *path* back to ``(uid, gid)`` and its recorded mode, best-effort.
+
+ Only root may hand a file to another uid, so this is a no-op for an unprivileged
+ process — which never changed the owner in the first place. An ``OSError`` leaves the
+ default file in place: a log that cannot be chowned is still a working log.
+ """
+ uid, gid, mode = owner
+ try:
+ if hasattr(os, "chown") and hasattr(os, "geteuid") and os.geteuid() == 0:
+ os.chown(path, uid, gid)
+ os.chmod(path, mode & 0o7777)
+ except OSError:
+ pass
+
+
class _ManagedRotatingFileHandler(RotatingFileHandler):
"""RotatingFileHandler with managed-mode perms and external-rotation detection.
@@ -540,7 +569,16 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):
return stream
def doRollover(self):
+ # The stdlib rollover renames baseFilename and opens a fresh one, so the new
+ # file is owned by whichever process wrote the record that crossed maxBytes.
+ # With one rotating handler per profile (#120151), that is usually the long-lived
+ # gateway — so a worker's log can be replaced by a root-owned file the worker can
+ # never reopen, turning a log rotation into a permanent EACCES on that profile.
+ # Snapshot the owner first and hand it back to the new file.
+ previous = _stat_owner(self.baseFilename)
super().doRollover()
+ if previous is not None:
+ _restore_owner(self.baseFilename, previous)
self._chmod_if_managed()
# Our own rollover writes a new baseFilename; refresh the snapshot so
# the next emit doesn't mistake it for external rotation.
diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.py
index ee38dce6949..e2a3a14cf66 100644
--- a/tests/test_hermes_logging.py
+++ b/tests/test_hermes_logging.py
@@ -821,3 +821,92 @@ class TestLineBufferPipedStdout:
# setup_logging runs per AIAgent build: a second call must not re-flush/reconfigure.
hermes_logging.setup_logging(hermes_home=tmp_path, force=True)
stream.reconfigure.assert_called_once_with(line_buffering=True)
+
+
+class TestRolloverPreservesLogOwnership:
+ """Regression for #120151.
+
+ ``doRollover`` renames ``agent.log`` and opens a new one, so the replacement is owned
+ by whichever process wrote the record that crossed ``maxBytes``. With a rotating handler
+ per profile, that is usually the long-lived gateway — so a worker's log can be replaced
+ by a root-owned file the worker can never reopen, and the profile is locked out for good.
+ """
+
+ @staticmethod
+ def _make_handler(log_path: Path, max_bytes: int = 1):
+ handler = hermes_logging._ManagedRotatingFileHandler(
+ str(log_path), maxBytes=max_bytes, backupCount=1, encoding="utf-8",
+ )
+ handler.setFormatter(logging.Formatter("%(message)s"))
+ return handler
+
+ @pytest.mark.platforms("linux", "macos")
+ def test_rollover_keeps_the_previous_owner_and_mode(self, tmp_path):
+ """A rollover must not silently change who owns the log."""
+ log_path = tmp_path / "agent.log"
+ log_path.write_text("seed\n", encoding="utf-8")
+ os.chmod(log_path, 0o640)
+ before = os.stat(log_path)
+
+ handler = self._make_handler(log_path)
+ try:
+ handler.doRollover()
+ handler.flush()
+ finally:
+ handler.close()
+
+ after = os.stat(log_path)
+ assert (after.st_uid, after.st_gid) == (before.st_uid, before.st_gid)
+ assert stat.S_IMODE(after.st_mode) == stat.S_IMODE(before.st_mode)
+
+ @pytest.mark.platforms("linux", "macos")
+ def test_restore_owner_is_a_noop_when_chown_is_impossible(self, tmp_path, monkeypatch):
+ """An unprivileged process cannot chown — that must stay silent, not raise.
+
+ The unprivileged case never changed the owner in the first place, so leaving the
+ new file as-is is correct; a raised OSError would turn a log write into a crash.
+ """
+ target = tmp_path / "agent.log"
+ target.write_text("x\n", encoding="utf-8")
+ monkeypatch.setattr(os, "geteuid", lambda: 1000, raising=False)
+ monkeypatch.setattr(os, "chown", _raise_oserror, raising=False)
+ hermes_logging._restore_owner(str(target), (0, 0, 0o600))
+ assert target.exists() # reached here only because nothing raised
+
+ @pytest.mark.platforms("linux", "macos")
+ def test_stat_owner_reports_nothing_on_windows(self, tmp_path):
+ """A st without uid/gid (Windows) must read as 'nothing to preserve'."""
+ assert hermes_logging._stat_owner(str(tmp_path / "missing.log")) is None
+ existing = tmp_path / "agent.log"
+ existing.write_text("x\n", encoding="utf-8")
+ owner = hermes_logging._stat_owner(str(existing))
+ assert owner is not None
+ assert owner[0] == os.getuid() and owner[1] == os.getgid()
+
+ @pytest.mark.platforms("not linux", "not macos")
+ def test_stat_owner_is_none_where_there_are_no_uids(self, tmp_path, monkeypatch):
+ """Windows must not be handed an owner tuple it cannot act on."""
+ existing = tmp_path / "agent.log"
+ existing.write_text("x\n", encoding="utf-8")
+ real_stat = os.stat
+
+ def posix_free_stat(path, *args, **kwargs):
+ actual = real_stat(path, *args, **kwargs)
+ return _StatWithoutOwner(actual)
+
+ monkeypatch.setattr(os, "stat", posix_free_stat)
+ assert hermes_logging._stat_owner(str(existing)) is None
+
+
+def _raise_oserror(*_args, **_kwargs):
+ raise OSError("operation not permitted")
+
+
+class _StatWithoutOwner:
+ """An ``os.stat_result`` stand-in with no uid/gid, the way Windows reports one."""
+
+ st_uid = None
+ st_gid = None
+
+ def __init__(self, real):
+ self.st_mode = real.st_mode