hermes-agent/tests/agent/test_secret_scope_env_cache.py
Teknium be22525da4 fix(secret-scope): .env memo notices a same-size .env edit inside one timestamp tick
load_env_file() memoised the parsed .env on the descriptor's stat identity
(mtime_ns, size, inode, ctime_ns). On a kernel that stamps mtime/ctime from
the coarse (jiffy) clock, an in-place rewrite of the same size inside one
tick leaves all four unchanged, so the cache served the old values. That is
the flake in CI run 39146191939:
test_reload_env_rereads_the_profile_dotenv_for_a_controlled_session saw
{'updated': 0} after .env went from TUI_RELOAD_PROBE=one to =two. The
single-profile /reload calls hermes_cli.config.reload_env() -> load_env() ->
load_env_file().

The memo now keys on the file's exact bytes. Each call still opens and reads
the small file and skips only the decode and parse. Explicit invalidation
(invalidate_env_file_cache / invalidate_env_cache) and the "unreadable file
is never cached" rule are unchanged.

Tests: a unit test collapses file_signature to a constant to simulate the
coarse clock (red before the fix). The gateway test now pins mtime and
asserts same size across the rewrite, so it no longer depends on timing.
2026-10-18 11:06:07 -07:00

99 lines
3.8 KiB
Python

"""The per-path ``load_env_file()`` memo in ``agent.secret_scope``.
``build_profile_secret_scope()`` sits on the gateway's hot paths (every turn, cron fire, MCP/browser
adoption, housekeeping drain) and used to re-read and re-parse the profile ``.env`` on each call.
A stale credential map is a worse failure than a slow one, so the contract under test is: parse once
while the file is unchanged, hand every caller its own dict, and see every real change on disk.
Files are written as bytes: ``Path.write_text`` translates ``\\n`` to ``\\r\\n`` on Windows, which
would break the same-size assertion.
"""
from __future__ import annotations
import os
import pytest
import agent.secret_scope as ss
# Comfortably past the coarsest mtime resolution in common use (FAT32 truncates to two seconds).
_MTIME_STEP_NS = 10_000_000_000
@pytest.fixture(autouse=True)
def _clear_cache():
ss.invalidate_env_file_cache()
yield
ss.invalidate_env_file_cache()
def _count_parses(monkeypatch) -> list:
calls: list = []
real = ss._parse_env_text
monkeypatch.setattr(ss, "_parse_env_text", lambda t: (calls.append(t), real(t))[1])
return calls
def _rewrite_same_size(path, text: str) -> None:
"""Same length, different content: only the mtime distinguishes the versions."""
previous = path.stat()
path.write_bytes(text.encode("utf-8"))
assert path.stat().st_size == previous.st_size
bumped = previous.st_mtime_ns + _MTIME_STEP_NS
os.utime(path, ns=(bumped, bumped))
def test_unchanged_file_is_parsed_once_and_each_caller_gets_its_own_dict(tmp_path, monkeypatch):
env = tmp_path / ".env"
env.write_bytes(b"A=1\nB=2\n")
calls = _count_parses(monkeypatch)
monkeypatch.setattr("hermes_cli.env_loader.get_secret_source_values", lambda home: {"EXT": "vault"})
first = ss.load_env_file(env)
first["INJECTED"] = "must-not-persist" # callers mutate what they get back
for _ in range(5):
assert ss.load_env_file(env) == {"A": "1", "B": "2"}
# The motivating path layers external secrets onto the result; that must not poison the memo.
scope = ss.build_profile_secret_scope(tmp_path)
assert scope["EXT"] == "vault"
assert ss.load_env_file(env) == {"A": "1", "B": "2"}
assert len(calls) == 1, f"expected one parse, got {len(calls)}"
def test_edits_and_deletion_are_seen(tmp_path, monkeypatch):
env = tmp_path / ".env"
env.write_bytes(b"KEY=aaa\n")
calls = _count_parses(monkeypatch)
assert ss.load_env_file(env) == {"KEY": "aaa"}
_rewrite_same_size(env, "KEY=bbb\n")
assert ss.load_env_file(env) == {"KEY": "bbb"}
assert len(calls) == 2
env.unlink()
assert ss.load_env_file(env) == {}
env.write_bytes(b"KEY=ccc\n")
assert ss.load_env_file(env) == {"KEY": "ccc"}
assert len(calls) == 3
def test_same_size_rewrite_inside_one_timestamp_tick_is_seen(tmp_path, monkeypatch):
"""On a kernel stamping mtime/ctime from the coarse (jiffy) clock, an in-place same-size rewrite
in the same tick leaves (mtime, size, inode, ctime) unchanged. Simulate that clock: every stat
identity collides, so only the bytes tell the versions apart (CI run 39146191939, where
``reload.env`` reported ``{'updated': 0}`` after ``.env`` went from ``one`` to ``two``).
"""
monkeypatch.setattr(ss, "file_signature", lambda st: (0, 0, 0, 0), raising=False)
env = tmp_path / ".env"
env.write_bytes(b"TUI_RELOAD_PROBE=one\n")
calls = _count_parses(monkeypatch)
assert ss.load_env_file(env) == {"TUI_RELOAD_PROBE": "one"}
assert ss.load_env_file(env) == {"TUI_RELOAD_PROBE": "one"}
assert len(calls) == 1 # unchanged bytes still skip the parse
env.write_bytes(b"TUI_RELOAD_PROBE=two\n")
assert ss.load_env_file(env) == {"TUI_RELOAD_PROBE": "two"}
assert len(calls) == 2