The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(updater): bound import probe teardown
KoNit-Ke74c29de5553
diff --git a/hermes_cli/_subprocess_compat.py b/hermes_cli/_subprocess_compat.pyindex 9ae2ce29ada..97d94f6ec76 100644--- a/hermes_cli/_subprocess_compat.py+++ b/hermes_cli/_subprocess_compat.py@@ -497,7 +497,7 @@ def _legacy_kill_process_tree(proc: "subprocess.Popen") -> None:def bounded_probe_run(argv: Sequence[str], *, timeout: float, errors: str = "replace",- env: "Mapping[str, str] | None" = None,+ env: "Mapping[str, str] | None" = None, cwd: "str | os.PathLike[str] | None" = None,) -> "subprocess.CompletedProcess[str] | None":"""Deadlock-safe ``subprocess.run(argv, capture_output=True, timeout=…)`` for fail-open probes.@@ -516,7 +516,7 @@ def bounded_probe_run(proc = subprocess.Popen(list(argv), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.DEVNULL,text=True, encoding="utf-8", errors=errors,- env=dict(env) if env is not None else None, **_popen_kwargs)+ env=dict(env) if env is not None else None, cwd=cwd, **_popen_kwargs)except Exception:return Nonetry:@@ -563,4 +563,3 @@ def bounded_git_probe(argv: Sequence[str], *, timeout: float) -> str:if result is None or result.returncode != 0:return ""return (result.stdout or "").strip()-diff --git a/hermes_cli/update_cmd_deps.py b/hermes_cli/update_cmd_deps.pyindex 2e63135fe21..7e3362f3ada 100644--- a/hermes_cli/update_cmd_deps.py+++ b/hermes_cli/update_cmd_deps.py@@ -13,6 +13,7 @@ import sysfrom pathlib import Pathfrom typing import Optionalfrom hermes_constants import venv_python_path+from hermes_cli._subprocess_compat import bounded_probe_run# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")@@ -83,14 +84,15 @@ def _critical_module_import_failures(venv_python = venv_python_path(Path(root) / "venv", windows=_m()._is_windows())if venv_python.exists():interpreter = str(venv_python)- result = subprocess.run(- [interpreter, "-c", probe], cwd=str(root), capture_output=True, text=True,- encoding="utf-8", errors="replace", timeout=120)- except subprocess.TimeoutExpired:- return _probe_failure("TimeoutExpired", "timed out before reporting import health")+ result = bounded_probe_run(+ [interpreter, "-c", probe], timeout=120, cwd=str(root),+ )except (OSError, subprocess.SubprocessError):- # Can't run the probe — don't block the update on our own tooling.+ # Keep this guard advisory: a broken probe runner cannot make an otherwise+ # successful update fail.return {}+ if result is None:+ return _probe_failure("TimeoutExpired", "timed out before reporting import health")output = result.stdout or ""if marker not in output:return _probe_failure(diff --git a/hermes_logging.py b/hermes_logging.pyindex 4798f0742c1..b1f2ffa8a37 100644--- a/hermes_logging.py+++ b/hermes_logging.py@@ -81,6 +81,14 @@ def _is_windows_concurrent_log_lock_timeout(exc: BaseException | None) -> bool:)+def _is_unavailable_log_stream(exc: BaseException | None) -> bool:+ """True when a file handler lost its backing stream during teardown or I/O."""+ return (+ (isinstance(exc, OSError) and exc.errno == 5)+ or (isinstance(exc, ValueError) and "closed file" in str(exc).lower())+ )++# Third-party loggers that are noisy at DEBUG/INFO level._NOISY_LOGGERS = ("openai", "openai._base_client", "httpx", "httpcore", "asyncio", "hpack", "hpack.hpack",@@ -324,8 +332,18 @@ class _ManagedRotatingFileHandler(RotatingFileHandler):silence it before stdlib prints to stderr (which the Desktop slash-workercaptures into chat output)."""- if not _is_windows_concurrent_log_lock_timeout(sys.exc_info()[1]):- super().handleError(record)+ exc = sys.exc_info()[1]+ if _is_windows_concurrent_log_lock_timeout(exc):+ return+ if _is_unavailable_log_stream(exc):+ # The QueueListener must not turn a transient filesystem failure+ # into a traceback for every queued record. Drop the stale stream;+ # the next emit will reopen it if the destination has recovered.+ if self.stream is not None:+ _quietly(self.stream.close)+ self.stream = None # type: ignore[assignment]+ return+ super().handleError(record)def _open(self):stream = super()._open()diff --git a/tests/hermes_cli/test_update_import_guard.py b/tests/hermes_cli/test_update_import_guard.pyindex 0eeb6367116..7262c279e5d 100644--- a/tests/hermes_cli/test_update_import_guard.py+++ b/tests/hermes_cli/test_update_import_guard.py@@ -206,7 +206,7 @@ def test_import_guard_rejects_malformed_health_payload(monkeypatch, tmp_path):Result.stdout = f"{marker}{{}}"return Result()- monkeypatch.setattr(update_cmd.subprocess, "run", malformed)+ monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", malformed)ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@ -219,9 +219,9 @@ def test_import_guard_reports_probe_timeout(monkeypatch, tmp_path):import subprocessdef timeout(*_args, **_kwargs):- raise subprocess.TimeoutExpired(["python", "-c", "probe"], 120)+ return None- monkeypatch.setattr(update_cmd.subprocess, "run", timeout)+ monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", timeout)ok, module, error = update_cmd._validate_critical_modules_import(tmp_path)@@ -241,14 +241,12 @@ def test_untracked_enumeration_failure_is_visible(monkeypatch, tmp_path, capsys)assert "Could not enumerate untracked files" in capsys.readouterr().out-def test_import_guard_is_non_fatal_when_probe_cannot_run(monkeypatch, tmp_path):- """If we can't spawn the probe, don't block the user's update."""-- def boom(*_a, **_kw):- raise OSError("cannot spawn")-- monkeypatch.setattr(update_cmd.subprocess, "run", boom)- assert update_cmd._validate_critical_modules_import(tmp_path) == (True, None, None)+def test_import_guard_reports_bounded_probe_failure(monkeypatch, tmp_path):+ """A wedged child reports promptly instead of blocking update teardown."""+ monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", lambda *_a, **_kw: None)+ assert update_cmd._validate_critical_modules_import(tmp_path) == (+ False, "critical-module probe", "timed out before reporting import health",+ )# ---------------------------------------------------------------------------@@ -299,6 +297,7 @@ def test_import_guard_prefers_the_project_venv_interpreter(monkeypatch, tmp_pathdef fake_run(cmd, **kwargs):seen["interpreter"] = cmd[0]+ seen["cwd"] = kwargs["cwd"]class R:returncode = 0@@ -307,10 +306,11 @@ def test_import_guard_prefers_the_project_venv_interpreter(monkeypatch, tmp_pathreturn R()- monkeypatch.setattr(update_cmd.subprocess, "run", fake_run)+ monkeypatch.setattr(update_cmd_deps, "bounded_probe_run", fake_run)update_cmd._validate_critical_modules_import(tmp_path)assert seen["interpreter"] == str(venv_python)+ assert seen["cwd"] == str(tmp_path)def test_import_guard_ignores_missing_third_party_dependency(monkeypatch, tmp_path):@@ -381,12 +381,12 @@ def test_probe_and_hint_share_one_first_party_definition():captured["probe"] = cmd[-1]return _Result()- real_run = update_cmd.subprocess.run- update_cmd.subprocess.run = capture+ real_run = update_cmd_deps.bounded_probe_run+ update_cmd_deps.bounded_probe_run = capturetry:update_cmd._validate_critical_modules_import("/tmp")finally:- update_cmd.subprocess.run = real_run+ update_cmd_deps.bounded_probe_run = real_runprobe_src = captured["probe"]# Every first-party root must appear in the probe's injected tuple.diff --git a/tests/test_hermes_logging.py b/tests/test_hermes_logging.pyindex 4254d955c69..9e2129fd055 100644--- a/tests/test_hermes_logging.py+++ b/tests/test_hermes_logging.py@@ -604,6 +604,23 @@ class TestExternalRotationRecovery:assert "AFTER rotation" not in rotated.read_text()+def test_eio_from_file_handler_is_suppressed(tmp_path, capsys):+ """An unavailable log destination must not print a traceback per record."""+ handler = hermes_logging._ManagedRotatingFileHandler(+ str(tmp_path / "agent.log"), maxBytes=1024, backupCount=1, encoding="utf-8",+ )+ record = logging.LogRecord("test.eio", logging.INFO, __file__, 0, "message", (), None)+ try:+ try:+ raise OSError(5, "Input/output error")+ except OSError:+ handler.handleError(record)++ assert "--- Logging error ---" not in capsys.readouterr().err+ finally:+ handler.close()++class TestSafeStderr:"""Tests for _safe_stderr() — Unicode tolerance on Windows console."""@@ -685,4 +702,3 @@ class TestAsyncQueueLogging:"agent.log" in getattr(h, "baseFilename", "")for h in hermes_logging._queued_file_handlers)-