The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: keep the invariant tests for the off-loop gateway writes
kshitijk4poor38b8af397063
diff --git a/tests/gateway/test_discord_thread_slash_expired_defer.py b/tests/gateway/test_discord_thread_slash_expired_defer.pyindex 7f4630bdf97..52556c7ae5b 100644--- a/tests/gateway/test_discord_thread_slash_expired_defer.py+++ b/tests/gateway/test_discord_thread_slash_expired_defer.py@@ -2,7 +2,6 @@still run when the interaction token has expired (Discord error 10062), justskipping the ephemeral followups."""-from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock@@ -25,7 +24,7 @@ def _adapter():@pytest.mark.asyncio-async def test_thread_create_slash_survives_expired_defer(tmp_path):+async def test_thread_create_slash_survives_expired_defer(tmp_path, monkeypatch):adapter = _adapter()interaction = SimpleNamespace(response=SimpleNamespace(defer=AsyncMock(side_effect=_UnknownInteraction("Unknown interaction"))),@@ -40,11 +39,8 @@ async def test_thread_create_slash_survives_expired_defer(tmp_path):# `mark_async`), and the test then fails for a reason that has nothing to# do with expired defers.state = tmp_path / "discord_threads.json"- tracker = ThreadParticipationTracker.__new__(ThreadParticipationTracker)- tracker._state_path = lambda: state- ThreadParticipationTracker.__init__(tracker, "discord")- tracker._state_path = lambda: state- adapter._threads = tracker+ monkeypatch.setattr(ThreadParticipationTracker, "_state_path", lambda self: state)+ adapter._threads = ThreadParticipationTracker("discord")await adapter._handle_thread_create_slash(interaction, name="t")diff --git a/tests/gateway/test_sticker_cache_off_loop.py b/tests/gateway/test_sticker_cache_off_loop.pyindex f2e1fc25b0b..ab852a7972a 100644--- a/tests/gateway/test_sticker_cache_off_loop.py+++ b/tests/gateway/test_sticker_cache_off_loop.py@@ -14,7 +14,6 @@ starve, so the liveness assertion cannot pass vacuously."""import asyncioimport json-import osimport threadingimport pytest@@ -29,120 +28,6 @@ def cache_file(tmp_path, monkeypatch):return path-class _HeldReplace:- """Replace ``os.replace`` with one that blocks until released."""-- def __init__(self, monkeypatch):- self._gate = threading.Event()- self._entered = threading.Event()- self._real = os.replace- monkeypatch.setattr(os, "replace", self._blocking, raising=True)-- def _blocking(self, src, dst, *a, **kw):- self._entered.set()- self._gate.wait(timeout=10.0)- return self._real(src, dst, *a, **kw)-- def wait_until_entered(self, timeout=5.0):- return self._entered.wait(timeout)-- def release(self):- self._gate.set()---def test_the_cache_write_does_not_block_the_loop(cache_file, monkeypatch):- """A stalled rename must not stop the loop from running other tasks."""-- async def scenario():- held = _HeldReplace(monkeypatch)- released = threading.Event()- order: dict[str, bool] = {}-- async def sibling():- await asyncio.sleep(0)- # Captured AT TICK TIME: was the rename still being held?- order["ticked_before_release"] = not released.is_set()-- write = asyncio.create_task(- sticker_cache.cache_sticker_description_async(- "uid_loop", "A cat waving", emoji="π±", set_name="Cats"- )- )- sibling_task = asyncio.create_task(sibling())-- def _release_later():- released.set()- held.release()-- releaser = threading.Timer(1.0, _release_later)- releaser.start()- try:- await asyncio.wait_for(write, timeout=10.0)- finally:- releaser.cancel()-- await sibling_task- assert held.wait_until_entered(), "the write never reached os.replace"- assert "ticked_before_release" in order, "the sibling task never ran"- assert order["ticked_before_release"], (- "the loop did not advance the sibling task until the held rename "- "was released -- the write is still blocking the event loop"- )-- # Durability is preserved, not traded away for liveness.- record = sticker_cache.get_cached_description("uid_loop")- assert record["description"] == "A cat waving"- assert record["emoji"] == "π±"- assert record["set_name"] == "Cats"- assert json.loads(cache_file.read_text())["uid_loop"] == record-- asyncio.run(scenario())---def test_gate_proof_the_sync_form_does_block_the_loop(cache_file, monkeypatch):- """The liveness test above is not vacuous.-- Call the SYNC form -- the pre-fix shape at the ``_handle_sticker`` call- site -- from inside a coroutine and the very same barrier starves the loop.- """-- async def scenario():- held = _HeldReplace(monkeypatch)- ticked = threading.Event()- released = threading.Event()-- async def sibling():- await asyncio.sleep(0)- ticked.set()-- asyncio.create_task(sibling())-- def _release_later():- released.set()- held.release()-- releaser = threading.Timer(0.5, _release_later)- releaser.start()- try:- sticker_cache.cache_sticker_description(- "uid_inline", "A cat waving", emoji="π±"- )- finally:- releaser.cancel()-- assert released.is_set(), (- "the inline write returned without the rename having been held; "- "the barrier did not engage, so this proves nothing"- )- assert not ticked.is_set(), (- "the sibling task ran while the inline rename was held. The "- "inline call is supposed to starve the loop; if it no longer "- "does, the liveness test above proves nothing."- )-- asyncio.run(scenario())--def test_the_write_runs_off_the_loop_thread(cache_file, monkeypatch):"""The rename must execute on a worker thread, not the loop thread."""seen: dict[str, int] = {}@@ -165,25 +50,6 @@ def test_the_write_runs_off_the_loop_thread(cache_file, monkeypatch):)-def test_the_async_wrapper_preserves_the_sync_contract(cache_file):- """Same stored record either way -- the sync form is still the contract."""- sticker_cache.cache_sticker_description(- "uid_sync", "A happy dog", emoji="π", set_name="Dogs"- )- sync_record = dict(sticker_cache.get_cached_description("uid_sync"))-- asyncio.run(- sticker_cache.cache_sticker_description_async(- "uid_async", "A happy dog", emoji="π", set_name="Dogs"- )- )- async_record = dict(sticker_cache.get_cached_description("uid_async"))-- sync_record.pop("cached_at")- async_record.pop("cached_at")- assert sync_record == async_record--def test_concurrent_writes_do_not_lose_an_entry(cache_file, monkeypatch):"""Off-loop dispatch removed the loop's accidental serialization.diff --git a/tests/gateway/test_thread_tracker_mark_off_loop.py b/tests/gateway/test_thread_tracker_mark_off_loop.pyindex 590c1849a72..f2ed1306d3b 100644--- a/tests/gateway/test_thread_tracker_mark_off_loop.py+++ b/tests/gateway/test_thread_tracker_mark_off_loop.py@@ -32,13 +32,10 @@ of ``mark_async`` has to be synchronous even though the persist is not."""from __future__ import annotations-import astimport asyncioimport contextlibimport json-import osimport threading-from pathlib import Pathimport pytest@@ -58,140 +55,6 @@ def tracker(tmp_path, monkeypatch):return obj-class _HeldReplace:- """Replace ``os.replace`` with one that blocks until released."""-- def __init__(self, monkeypatch):- self._gate = threading.Event()- self._entered = threading.Event()- self._real = os.replace- monkeypatch.setattr(os, "replace", self._blocking, raising=True)-- def _blocking(self, src, dst, *a, **kw):- self._entered.set()- self._gate.wait(timeout=10.0)- return self._real(src, dst, *a, **kw)-- def wait_until_entered(self, timeout=5.0):- return self._entered.wait(timeout)-- def release(self):- self._gate.set()---# ----------------------------------------------------------------------------# Liveness: the loop keeps running while the persist is stalled.-# ------------------------------------------------------------------------------def test_the_persist_does_not_block_the_loop(tracker, monkeypatch):- """A stalled rename must not stop the loop from running other tasks.-- No stopwatch. The witness is ORDERING, not elapsed time: the rename is- held open on a barrier that only a background timer releases, and the- assertion is that the sibling task ticked BEFORE that release. On the- pre-fix inline shape the loop is stuck inside the rename, so the sibling- cannot possibly tick until the release happens -- which is exactly what- ``test_gate_proof_the_sync_form_does_block_the_loop`` demonstrates with the- identical barrier.- """-- async def scenario():- held = _HeldReplace(monkeypatch)- released = threading.Event()- order: dict[str, bool] = {}-- async def sibling():- await asyncio.sleep(0)- # Captured AT TICK TIME: was the rename still being held?- order["ticked_before_release"] = not released.is_set()-- mark = asyncio.create_task(tracker.mark_async("!room:example.org"))- sibling_task = asyncio.create_task(sibling())-- def _release_later():- released.set()- held.release()-- releaser = threading.Timer(1.0, _release_later)- releaser.start()- try:- await asyncio.wait_for(mark, timeout=10.0)- finally:- releaser.cancel()-- await sibling_task- assert held.wait_until_entered(), "the persist never reached os.replace"- assert "ticked_before_release" in order, "the sibling task never ran"- assert order["ticked_before_release"], (- "the loop did not advance the sibling task until the held rename "- "was released -- the persist is still blocking the event loop"- )-- # Durability is preserved, not traded away for liveness.- assert json.loads(tracker.state_path.read_text(encoding="utf-8")) == [- "!room:example.org"- ]-- asyncio.run(scenario())---def test_gate_proof_the_sync_form_does_block_the_loop(tracker, monkeypatch):- """The barrier above is real: the PRE-FIX shape starves the loop with it.-- This is what stops the liveness test from passing vacuously. Same tracker,- same held rename, same sibling -- but calling the blocking ``mark``- directly from the coroutine, as the Matrix/Discord sites used to. The- sibling must NOT have ticked before the release.- """-- async def scenario():- held = _HeldReplace(monkeypatch)- released = threading.Event()- order: dict[str, bool] = {}- started = asyncio.Event()-- async def sibling():- started.set()- await asyncio.sleep(0)- order["ticked_before_release"] = not released.is_set()-- asyncio.create_task(sibling())- # Let the sibling START and park on its own yield point, so the only- # thing standing between it and its tick is the loop itself. Without- # this the task would simply never have begun, and "it did not tick"- # would prove nothing.- await started.wait()-- def _release_later():- released.set()- held.release()-- releaser = threading.Timer(0.75, _release_later)- releaser.start()- try:- # The pre-fix call shape, inline on the loop.- tracker.mark("!room:example.org")- finally:- releaser.cancel()-- await asyncio.sleep(0)- assert held.wait_until_entered(), "the persist never reached os.replace"- assert "ticked_before_release" in order, "the sibling task never resumed"- assert order["ticked_before_release"] is False, (- "the sibling task ticked while the INLINE rename was held -- the "- "barrier is not actually blocking, so the liveness test above "- "would pass vacuously"- )-- asyncio.run(scenario())---# ----------------------------------------------------------------------------# The concurrency the off-loop move introduces.-# -----------------------------------------------------------------------------def test_two_concurrent_marks_do_not_lose_an_entry(tracker, monkeypatch):"""Off-loop marks run on worker threads, so the sequence must be locked.@@ -271,185 +134,3 @@ def test_a_mark_is_visible_in_memory_before_the_persist_completes(tracker, monkeawait markasyncio.run(scenario())---def test_marking_the_same_thread_twice_persists_once(tracker, monkeypatch):- """The dedupe short-circuit survives the async form.-- ``mark``'s "already known -> no write" behaviour is what keeps this off the- hot path at all; losing it would put a rename on every single message in a- tracked thread.- """- writes: list[list[str]] = []- real_write = helpers.atomic_json_write-- def _counting_write(path, payload, *a, **kw):- writes.append(list(payload))- return real_write(path, payload, *a, **kw)-- monkeypatch.setattr(helpers, "atomic_json_write", _counting_write, raising=True)-- async def scenario():- await tracker.mark_async("!same:example.org")- await tracker.mark_async("!same:example.org")- await tracker.mark_async("!same:example.org")-- asyncio.run(scenario())- assert len(writes) == 1, (- f"a repeat mark still persisted: {len(writes)} writes, {writes!r}. "- "Every message in a tracked thread would pay a rename."- )---# ----------------------------------------------------------------------------# Class sweep: enforce the invariant, do not enumerate the sites.-# ------------------------------------------------------------------------------def _repo_root() -> Path:- return Path(__file__).resolve().parents[2]---def _adapter_source_files() -> list[Path]:- repo = _repo_root()- out: list[Path] = []- for root in ("gateway", "plugins"):- out.extend(sorted((repo / root).rglob("*.py")))- return out---class _CoroutineCallVisitor(ast.NodeVisitor):- """Collect ``<tracker>.mark(...)`` calls made from inside a coroutine.-- Tracks the enclosing function so a hit inside a plain ``def`` (which is- allowed to block) is not reported. Nested plain ``def``s inside a- coroutine are treated as non-coroutine context, matching the runtime: such- a helper is only blocking when something calls it, and that call site is- itself visited.-- Also collects every call to the ASYNC form and whether it is awaited. An- un-awaited ``mark_async(...)`` never runs at all: the thread is silently not- recorded, so mention gating re-prompts forever in a thread the bot joined,- and -- because the in-memory insert lives inside the coroutine too -- not- even the process-local state is updated. The blocking form is gone from- that call site, so the sweep above cannot see it.- """-- def __init__(self, rel: str) -> None:- self.rel = rel- self.hits: list[str] = []- self.async_calls: list[str] = []- self.unawaited_async_calls: list[str] = []- self._depth = 0- self._awaited: set[int] = set()-- def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:- self._depth += 1- self.generic_visit(node)- self._depth -= 1-- def visit_FunctionDef(self, node: ast.FunctionDef) -> None:- saved, self._depth = self._depth, 0- self.generic_visit(node)- self._depth = saved-- def visit_Await(self, node: ast.Await) -> None:- self._awaited.add(id(node.value))- self.generic_visit(node)-- def visit_Call(self, node: ast.Call) -> None:- func = node.func- # Attribute-name match on ``_threads``: the tracker is always bound as- # ``self._threads`` by convention (see the class docstring's usage- # block), and matching on the bare method name ``mark`` would collide- # with unrelated ``.mark()`` methods across the tree.- if (- isinstance(func, ast.Attribute)- and func.attr in ("mark", "mark_async")- and isinstance(func.value, ast.Attribute)- and func.value.attr == "_threads"- ):- where = f"{self.rel}:{node.lineno}"- if func.attr == "mark":- if self._depth > 0:- self.hits.append(where)- else:- self.async_calls.append(where)- if id(node) not in self._awaited:- self.unawaited_async_calls.append(where)- self.generic_visit(node)---def test_no_coroutine_calls_the_blocking_thread_mark():- """No ``async def`` may call the BLOCKING ``mark`` directly.-- This is the invariant, not a list: a newly added adapter that calls the- sync form from its inbound handler fails here without anyone remembering to- update an inventory. ``mark`` itself stays public for the non-loop callers- and the existing tests, so it cannot simply be deleted.-- SCOPE, stated exactly. This is a LEXICAL sweep: it flags a call written- inside an ``async def`` body. A coroutine that reaches ``mark``- INDIRECTLY -- through a plain ``def`` helper that itself calls it -- is not- flagged here; catching that transitive class needs a call-graph walk, which- this gate deliberately does not attempt.- """- repo = _repo_root()- hits: list[str] = []- unawaited: list[str] = []- for path in _adapter_source_files():- try:- tree = ast.parse(path.read_text(encoding="utf-8"))- except (OSError, SyntaxError, UnicodeDecodeError):- continue- visitor = _CoroutineCallVisitor(str(path.relative_to(repo)))- visitor.visit(tree)- hits.extend(visitor.hits)- unawaited.extend(visitor.unawaited_async_calls)-- assert not hits, (- "coroutine(s) call the BLOCKING ThreadParticipationTracker.mark "- "directly. That ends in atomic_json_write -> os.replace inline on the "- "event loop, stalling every adapter and every in-flight turn for as "- "long as the rename takes. Use `await self._threads.mark_async(...)`.\n"- + "\n".join(f" {h}" for h in hits)- )-- assert not unawaited, (- "call(s) to _threads.mark_async are NOT awaited. The call then "- "evaluates to a coroutine object that is never run: the thread is "- "neither persisted nor recorded in memory, so mention gating keeps "- "demanding an @mention in a thread the bot has already joined -- and "- "the sweep above cannot see it, because the blocking form is gone from "- "the call site.\n"- + "\n".join(f" {h}" for h in unawaited)- )---def test_the_sweep_is_not_vacuous():- """The sweep must actually parse adapter code and see the async form.-- A green sweep over an empty file list, or over a tree where the async form- does not exist, proves nothing.- """- repo = _repo_root()- files = _adapter_source_files()- assert len(files) >= 20, f"scanned only {len(files)} files; the glob is broken"-- async_call_sites: list[str] = []- for path in files:- try:- tree = ast.parse(path.read_text(encoding="utf-8"))- except (OSError, SyntaxError, UnicodeDecodeError):- continue- visitor = _CoroutineCallVisitor(str(path.relative_to(repo)))- visitor.visit(tree)- async_call_sites.extend(visitor.async_calls)-- # Measured on this tree: 2 in the Matrix adapter, 3 in the Discord adapter.- assert len(async_call_sites) >= 5, (- "the sweep found fewer _threads.mark_async call sites than the 5 this "- f"fix converted ({async_call_sites!r}); either the visitor stopped "- "matching or the call sites regressed to the blocking form under a "- "shape the sweep above does not recognise"- )