The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tests): gateway adapter-guard cache no longer fails healthy files with a blank ERROR under the parallel runner
Teknium8c71fd78d5a0
diff --git a/tests/gateway/conftest.py b/tests/gateway/conftest.pyindex d485d4ab2fe..78759616f48 100644--- a/tests/gateway/conftest.py+++ b/tests/gateway/conftest.py@@ -32,6 +32,7 @@ incident."""import ast+import osimport sysfrom pathlib import Pathfrom unittest.mock import MagicMock@@ -504,6 +505,10 @@ def pytest_configure(config):cache_dir.mkdir(parents=True, exist_ok=True)# Evict stale cache entries from previous fingerprints (best-effort).+ # ``.tmp-gw-adapter-guard-*`` staging files (see+ # ``_write_guard_cache_atomic``) deliberately do NOT match these globs:+ # a sibling process evicting mid-publish must never unlink a temp file+ # between its write and its ``os.replace``.try:for old in cache_dir.glob("gw-adapter-guard-*"):if old.name != f"gw-adapter-guard-{fp}":@@ -517,6 +522,15 @@ def pytest_configure(config):# Use filelock to ensure only one process scans at a time.# Concurrent subprocesses all hit pytest_configure simultaneously;# without a lock they'd all find no cache and all run the scan.+ #+ # NOTE: filelock is NOT in CI's dependency closure (`uv sync --extra all+ # --extra dev ...` does not pull it), so on CI the _NoLock fallback is+ # what actually runs. Correctness therefore cannot depend on the lock:+ # the cache write must be atomic and the read must tolerate a+ # not-yet-visible cache. Before the atomic-write fix, a reader could+ # observe a sibling's ``write_text`` mid-truncate, read "" and raise+ # ``UsageError("")`` — the empty ``ERROR:`` flake that hit+ # tests/gateway/relay/* files under the 96-way per-file runner.try:from filelock import FileLocklock = FileLock(str(lock_file), timeout=120)@@ -531,10 +545,10 @@ def pytest_configure(config):lock = _NoLock()with lock:- if cache_file.exists():- cached = cache_file.read_text(encoding="utf-8")- if cached == "clean":- return+ cached = _read_guard_cache(cache_file)+ if cached == "clean":+ return+ if cached is not None:raise pytest.UsageError(cached)# Slow path: this process is the first to acquire the lock.@@ -547,8 +561,53 @@ def pytest_configure(config):+ "\n\n"+ _GUARD_HINT)- cache_file.write_text(msg, encoding="utf-8")+ _write_guard_cache_atomic(cache_file, msg)raise pytest.UsageError(msg)else:- cache_file.write_text("clean", encoding="utf-8")+ _write_guard_cache_atomic(cache_file, "clean")+++def _read_guard_cache(cache_file: Path) -> str | None:+ """Read the guard cache, treating unreadable/empty content as a miss.++ Returns the cached text, or ``None`` when the cache should be treated as+ absent (missing file, concurrent delete, or empty content). An empty or+ vanished file is NEVER a violation — before this guard existed, a reader+ racing a sibling's non-atomic write raised ``UsageError("")``, failing a+ perfectly healthy test file with a blank ``ERROR:`` line.+ """+ try:+ cached = cache_file.read_text(encoding="utf-8")+ except (FileNotFoundError, OSError):+ return None+ if not cached.strip():+ return None+ return cached+++def _write_guard_cache_atomic(cache_file: Path, content: str) -> None:+ """Publish the guard cache atomically (write-temp + ``os.replace``).++ ``Path.write_text`` opens with truncation, so concurrent readers can see+ an empty or partial file. ``os.replace`` makes the new content appear+ all-at-once under the final name — readers see either the old state+ (miss → they scan too, harmless) or the complete verdict, never a+ torn write. This must hold WITHOUT the filelock, which CI doesn't+ install.++ The staging name starts with ``.tmp-`` so it can never match the stale+ eviction globs (``gw-adapter-guard-*`` / ``.gw-adapter-guard-*.lock``);+ otherwise a sibling's eviction pass could unlink the temp between the+ write and the ``os.replace``.+ """+ tmp = cache_file.with_name(f".tmp-{cache_file.name}.{os.getpid()}")+ try:+ tmp.write_text(content, encoding="utf-8")+ os.replace(tmp, cache_file)+ except OSError:+ # Best-effort cache: losing it costs a rescan, never correctness.+ try:+ tmp.unlink(missing_ok=True)+ except OSError:+ passdiff --git a/tests/gateway/test_adapter_guard_cache_race.py b/tests/gateway/test_adapter_guard_cache_race.pynew file mode 100644index 00000000000..286be3d496b--- /dev/null+++ b/tests/gateway/test_adapter_guard_cache_race.py@@ -0,0 +1,86 @@+"""Regression tests for the adapter-guard cache race (empty ``ERROR:`` flake).++CI runs the suite as ~96 concurrent per-file pytest subprocesses and does NOT+install ``filelock``, so ``tests/gateway/conftest.py::pytest_configure`` runs+its cache read/write completely lock-free there. The original code published+the verdict with ``Path.write_text`` (open-truncate-write): a sibling process+reading between the truncate and the write saw an empty file and raised+``pytest.UsageError("")`` — surfacing in the flaky-retry frames as a bare+``ERROR:`` with no message on healthy ``tests/gateway/relay/*`` files+(e.g. CI runs 32930243538, 32932008269 on 2026-08-26).++These tests pin the two properties the fix relies on:++1. ``_read_guard_cache`` treats empty/vanished cache files as a miss, never+ as a violation verdict.+2. ``_write_guard_cache_atomic`` publishes via ``os.replace`` from a staging+ name that the stale-fingerprint eviction globs cannot match.+"""++import os++from tests.gateway import conftest as gw_conftest+++class TestReadGuardCache:+ def test_missing_file_is_a_miss(self, tmp_path):+ assert gw_conftest._read_guard_cache(tmp_path / "absent") is None++ def test_empty_file_is_a_miss_not_a_violation(self, tmp_path):+ """A torn/empty cache must be treated as absent. Before the fix this+ exact state produced ``UsageError("")`` — the empty ``ERROR:`` flake."""+ f = tmp_path / "gw-adapter-guard-cafe"+ f.write_text("", encoding="utf-8")+ assert gw_conftest._read_guard_cache(f) is None++ def test_whitespace_only_is_a_miss(self, tmp_path):+ f = tmp_path / "gw-adapter-guard-cafe"+ f.write_text("\n \n", encoding="utf-8")+ assert gw_conftest._read_guard_cache(f) is None++ def test_clean_and_violation_content_round_trip(self, tmp_path):+ f = tmp_path / "gw-adapter-guard-cafe"+ f.write_text("clean", encoding="utf-8")+ assert gw_conftest._read_guard_cache(f) == "clean"+ f.write_text("violation: bad import", encoding="utf-8")+ assert gw_conftest._read_guard_cache(f) == "violation: bad import"+++class TestWriteGuardCacheAtomic:+ def test_publishes_content_under_final_name(self, tmp_path):+ f = tmp_path / "gw-adapter-guard-cafe"+ gw_conftest._write_guard_cache_atomic(f, "clean")+ assert f.read_text(encoding="utf-8") == "clean"++ def test_no_staging_file_left_behind(self, tmp_path):+ cache_dir = tmp_path / "cache"+ cache_dir.mkdir()+ f = cache_dir / "gw-adapter-guard-cafe"+ gw_conftest._write_guard_cache_atomic(f, "clean")+ leftovers = [p.name for p in cache_dir.iterdir() if p.name != f.name]+ assert leftovers == []++ def test_staging_name_never_matches_eviction_globs(self, tmp_path):+ """The eviction pass in pytest_configure unlinks+ ``gw-adapter-guard-*`` and ``.gw-adapter-guard-*.lock`` entries for+ other fingerprints. The staging file must be invisible to both globs,+ or a sibling's eviction could delete it between write and replace."""+ f = tmp_path / "gw-adapter-guard-cafe"+ staging = f.with_name(f".tmp-{f.name}.{os.getpid()}")+ staging.write_text("in flight", encoding="utf-8")+ try:+ evictable = set(tmp_path.glob("gw-adapter-guard-*")) | set(+ tmp_path.glob(".gw-adapter-guard-*.lock")+ )+ assert staging not in evictable+ finally:+ staging.unlink(missing_ok=True)++ def test_overwrite_is_all_or_nothing(self, tmp_path):+ """os.replace swaps the whole file: after any successful publish the+ content is complete, never a truncated prefix of the new verdict."""+ f = tmp_path / "gw-adapter-guard-cafe"+ gw_conftest._write_guard_cache_atomic(f, "clean")+ long_msg = "violation " * 5000+ gw_conftest._write_guard_cache_atomic(f, long_msg)+ assert f.read_text(encoding="utf-8") == long_msg