The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(logging): check a routed profile's liveness at most every 2 s
kshitijk4poor6e4f652a3bd4
diff --git a/hermes_logging.py b/hermes_logging.pyindex 0419ae919e8..7e2995d9f9f 100644--- a/hermes_logging.py+++ b/hermes_logging.py@@ -17,6 +17,7 @@ import sysimport threadingfrom logging.handlers import QueueHandler, QueueListenerfrom pathlib import Path+from time import monotonic as _monotonicfrom typing import Optional, Sequencefrom hermes_constants import (@@ -446,6 +447,9 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):from hermes_cli.config import is_managedself._managed = is_managed()self._unavailable_reported = False+ # Set by _ProfileRoutingFileHandler: a vanished logs/ dir means the profile was deleted,+ # so skip the write (the router re-routes the record) instead of a FileNotFoundError traceback.+ self._skip_write_when_dir_missing = Falsesuper().__init__(*args, **kwargs)self._record_stream_stat()@@ -502,6 +506,10 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):# The kernel caches inode metadata, so this stat is sub-microsecond on a hot file.if self.stream is not None or os.path.exists(self.baseFilename):self._reopen_if_externally_rotated()+ # Only reached with no stream (reopen failed), so a healthy emit pays no extra stat.+ if (self.stream is None and self._skip_write_when_dir_missing+ and not os.path.isdir(os.path.dirname(self.baseFilename))):+ returnsuper().emit(record)# A record actually reached the file: only now has the destination recovered. Resetting# in _open() is wrong — open() succeeds on a device whose write/flush still raise EIO,@@ -581,6 +589,14 @@ def _new_file_handler(return handler+# A routed profile home is re-checked for an out-of-band delete (missing dir or tombstone) at+# most this often. WHY: the check is two stats per record per router on the listener thread,+# nearly doubling the syscalls of every live-profile emit; a deleted home only needs catching+# within a couple of seconds. Inside that window a tombstoned (not yet removed) home still gets+# its records; an rmtree is caught at once by the write that finds the directory gone.+_PROFILE_LIVENESS_RECHECK_S = 2.0++class _ProfileRoutingFileHandler(logging.Handler):"""Route queued records to the log file for their Hermes home.@@ -601,6 +617,8 @@ class _ProfileRoutingFileHandler(logging.Handler):self._backup_count = getattr(existing, "backupCount", 0)self._profile_handlers: dict[Path, _ManagedRotatingFileHandler] = {}self._profile_handlers_lock = threading.RLock()+ # Home -> monotonic time of its last liveness check (see _PROFILE_LIVENESS_RECHECK_S).+ self._liveness_checked_at: dict[Path, float] = {}self.setFormatter(existing.formatter)for log_filter in existing.filters:self.addFilter(log_filter)@@ -613,23 +631,39 @@ class _ProfileRoutingFileHandler(logging.Handler):candidate = self._default_homeif candidate == self._default_home or candidate not in self._profile_homes:return self._default_home- if not candidate.is_dir() or named_profile_is_deleted(candidate):- # Deleted out of band (CLI ``hermes profile delete`` while this process runs; it- # tombstones before rmtree). The startup snapshot still names it, so its handler would- # retry the vanished logs/ path on every record (#103777). Release it the way an- # in-process delete does: closes the stale fd and drops it from the routing set, so- # later records for it skip this check and fall back to the default home.- self.release_profile(candidate)- return self._default_home+ last = self._liveness_checked_at.get(candidate)+ if last is None or _monotonic() - last >= _PROFILE_LIVENESS_RECHECK_S:+ # First sighting always checks, so a home deleted before it ever logged is caught on+ # its first record; afterwards at most once per interval. An rmtree inside the+ # interval is caught by emit() on the record whose write finds the dir gone.+ if self._release_if_deleted(candidate):+ return self._default_homereturn candidate+ def _release_if_deleted(self, home: Path) -> bool:+ """Release *home* if it was deleted out of band; True when it was."""+ self._liveness_checked_at[home] = _monotonic()+ if home.is_dir() and not named_profile_is_deleted(home):+ return False+ # Deleted out of band (CLI ``hermes profile delete`` while this process runs; it+ # tombstones before rmtree). The startup snapshot still names it, so its handler would+ # retry the vanished logs/ path on every record (#103777). Release it the way an+ # in-process delete does: the stale fd is closed on this routed record and the home is+ # dropped from the routing set, so later records fall back to the default home. This+ # does not reach into another process: a CLI delete racing a live server's open fd+ # still relies on release_profile_log_handlers in-process and #130285.+ self.release_profile(home)+ return True+def _handler_for_home(self, home: Path) -> _ManagedRotatingFileHandler:with self._profile_handlers_lock:if home not in self._profile_handlers:- self._profile_handlers[home] = _new_file_handler(+ handler = _new_file_handler(home / "logs" / self._filename, level=self.level, max_bytes=self._max_bytes,backup_count=self._backup_count, formatter=self.formatter,)+ handler._skip_write_when_dir_missing = home != self._default_home+ self._profile_handlers[home] = handlerreturn self._profile_handlers[home]def emit(self, record: logging.LogRecord) -> None:@@ -647,6 +681,10 @@ class _ProfileRoutingFileHandler(logging.Handler):handler.handle(record)finally:reset_hermes_home_override(token)+ # The write lost its stream (an rmtree inside the liveness interval skips it, see+ # _ManagedRotatingFileHandler.emit): re-check now so this record is not dropped.+ if handler.stream is None and self._release_if_deleted(home):+ self._handler_for_home(self._default_home).handle(record)except Exception:self.handleError(record)@@ -663,6 +701,7 @@ class _ProfileRoutingFileHandler(logging.Handler):with self._profile_handlers_lock:handler = self._profile_handlers.pop(home, None)self._profile_homes.discard(home)+ self._liveness_checked_at.pop(home, None)if handler is None:return False_quietly(handler.close)diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.pyindex 7234d1f90ed..4b675bc4038 100644--- a/tests/test_hermes_logging.py+++ b/tests/test_hermes_logging.py@@ -66,6 +66,19 @@ def hermes_home(tmp_path, monkeypatch):return home+def liveness_clock(monkeypatch):+ """Drive the router's liveness-check clock so tests can cross the recheck interval+ without sleeping. Returns ``advance()``, which jumps past the interval."""+ now = [1000.0]+ monkeypatch.setattr(hermes_logging, "_monotonic", lambda: now[0], raising=False)++ def advance():+ now[0] += getattr(hermes_logging, "_PROFILE_LIVENESS_RECHECK_S", 2.0)++ return advance++@pytest.mark.parametrize("mode,component", [("cli", None), ("gateway", "gateway.log"), ("gui", "gui.log")])@pytest.mark.parametrize("configured,explicit,minimum", [(None, None, logging.INFO), ("DEBUG", "WARNING", logging.WARNING), ("DEBUG", None, logging.DEBUG)])def test_repeated_setup_routes_records_once(hermes_home, mode, component, configured, explicit, minimum):@@ -336,9 +349,12 @@ class TestSetupLogging:assert "FileNotFoundError" not in capsys.readouterr().err@pytest.mark.parametrize("removal", ["tombstone", "rmtree"])- def test_out_of_band_profile_delete_releases_routed_handler(self, hermes_home, capsys, removal):+ def test_out_of_band_profile_delete_releases_routed_handler(+ self, hermes_home, capsys, liveness_clock, removal+ ):"""A CLI delete tombstones then removes the home behind a running serve: the router must- stop writing there at either step and close the stale file, like an in-process delete."""+ stop writing there on either signal alone and close the stale file, like an in-process+ delete. The rmtree case has no tombstone so it exercises the missing-dir branch."""import shutilfrom hermes_constants import (@@ -363,9 +379,11 @@ class TestSetupLogging:routed = [h._profile_handlers[profile_home] for h in hermes_logging._queued_file_handlersif isinstance(h, hermes_logging._ProfileRoutingFileHandler)]assert routed- mark_named_profile_deleted(profile_home)- if removal == "rmtree":- shutil.rmtree(profile_home)+ if removal == "tombstone":+ mark_named_profile_deleted(profile_home)+ liveness_clock() # a tombstone alone is seen on the next interval check+ else:+ shutil.rmtree(profile_home) # caught by the write itself, inside the intervalcapsys.readouterr()for i in range(3):emit(f"after delete {i}")@@ -377,6 +395,42 @@ class TestSetupLogging:profile_log = profile_home / "logs" / "agent.log"assert not profile_log.exists() or "after delete" not in profile_log.read_text(encoding="utf-8-sig")+ def test_live_profile_liveness_checked_at_most_once_per_interval(self, hermes_home, liveness_clock):+ """A live routed profile must not pay the delete check (two stats) on every record."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override++ profile_home = (hermes_home / "profiles" / "worker").resolve()+ profile_home.mkdir(parents=True)+ hermes_logging.setup_logging(hermes_home=hermes_home)+ assert hermes_logging.enable_profile_log_routing([hermes_home, profile_home]) is True+ logger = logging.getLogger("cron.scheduler.liveness-rate-limit-test")+ calls = []+ real = hermes_logging.named_profile_is_deleted++ def counting(home):+ calls.append(home)+ return real(home)++ def emit_many(n):+ token = set_hermes_home_override(profile_home)+ try:+ for i in range(n):+ logger.warning("live %d", i)+ finally:+ reset_hermes_home_override(token)+ hermes_logging.flush_log_queue()++ with patch.object(hermes_logging, "named_profile_is_deleted", counting):+ emit_many(5)+ first = len(calls)+ liveness_clock()+ emit_many(5)+ routers = sum(isinstance(h, hermes_logging._ProfileRoutingFileHandler)+ for h in hermes_logging._queued_file_handlers)+ assert routers and first == routers, "first sighting checks once per router, then rate-limits"+ assert len(calls) == 2 * routers+ assert "live 4" in (profile_home / "logs" / "agent.log").read_text(encoding="utf-8-sig")+def test_explicit_params_override_config(self, hermes_home):"""Explicit function params take precedence over config.yaml."""import hermes_yaml as yaml