Skip to content

The agent that grows with you

fix(redact): the log formatter never waits for config

Ben Barclay8ae88edc8ab7
diff --git a/agent/redact.py b/agent/redact.py
index 47c59918714..7160c9f8a68 100644
--- a/agent/redact.py
+++ b/agent/redact.py
@@ -130,13 +130,20 @@ def _redact_enabled() -> bool:
from hermes_cli.config import load_env
raw = load_env().get("HERMES_REDACT_SECRETS")
if raw is None:
- from hermes_cli.config import load_config_readonly
- cfg_val = (load_config_readonly().get("security") or {}).get("redact_secrets")
+ # Never wait for config here: this runs under the logging handler's lock, and the
+ # thread holding the config lock (or booting this profile's config) may be logging.
+ from hermes_cli.config import load_config_readonly_nowait
+ cfg = load_config_readonly_nowait()
+ if cfg is None:
+ return True # not readable at once: the secure default, not cached
+ cfg_val = (cfg.get("security") or {}).get("redact_secrets")
raw = None if cfg_val is None else str(cfg_val)
if raw is not None:
enabled = str(raw).strip().lower() in {"1", "true", "yes", "on"}
except Exception:
enabled = True # unreadable policy: keep the secure default
+ except SystemExit: # ConfigBackendUnavailable: config not loadable now; never cache that
+ return True
with _REDACT_ENABLED_LOCK:
_REDACT_ENABLED_BY_HOME[home_key] = enabled
return enabled
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 6dc63b54f14..3ba2284889c 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -1982,6 +1982,22 @@ def load_config() -> dict[str, Any]:
return _load_config_impl(want_deepcopy=True)
+def load_config_readonly_nowait() -> Optional[dict[str, Any]]:
+ """:func:`load_config_readonly` for code that must never wait (a log formatter, under the
+ handler's lock). None when ``_CONFIG_LOCK`` is held elsewhere or the read would start a remote
+ boot fetch: callers use a secure default and must not cache it."""
+ from hermes_cli.config_backend import ConfigBackendUnavailable, without_boot
+ if not _CONFIG_LOCK.acquire(blocking=False):
+ return None
+ try:
+ with without_boot():
+ return load_config_readonly()
+ except ConfigBackendUnavailable:
+ return None
+ finally:
+ _CONFIG_LOCK.release()
+
+
def load_config_readonly() -> dict[str, Any]:
"""``load_config()`` without the defensive deepcopy (~half of the 265us cache-hit cost).
**Mutating the returned dict (or any nested structure) corrupts the in-process cache for
diff --git a/hermes_cli/config_backend.py b/hermes_cli/config_backend.py
index 622d5f47771..ec7db04835c 100644
--- a/hermes_cli/config_backend.py
+++ b/hermes_cli/config_backend.py
@@ -526,6 +526,25 @@ def refused_locked_omission_prefixes() -> tuple[str, ...]:
# Dotted keys a document save in this context stores at the user layer even when the value equals
# what an upper level already supplies (an explicit `config set`): the file backend always writes
# them, and a backend with levels must not drop them as "no change".
+_NO_BOOT: contextvars.ContextVar[bool] = contextvars.ContextVar("config_no_boot", default=False)
+
+
+def without_boot():
+ """Reads in this scope never start loading a profile's config (a remote boot fetch, with its
+ network calls and retries): a backend raises :class:`ConfigBackendUnavailable` instead. For
+ code that must never wait, such as a log formatter."""
+ token = _NO_BOOT.set(True)
+ try:
+ yield
+ finally:
+ _NO_BOOT.reset(token)
+
+
+def boot_allowed() -> bool:
+ return not _NO_BOOT.get()
+
+
_PINNED_KEYS: contextvars.ContextVar[tuple[str, ...]] = contextvars.ContextVar("config_pinned_keys", default=())
diff --git a/plugins/config_backends/remote/backend.py b/plugins/config_backends/remote/backend.py
index 004808c5129..7d37e147b3e 100644
--- a/plugins/config_backends/remote/backend.py
+++ b/plugins/config_backends/remote/backend.py
@@ -21,6 +21,7 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
+from hermes_cli.config_backend import boot_allowed as config_backend_boot_allowed
from hermes_cli.config_backend import (
Changes, ConfigBackendUnavailable, ConfigLockedError, ConfigValueError, ConfigWriteError, UserLayer,
pinned_keys, refused_locked_omission_prefixes)
@@ -206,6 +207,9 @@ class RemoteBackend:
if poller is None or self._poller_pid != os.getpid() or not poller.is_alive():
self._ensure_poller()
return st
+ if not config_backend_boot_allowed():
+ raise ConfigBackendUnavailable(
+ f"Remote Config: the config for {home} is not loaded yet, and this read does not wait for it.")
if key in self._booting():
# This thread is loading this profile (resolving its credential or fetching): the read
# can only be served by the load it is part of. Waiting would wait on itself forever.
diff --git a/tests/plugins/config_backends/test_remote_backend.py b/tests/plugins/config_backends/test_remote_backend.py
index b7067c6aa56..8a7fd4927f8 100644
--- a/tests/plugins/config_backends/test_remote_backend.py
+++ b/tests/plugins/config_backends/test_remote_backend.py
@@ -1880,98 +1880,3 @@ def test_custom_endpoint_make_default_refuses_when_its_provider_entry_is_locked(
id="new-probe", name="new-probe", base_url="https://new.example/v1", model="new-model", make_default=True))
assert exc.value.status_code == 403, exc.value
assert plane.profile("default")["values"].get("model") in (None, {}), plane.profile("default")
-
-
-# --- re-entry ----------------------------------------------------------------------------
-
-def _blocked_in_state(thread) -> bool:
- import sys
- frame = sys._current_frames().get(thread.ident)
- while frame is not None:
- if frame.f_code is backend_mod.RemoteBackend._state.__code__:
- return True
- frame = frame.f_back
- return False
-
-
-def test_same_thread_reentry_raises_while_other_threads_wait(plane, monkeypatch):
- """Code on a profile's boot path (its credential before the fetch, or anything during it) that
- reads that profile's config gets a loud ConfigBackendUnavailable at once instead of waiting on
- its own load forever; another thread still waits for the fetch in flight and shares it."""
- import threading
- import time
-
- from tests.waiting import wait_until
-
- backend = remote_pkg.get_remote_backend()
- home = plane.home
- real_token, real_request = backend_mod.client.plane_token, backend_mod.client.request
- errors: list = []
- other: dict = {}
- waiter = threading.Thread(target=lambda: other.setdefault("state", backend._state(home)), daemon=True)
-
- def reenter():
- started = time.monotonic()
- try:
- backend.version(home)
- except ConfigBackendUnavailable as exc:
- errors.append((str(exc), time.monotonic() - started))
-
- def token(h):
- if not errors:
- reenter() # before the fetch lock
- return real_token(h)
-
- def request(method, *args, **kwargs):
- if method == "GET" and len(errors) == 1:
- reenter() # under the fetch lock
- waiter.start()
- wait_until(lambda: _blocked_in_state(waiter), timeout=5, what="the other thread waits")
- return real_request(method, *args, **kwargs)
-
- monkeypatch.setattr(backend_mod.client, "plane_token", token)
- monkeypatch.setattr(backend_mod.client, "request", request)
- plane.upper = {"display": {"skin": "ares"}}
- assert backend.read_user_doc(home)["display"]["skin"] == "ares"
- assert len(errors) == 2 and all("re-entered" in msg and secs < 1.0 for msg, secs in errors)
- waiter.join(5)
- assert not waiter.is_alive() and other["state"] is backend._state(home)
- assert len(_gets(plane)) == 1 # the waiting thread used the fetch it waited for
- backend.version(home) # once loaded, the same thread reads normally
-
-
-def test_nothing_is_logged_under_a_backend_lock(plane, monkeypatch):
- """A log handler can read config, and a thread holding the handler's lock may be waiting for a
- backend lock: the boot retry warning and the write's inherited-key warning are both emitted
- with no fetch lock or profile state lock held."""
- import logging
-
- backend = remote_pkg.get_remote_backend()
- seen: list = []
-
- class Probe(logging.Handler):
- def emit(self, record):
- held = any(lk.locked() for lk in list(backend._fetch_locks.values()))
- held = held or any(st.lock._is_owned() for st in list(backend._states.values()))
- seen.append((record.getMessage(), held))
-
- real_request = backend_mod.client.request
-
- def first_get_fails(method, *args, **kwargs):
- resp = real_request(method, *args, **kwargs)
- plane.fail_status = None
- return resp
-
- monkeypatch.setattr(backend_mod.client, "request", first_get_fails)
- probe = Probe(level=logging.WARNING)
- backend_mod.logger.addHandler(probe)
- try:
- plane.upper = {"display": {"personality": "concise"}}
- plane.profile("default")["values"] = {"display": {"personality": "pirate"}}
- plane.fail_status = 503 # the first GET: a retryable outage, warned about before the retry
- write_config_key(plane.home / "config.yaml", "display.personality", None)
- finally:
- backend_mod.logger.removeHandler(probe)
- messages = [m for m, _ in seen]
- assert any("retrying" in m for m in messages) and any("still set by an upper level" in m for m in messages)
- assert [m for m, held in seen if held] == []
diff --git a/tests/plugins/config_backends/test_remote_backend_lock_order.py b/tests/plugins/config_backends/test_remote_backend_lock_order.py
new file mode 100644
index 00000000000..b7faeb111ef
--- /dev/null
+++ b/tests/plugins/config_backends/test_remote_backend_lock_order.py
@@ -0,0 +1,172 @@
+"""Remote backend lock order: same-thread re-entry, logging outside backend locks, the formatter."""
+from __future__ import annotations
+
+from hermes_cli.config_backend import ConfigBackendUnavailable, write_config_key
+from plugins.config_backends import remote as remote_pkg
+from plugins.config_backends.remote import backend as backend_mod
+
+from . import test_remote_backend as _base
+
+plane = _base.plane # the stub-plane fixture
+_gets = _base._gets
+
+
+# --- re-entry ----------------------------------------------------------------------------
+
+def _blocked_in_state(thread) -> bool:
+ import sys
+ frame = sys._current_frames().get(thread.ident)
+ while frame is not None:
+ if frame.f_code is backend_mod.RemoteBackend._state.__code__:
+ return True
+ frame = frame.f_back
+ return False
+
+
+def test_same_thread_reentry_raises_while_other_threads_wait(plane, monkeypatch):
+ """Code on a profile's boot path (its credential before the fetch, or anything during it) that
+ reads that profile's config gets a loud ConfigBackendUnavailable at once instead of waiting on
+ its own load forever; another thread still waits for the fetch in flight and shares it."""
+ import threading
+ import time
+
+ from tests.waiting import wait_until
+
+ backend = remote_pkg.get_remote_backend()
+ home = plane.home
+ real_token, real_request = backend_mod.client.plane_token, backend_mod.client.request
+ errors: list = []
+ other: dict = {}
+ waiter = threading.Thread(target=lambda: other.setdefault("state", backend._state(home)), daemon=True)
+
+ def reenter():
+ started = time.monotonic()
+ try:
+ backend.version(home)
+ except ConfigBackendUnavailable as exc:
+ errors.append((str(exc), time.monotonic() - started))
+
+ def token(h):
+ if not errors:
+ reenter() # before the fetch lock
+ return real_token(h)
+
+ def request(method, *args, **kwargs):
+ if method == "GET" and len(errors) == 1:
+ reenter() # under the fetch lock
+ waiter.start()
+ wait_until(lambda: _blocked_in_state(waiter), timeout=5, what="the other thread waits")
+ return real_request(method, *args, **kwargs)
+
+ monkeypatch.setattr(backend_mod.client, "plane_token", token)
+ monkeypatch.setattr(backend_mod.client, "request", request)
+ plane.upper = {"display": {"skin": "ares"}}
+ assert backend.read_user_doc(home)["display"]["skin"] == "ares"
+ assert len(errors) == 2 and all("re-entered" in msg and secs < 1.0 for msg, secs in errors)
+ waiter.join(5)
+ assert not waiter.is_alive() and other["state"] is backend._state(home)
+ assert len(_gets(plane)) == 1 # the waiting thread used the fetch it waited for
+ backend.version(home) # once loaded, the same thread reads normally
+
+
+def test_nothing_is_logged_under_a_backend_lock(plane, monkeypatch):
+ """A log handler can read config, and a thread holding the handler's lock may be waiting for a
+ backend lock: the boot retry warning and the write's inherited-key warning are both emitted
+ with no fetch lock or profile state lock held."""
+ import logging
+
+ backend = remote_pkg.get_remote_backend()
+ seen: list = []
+
+ class Probe(logging.Handler):
+ def emit(self, record):
+ held = any(lk.locked() for lk in list(backend._fetch_locks.values()))
+ held = held or any(st.lock._is_owned() for st in list(backend._states.values()))
+ seen.append((record.getMessage(), held))
+
+ real_request = backend_mod.client.request
+
+ def first_get_fails(method, *args, **kwargs):
+ resp = real_request(method, *args, **kwargs)
+ plane.fail_status = None
+ return resp
+
+ monkeypatch.setattr(backend_mod.client, "request", first_get_fails)
+ probe = Probe(level=logging.WARNING)
+ backend_mod.logger.addHandler(probe)
+ try:
+ plane.upper = {"display": {"personality": "concise"}}
+ plane.profile("default")["values"] = {"display": {"personality": "pirate"}}
+ plane.fail_status = 503 # the first GET: a retryable outage, warned about before the retry
+ write_config_key(plane.home / "config.yaml", "display.personality", None)
+ finally:
+ backend_mod.logger.removeHandler(probe)
+ messages = [m for m, _ in seen]
+ assert any("retrying" in m for m in messages) and any("still set by an upper level" in m for m in messages)
+ assert [m for m, held in seen if held] == []
+
+
+def test_boot_retry_warning_through_the_real_redacting_formatter(plane, monkeypatch):
+ """The boot's retry warning is formatted by RedactingFormatter, which reads the routed profile's
+ redaction policy from config: on the booting thread that read must not re-enter the boot (it
+ would abort it), and it must never wait for the config lock another thread holds."""
+ import logging
+ import threading
+
+ from agent import redact
+ from agent.redact import RedactingFormatter
+ from hermes_cli import config as config_mod
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ backend = remote_pkg.get_remote_backend()
+ formatted: list = []
+
+ class Handler(logging.Handler):
+ def emit(self, record):
+ formatted.append(self.format(record))
+
+ real_request = backend_mod.client.request
+
+ def first_get_fails(method, *args, **kwargs):
+ resp = real_request(method, *args, **kwargs)
+ plane.fail_status = None
+ return resp
+
+ monkeypatch.setattr(backend_mod.client, "request", first_get_fails)
+ monkeypatch.setattr(redact, "_REDACT_ENABLED_BY_HOME", {})
+ handler = Handler(level=logging.WARNING)
+ handler.setFormatter(RedactingFormatter("%(message)s"))
+ backend_mod.logger.addHandler(handler)
+ plane.upper = {"display": {"skin": "ares"}}
+ plane.fail_status = 503
+ token = set_hermes_home_override(plane.home) # a routed profile: the formatter reads its config
+ try:
+ assert backend.read_user_doc(plane.home)["display"]["skin"] == "ares" # booted after one retry
+ assert any("retrying" in m for m in formatted), formatted
+ assert len(_gets(plane)) == 2
+ assert redact._REDACT_ENABLED_BY_HOME == {} # the boot-time fallback was not cached
+
+ # Another thread holds the config lock: formatting returns at once with the secure default.
+ held, release = threading.Event(), threading.Event()
+
+ def holder():
+ with config_mod._CONFIG_LOCK:
+ held.set()
+ release.wait(10)
+
+ t = threading.Thread(target=holder, daemon=True)
+ t.start()
+ assert held.wait(5)
+ try:
+ done: list = []
+ worker = threading.Thread(target=lambda: done.append(redact._redact_enabled()), daemon=True)
+ worker.start()
+ worker.join(5)
+ assert done == [True], "the formatter waited for the config lock"
+ assert redact._REDACT_ENABLED_BY_HOME == {}
+ finally:
+ release.set()
+ t.join(5)
+ finally:
+ reset_hermes_home_override(token)
+ backend_mod.logger.removeHandler(handler)