Skip to content

The agent that grows with you

fix(config): serialize .env read-modify-write cycles with a file lock

Brooklyn Nicholsonca8f8dd5d8b1
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index e2ad5c1f7fe..466e48dca51 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -25,7 +25,7 @@ import tempfile
import threading
import time
import unicodedata
-from contextlib import suppress
+from contextlib import contextmanager, suppress
from dataclasses import dataclass
from decimal import Decimal, InvalidOperation
from pathlib import Path
@@ -2600,14 +2600,15 @@ def sanitize_env_file() -> int:
env_path = get_env_path()
if not env_path.exists():
return 0
- with open(env_path, encoding="utf-8-sig", errors="replace") as f:
- original_lines = f.readlines()
- sanitized = _sanitize_env_lines(original_lines)
- if sanitized == original_lines:
- return 0
- fixes = abs(len(sanitized) - len(original_lines)) or sum(
- 1 for a, b in zip(original_lines, sanitized) if a != b)
- _write_env_lines(env_path, sanitized, preserve_mode=False)
+ with _env_write_lock(env_path):
+ with open(env_path, encoding="utf-8-sig", errors="replace") as f:
+ original_lines = f.readlines()
+ sanitized = _sanitize_env_lines(original_lines)
+ if sanitized == original_lines:
+ return 0
+ fixes = abs(len(sanitized) - len(original_lines)) or sum(
+ 1 for a, b in zip(original_lines, sanitized) if a != b)
+ _write_env_lines(env_path, sanitized, preserve_mode=False)
invalidate_env_cache()
return fixes
@@ -2619,6 +2620,49 @@ def _read_env_lines(env_path: Path) -> list:
return _sanitize_env_lines(f.readlines())
+_ENV_WRITE_LOCK_HOLDERS: Dict[str, Any] = {}
+_ENV_WRITE_LOCK_HOLDERS_GUARD = threading.Lock()
+
+
+def _env_write_lock_holder(env_path: Path) -> Any:
+ """Reentrancy tracker for one canonical ``.env`` path (mirrors auth's
+ ``_auth_lock_holder_for``): multiplexed profiles each get their own tracker."""
+ key = str(env_path)
+ with _ENV_WRITE_LOCK_HOLDERS_GUARD:
+ return _ENV_WRITE_LOCK_HOLDERS.setdefault(key, threading.local())
+
+
+@contextmanager
+def _env_write_lock(env_path: Path):
+ """Serialize a whole ``.env`` read-modify-write cycle (#77187).
+
+ ``save_env_value`` / ``remove_env_value`` / ``sanitize_env_file`` read the file,
+ rewrite it in memory, then atomically replace it. Without a lock, two
+ concurrent writers (setup wizard + dashboard save, gateway + CLI) both
+ snapshot the pre-write file and the loser's replace silently drops the
+ winner's key. ``_CONFIG_LOCK`` cannot help: it guards in-memory config only.
+
+ Reuses ``hermes_cli.auth._file_lock`` (fcntl flock / msvcrt byte lock,
+ cross-process, reentrant per thread) rather than growing a second kernel-lock
+ implementation. The import is call-time: ``hermes_cli.auth`` imports this
+ module at import time, so a module-level import would be circular. Nothing
+ under this lock takes other locks, and the only nesting direction that exists
+ (credential_lifecycle takes ``_auth_store_lock`` around its own auth-store
+ writes, NOT around ``save_env_value``) keeps a single ordering — no cycle.
+ On a filesystem without flock the helper degrades to a depth-only guard
+ (same behavior as auth's locks), never to a crash.
+ """
+ from hermes_cli.auth import _file_lock
+
+ with _file_lock(
+ env_path.with_name(env_path.name + ".lock"),
+ _env_write_lock_holder(env_path),
+ 15.0,
+ f"Timed out waiting for the environment file lock ({env_path})",
+ ):
+ yield
+
+
def _write_env_lines(env_path: Path, lines: list, *, preserve_mode: bool) -> None:
"""Atomically replace ``.env`` (tmp file + fsync + rename).
``preserve_mode`` keeps the original file mode (e.g. 0640 for Docker volume mounts) instead of
@@ -2780,18 +2824,19 @@ def save_env_value(key: str, value: str):
ensure_hermes_home()
env_path = get_env_path()
- lines = _read_env_lines(env_path) if env_path.exists() else []
- serialized_value = _quote_env_value(value)
+ with _env_write_lock(env_path):
+ lines = _read_env_lines(env_path) if env_path.exists() else []
+ serialized_value = _quote_env_value(value)
- idx = next((i for i, line in enumerate(lines) if _env_line_defines_key(line, key)), None)
- if idx is not None:
- lines[idx] = f"{key}={serialized_value}\n"
- else:
- if lines and not lines[-1].endswith("\n"):
- lines[-1] += "\n"
- lines.append(f"{key}={serialized_value}\n")
+ idx = next((i for i, line in enumerate(lines) if _env_line_defines_key(line, key)), None)
+ if idx is not None:
+ lines[idx] = f"{key}={serialized_value}\n"
+ else:
+ if lines and not lines[-1].endswith("\n"):
+ lines[-1] += "\n"
+ lines.append(f"{key}={serialized_value}\n")
- _write_env_lines(env_path, lines, preserve_mode=env_path.exists())
+ _write_env_lines(env_path, lines, preserve_mode=env_path.exists())
_publish_env_value(key, value)
invalidate_env_cache()
@@ -2816,11 +2861,12 @@ def remove_env_value(key: str) -> bool:
_publish_env_value(key, None)
return False
- lines = _read_env_lines(env_path)
- new_lines = [line for line in lines if not _env_line_defines_key(line, key)]
- found = len(new_lines) < len(lines)
- if found:
- _write_env_lines(env_path, new_lines, preserve_mode=True)
+ with _env_write_lock(env_path):
+ lines = _read_env_lines(env_path)
+ new_lines = [line for line in lines if not _env_line_defines_key(line, key)]
+ found = len(new_lines) < len(lines)
+ if found:
+ _write_env_lines(env_path, new_lines, preserve_mode=True)
_publish_env_value(key, None)
invalidate_env_cache()
return found
diff --git a/tests/hermes_cli/test_env_write_race.py b/tests/hermes_cli/test_env_write_race.py
new file mode 100644
index 00000000000..bfe4fa58a61
--- /dev/null
+++ b/tests/hermes_cli/test_env_write_race.py
@@ -0,0 +1,122 @@
+"""Concurrent ``.env`` writers must not clobber each other (#77187).
+
+``save_env_value`` / ``remove_env_value`` do a read-modify-write cycle on
+``~/.hermes/.env``. Without a lock serializing the whole cycle, two concurrent
+writers both snapshot the file and the loser's atomic replace silently drops
+the winner's key.
+
+The race window is widened deterministically through the ``_read_env_lines``
+module seam: a two-party barrier makes both writers snapshot before either
+renames (red on an unlocked base). On a serialized path the second writer cannot
+even read until the first writer's whole cycle completes, so the barrier times
+out, breaks, and both writers proceed one-after-the-other (green).
+"""
+
+from __future__ import annotations
+
+import threading
+import unittest.mock as mock
+
+import pytest
+
+from hermes_cli import config as config_mod
+
+# Barrier timeout: on the serialized (fixed) path the lock holder waits out this
+# window for a second reader that cannot arrive (blocked on the lock). Short
+# enough to keep the suite fast, long enough that a genuinely concurrent second
+# reader on the broken path trips the barrier before it expires.
+_BARRIER_WAIT_SECONDS = 1.0
+_JOIN_TIMEOUT = 20.0
+
+
+def _env_keys(env_path) -> set:
+ keys = set()
+ for line in env_path.read_text(encoding="utf-8-sig").splitlines():
+ stripped = line.strip()
+ if stripped.startswith("export "):
+ stripped = stripped[7:].lstrip()
+ name, sep, _ = stripped.partition("=")
+ if sep:
+ keys.add(name.strip())
+ return keys
+
+
+def race_env_home(tmp_path, monkeypatch):
+ """A temp HERMES_HOME whose .env carries a pre-existing BASE key."""
+ env_path = tmp_path / ".env"
+ env_path.write_text("BASE_KEY=base\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ for leaked in ("RACE_A", "RACE_B"):
+ monkeypatch.delenv(leaked, raising=False)
+ return env_path
+
+
+def _race_two_writers(writer_a, writer_b):
+ """Run two ``.env`` writers concurrently, both entering the read phase together.
+
+ The seam barriers both threads AFTER their read: on an unlocked cycle both
+ are guaranteed to snapshot the same pre-write file before either renames, so
+ the last rename deterministically drops the other writer's key. On a locked
+ cycle the second reader only runs after the first writer finishes, the
+ barrier times out (BrokenBarrierError, swallowed) and writers serialize.
+ """
+ barrier = threading.Barrier(2)
+ original_read = config_mod._read_env_lines
+ errors: list = []
+
+ def read_then_barrier(env_path_arg):
+ lines = original_read(env_path_arg)
+ try:
+ barrier.wait(timeout=_BARRIER_WAIT_SECONDS)
+ except threading.BrokenBarrierError:
+ pass # serialized path: the other writer is behind the file lock
+ return lines
+
+ def run(fn):
+ try:
+ fn()
+ except BaseException as exc: # surfaced via the errors assert below
+ errors.append(exc)
+
+ with mock.patch.object(config_mod, "_read_env_lines", side_effect=read_then_barrier):
+ threads = [
+ threading.Thread(target=run, args=(writer_a,), name="env-writer-a"),
+ threading.Thread(target=run, args=(writer_b,), name="env-writer-b"),
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(_JOIN_TIMEOUT)
+
+ assert not errors, f"writer threads raised: {errors!r}"
+ assert not any(t.is_alive() for t in threads), "writer threads timed out"
+
+
+def test_concurrent_save_env_value_writers_do_not_lose_keys(race_env_home):
+ """Two threads behind a barrier save different keys; ``.env`` must end with
+ BASE plus BOTH new keys — the loser's write must not be clobbered by the
+ winner's stale snapshot (#77187)."""
+ env_path = race_env_home
+ _race_two_writers(
+ lambda: config_mod.save_env_value("RACE_A", "a"),
+ lambda: config_mod.save_env_value("RACE_B", "b"),
+ )
+ keys = _env_keys(env_path)
+ assert keys == {"BASE_KEY", "RACE_A", "RACE_B"}, (
+ f"lost a write to the unlocked read-modify-write race: {keys}")
+
+
+def test_concurrent_remove_and_save_do_not_lose_keys(race_env_home):
+ """A remove racing a save of a DIFFERENT key must neither lose the saved key
+ nor resurrect the removed one: the remove's stale snapshot (which still
+ contains the removed key) must never be the one that lands."""
+ env_path = race_env_home
+ env_path.write_text("BASE_KEY=base\nDOOMED_KEY=old\n", encoding="utf-8")
+ _race_two_writers(
+ lambda: config_mod.remove_env_value("DOOMED_KEY"),
+ lambda: config_mod.save_env_value("RACE_B", "b"),
+ )
+ keys = _env_keys(env_path)
+ assert keys == {"BASE_KEY", "RACE_B"}, (
+ f"remove/save race produced a torn .env: {keys}")