The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(logging): inline the rollover owner restore into doRollover (#120151, salvage #124764)
teknium1b05f767b0708
diff --git a/hermes_logging.py b/hermes_logging.pyindex 2fff2f2d4f7..5dc6042255e 100644--- a/hermes_logging.py+++ b/hermes_logging.py@@ -17,7 +17,7 @@ import sysimport threadingfrom logging.handlers import QueueHandler, QueueListenerfrom pathlib import Path-from typing import Optional, Sequence, Tuple+from typing import Optional, Sequencefrom hermes_constants import get_config_path, get_hermes_home, mkdir_under_hermes_home@@ -430,35 +430,6 @@ 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.@@ -569,16 +540,22 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):return streamdef 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)+ # The stdlib rollover opens a fresh baseFilename owned by whichever process crossed+ # maxBytes. With one rotating handler per profile that is usually the long-lived root+ # gateway, and a worker on another uid can never reopen its own agent.log (#120151).+ # Only root can hand the file back; an unprivileged process never changed the owner.+ try:+ previous = os.stat(self.baseFilename)+ except OSError:+ previous = Nonesuper().doRollover()if previous is not None:- _restore_owner(self.baseFilename, previous)+ try:+ if getattr(os, "geteuid", lambda: -1)() == 0:+ os.chown(self.baseFilename, previous.st_uid, previous.st_gid)+ os.chmod(self.baseFilename, previous.st_mode & 0o7777)+ except OSError:+ pass # a log that cannot be chowned is still a working logself._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.pyindex e2a3a14cf66..a096d54ca11 100644--- a/tests/test_hermes_logging.py+++ b/tests/test_hermes_logging.py@@ -824,89 +824,38 @@ class TestLineBufferPipedStdout: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.- """+ """#120151: the stdlib rollover opens a fresh ``agent.log`` owned by the rotating process; a root+ gateway sharing a profile's log with a worker on another uid must hand the new file back."""@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"+ def _rolled_handler(log_path: Path):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)+ handler = hermes_logging._ManagedRotatingFileHandler(+ str(log_path), maxBytes=1, backupCount=1, encoding="utf-8")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+ def test_rollover_hands_the_new_file_back_to_the_previous_owner(self, tmp_path, monkeypatch):+ log_path = tmp_path / "agent.log"+ chowned = []+ monkeypatch.setattr(os, "geteuid", lambda: 0)+ monkeypatch.setattr(os, "chown", lambda path, uid, gid: chowned.append((path, uid, gid)))+ self._rolled_handler(log_path)+ assert chowned == [(str(log_path), os.getuid(), os.getgid())]+ assert stat.S_IMODE(os.stat(log_path).st_mode) == 0o640@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 test_rollover_survives_a_refused_chown(self, tmp_path, monkeypatch):+ """A log that cannot be chowned is still a working log: never raise out of a rollover."""+ log_path = tmp_path / "agent.log"+ monkeypatch.setattr(os, "geteuid", lambda: 0)- def __init__(self, real):- self.st_mode = real.st_mode+ def _refuse(*_args):+ raise OSError("operation not permitted")+ monkeypatch.setattr(os, "chown", _refuse)+ self._rolled_handler(log_path)+ assert log_path.exists()