Skip to content

The agent that grows with you

Code health blocks new wall-clock sleeps in tests (HX013), adds a shared wait_until helper (#136644)

Teknium74f77ab9b04c
diff --git a/scripts/code_health/config.py b/scripts/code_health/config.py
index de0152ab1b9..e52dccd3efa 100644
--- a/scripts/code_health/config.py
+++ b/scripts/code_health/config.py
@@ -54,6 +54,7 @@ class Rule:
source: str # "ruff" | "ast" | "regex"
exclude: tuple[str, ...] = TESTS
blocking: bool = True
+ include: tuple[str, ...] = () # when set, the rule applies only to these paths
pattern_id: str = "" # regex rules: id in scripts/ci/profile_scope_patterns.json
@@ -139,6 +140,14 @@ RULES: tuple[Rule, ...] = (
# Structure.
Rule("HX011", "if/elif ladder on one name", "use a dict/table -> handler (`_SLASH_DISPATCH`"
" is the shape)", "ast", exclude=()),
+ # Tests: a fixed delay is a race against the runner's load (the usual flake).
+ Rule("HX013", "wall-clock sleep in a test", "wait for the condition, not the clock: an"
+ " Event the code under test sets (`threading.Event` / `asyncio.Event`, `.wait(timeout=)`),"
+ " or poll with `tests.waiting.wait_until(predicate, timeout=...)` (`async_wait_until` in a"
+ " coroutine; a poll loop's interval under a deadline or a `range(n)` bound passes); a stand-in that must hang"
+ " blocks on an Event the test sets at teardown."
+ " `sleep(0)` to yield is fine. A delay that IS the behaviour under test takes"
+ " `# health: allow HX013 -- <why>`", "ast", include=TESTS, exclude=()),
)
RULES_BY_ID = {rule.id: rule for rule in RULES}
@@ -151,6 +160,8 @@ def _matches(path: str, globs: tuple[str, ...]) -> bool:
def rule_applies(rule: Rule, path: str) -> bool:
+ if rule.include and not _matches(path, rule.include):
+ return False
return not _matches(path, rule.exclude)
diff --git a/scripts/code_health/py_ast.py b/scripts/code_health/py_ast.py
new file mode 100644
index 00000000000..8e3d0636ff7
--- /dev/null
+++ b/scripts/code_health/py_ast.py
@@ -0,0 +1,67 @@
+"""AST helpers shared by the HX checkers (``py_rules`` and its ``py_rules_*`` siblings).
+
+A leaf module: it imports nothing from the engine, so every checker module can use it without a
+cycle.
+"""
+
+from __future__ import annotations
+
+import ast
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+
+_FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
+
+
+@dataclass
+class Ctx:
+ known_env: set[str] = field(default_factory=set)
+
+
+def _dotted(node: ast.AST) -> str:
+ """``os.environ.get`` for an Attribute chain, ``""`` for anything else."""
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+ if isinstance(node, ast.Call):
+ inner = _dotted(node.func)
+ return ".".join([f"{inner}()", *reversed(parts)]) if inner else ""
+ return ""
+
+
+def _call_name(call: ast.Call) -> str:
+ return _dotted(call.func)
+
+
+def _deferred_parts(node: ast.AST) -> list[ast.AST] | None:
+ """For a node whose evaluation defers part of itself, the parts that run NOW; else None.
+
+ A lambda/def runs only its defaults and decorators when evaluated; a generator expression
+ runs only its first iterable (the element, conditions and later loops run on consumption).
+ Comprehensions and class bodies run immediately, so they are not deferred.
+ """
+ if isinstance(node, ast.Lambda):
+ return [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]
+ if isinstance(node, _FUNCS):
+ defaults = [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]
+ return [*node.decorator_list, *defaults]
+ if isinstance(node, ast.GeneratorExp):
+ return [node.generators[0].iter]
+ return None
+
+
+def _eager(node: ast.AST) -> Iterator[ast.AST]:
+ """Every node evaluated when ``node`` is evaluated (or a statement executes), root included."""
+ stack = [node]
+ while stack:
+ current = stack.pop()
+ parts = _deferred_parts(current)
+ if parts is not None:
+ stack.extend(parts)
+ continue
+ yield current
+ stack.extend(ast.iter_child_nodes(current))
diff --git a/scripts/code_health/py_rules.py b/scripts/code_health/py_rules.py
index c0358b609b0..f53a46c33c4 100644
--- a/scripts/code_health/py_rules.py
+++ b/scripts/code_health/py_rules.py
@@ -13,7 +13,9 @@ from collections.abc import Callable, Iterable, Iterator
from dataclasses import dataclass, field
import itertools
-_FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef)
+from scripts.code_health.py_ast import _FUNCS, Ctx, _call_name, _deferred_parts, _dotted, _eager
+from scripts.code_health.py_rules_sleep import wall_clock_sleep
+
_CAPTURE_CALLS = {
"get_hermes_home",
"display_hermes_home",
@@ -36,11 +38,6 @@ _SUBPROCESS_WAITS = {"run", "call", "check_call", "check_output"}
_SHELL_IDENTITY = ("pgrep -f", "ps aux", "ps -ef", "ps -eo")
-@dataclass
-class Ctx:
- known_env: set[str] = field(default_factory=set)
-
-
@dataclass
class _Scope:
"""One lexical scope's bindings: names an import binds, and names anything else binds."""
@@ -220,25 +217,6 @@ def canonical_tree(tree: ast.Module) -> ast.Module:
return ast.fix_missing_locations(_Spell().visit(tree))
-def _dotted(node: ast.AST) -> str:
- """``os.environ.get`` for an Attribute chain, ``""`` for anything else."""
- parts: list[str] = []
- while isinstance(node, ast.Attribute):
- parts.append(node.attr)
- node = node.value
- if isinstance(node, ast.Name):
- parts.append(node.id)
- return ".".join(reversed(parts))
- if isinstance(node, ast.Call):
- inner = _dotted(node.func)
- return ".".join([f"{inner}()", *reversed(parts)]) if inner else ""
- return ""
-
-
-def _call_name(call: ast.Call) -> str:
- return _dotted(call.func)
-
-
def _str_arg(call: ast.Call, index: int = 0) -> str | None:
if len(call.args) > index:
arg = call.args[index]
@@ -289,36 +267,6 @@ def _env_write_names(node: ast.AST) -> list[str]:
return []
-def _deferred_parts(node: ast.AST) -> list[ast.AST] | None:
- """For a node whose evaluation defers part of itself, the parts that run NOW; else None.
-
- A lambda/def runs only its defaults and decorators when evaluated; a generator expression
- runs only its first iterable (the element, conditions and later loops run on consumption).
- Comprehensions and class bodies run immediately, so they are not deferred.
- """
- if isinstance(node, ast.Lambda):
- return [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]
- if isinstance(node, _FUNCS):
- defaults = [d for d in (*node.args.defaults, *node.args.kw_defaults) if d is not None]
- return [*node.decorator_list, *defaults]
- if isinstance(node, ast.GeneratorExp):
- return [node.generators[0].iter]
- return None
-
-
-def _eager(node: ast.AST) -> Iterator[ast.AST]:
- """Every node evaluated when ``node`` is evaluated (or a statement executes), root included."""
- stack = [node]
- while stack:
- current = stack.pop()
- parts = _deferred_parts(current)
- if parts is not None:
- stack.extend(parts)
- continue
- yield current
- stack.extend(ast.iter_child_nodes(current))
-
-
def _hermes_home_path(text: str, prefix: str = "") -> bool:
"""``text`` (after ``prefix``) starts with the exact ``.hermes`` path component, so
``.hermes/x`` matches and ``.hermes-profile-exports`` does not."""
@@ -925,4 +873,5 @@ CHECKERS: dict[str, Callable[[ast.Module, Ctx], Iterable[int]]] = {
"HX010": bool_of_env,
"HX011": elif_ladder,
"HX012": raw_thread,
+ "HX013": wall_clock_sleep,
}
diff --git a/scripts/code_health/py_rules_sleep.py b/scripts/code_health/py_rules_sleep.py
new file mode 100644
index 00000000000..38dfe436abd
--- /dev/null
+++ b/scripts/code_health/py_rules_sleep.py
@@ -0,0 +1,243 @@
+"""HX013: a wall-clock sleep in a test (registered in ``py_rules.CHECKERS``).
+
+A fixed delay is a race against the runner's load. The one sleep that is not is the interval of
+a loop that polls a condition under a bound, so the poll-shape analysis lives here too.
+"""
+
+from __future__ import annotations
+
+import ast
+from collections.abc import Iterable, Iterator
+
+from scripts.code_health.py_ast import _FUNCS, Ctx, _call_name, _dotted, _eager
+
+# Sleeps that block on the wall clock -> keyword names of their delay (positional slot 0).
+_SLEEPS = {
+ "time.sleep": ("secs", "seconds"),
+ "asyncio.sleep": ("delay",),
+ "anyio.sleep": ("delay",),
+ "trio.sleep": ("seconds",),
+ # a fresh Event nobody can set is a sleep spelled differently
+ "threading.Event().wait": ("timeout",),
+}
+_LOOPS = (ast.While, ast.For, ast.AsyncFor)
+
+
+def _delay(call: ast.Call, names: tuple[str, ...]) -> ast.expr | None:
+ if call.args:
+ return call.args[0]
+ return next((kw.value for kw in call.keywords if kw.arg in names), None)
+
+
+def _zero(node: ast.expr | None) -> bool:
+ """A literal ``0`` / ``0.0``: a scheduler yield, not a delay (``False`` is not a delay)."""
+ return (isinstance(node, ast.Constant) and type(node.value) in (int, float)
+ and node.value == 0)
+
+
+_CLOCKS = {"time.monotonic", "time.time", "time.perf_counter", "time.monotonic_ns", "time.time_ns"}
+
+
+def _reads_clock(node: ast.AST, clocks: frozenset[str] = frozenset()) -> bool:
+ """A wall-clock read: ``time.monotonic()`` and friends, an event loop's ``.time()``, or a
+ local in ``clocks`` (every binding of it is derived from one: ``end = time.monotonic() + 5``)."""
+ return any((isinstance(inner, ast.Name) and inner.id in clocks)
+ or (isinstance(inner, ast.Call) and _clock_call(inner)) for inner in _eager(node))
+
+
+def _clock_call(call: ast.Call) -> bool:
+ name = _call_name(call)
+ return name in _CLOCKS or name.endswith(("loop().time", "loop.time"))
+
+
+def _duration(node: ast.AST) -> bool:
+ """A plain number or a name for one (``timeout``, ``self.timeout``), or arithmetic on them."""
+ if isinstance(node, ast.BinOp):
+ return _duration(node.left) and _duration(node.right)
+ if isinstance(node, ast.UnaryOp):
+ return _duration(node.operand)
+ if isinstance(node, ast.Attribute):
+ name = _dotted(node) # ``self.timeout``, not ``path.stat().st_mtime``
+ return bool(name) and "()" not in name
+ return isinstance(node, (ast.Constant, ast.Name))
+
+
+def _clock_value(node: ast.AST, clocks: frozenset[str]) -> bool:
+ """A time value: a clock call, a clock local, or one plus/minus a duration or another time
+ (``time.monotonic() + timeout``). ``time.time() - path.stat().st_mtime`` is an age, not a time."""
+ if isinstance(node, ast.BinOp) and isinstance(node.op, (ast.Add, ast.Sub)):
+ left, right = _clock_value(node.left, clocks), _clock_value(node.right, clocks)
+ return (left or right) and (left or _duration(node.left)) and (right or _duration(node.right))
+ if isinstance(node, ast.Name):
+ return node.id in clocks
+ return isinstance(node, ast.Call) and _clock_call(node)
+
+
+def _clock_only(leaf: ast.expr, clocks: frozenset[str]) -> bool:
+ """A test operand that only watches the clock: it reads one and calls nothing else
+ (``time.monotonic() < self.end``, ``time.time() - t["at"] < 0.5``). A call to anything but a
+ clock is observed state (``time.time() - path.stat().st_mtime > 5``). Fails closed: an
+ attribute compared with the clock (``obj.cooldown_until <= time.monotonic()``) stays clock-only,
+ since a stored timestamp looks the same; poll such state through a predicate instead."""
+ if not _reads_clock(leaf, clocks):
+ return False
+ stack: list[ast.AST] = [leaf]
+ while stack:
+ node = stack.pop()
+ if isinstance(node, ast.Call) and _clock_call(node):
+ continue # ``asyncio.get_event_loop().time()`` is one clock read
+ if isinstance(node, (ast.Call, ast.Await, ast.Yield, ast.YieldFrom)):
+ return False
+ stack.extend(ast.iter_child_nodes(node))
+ return True
+
+
+def _own(scope: ast.AST) -> Iterator[ast.AST]:
+ """Nodes of ``scope`` outside the defs, lambdas and classes nested in it."""
+ stack = list(ast.iter_child_nodes(scope))
+ while stack:
+ node = stack.pop()
+ yield node
+ if not isinstance(node, (*_FUNCS, ast.Lambda, ast.ClassDef)):
+ stack.extend(ast.iter_child_nodes(node))
+
+
+def _clock_names(scope: ast.AST) -> frozenset[str]:
+ """Locals of ``scope`` whose every binding assigns a time value (``_clock_value``; a
+ constant start value aside): ``end = time.monotonic() + 5``, ``now =
+ loop.time()``. A name also bound any other way (parameter, loop target, tuple unpacking)
+ is not; ``+=`` keeps what it was."""
+ plain: dict[int, ast.AST] = {}
+ nodes = list(_own(scope))
+ for node in nodes:
+ if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)) and node.value is not None:
+ for target in node.targets if isinstance(node, ast.Assign) else [node.target]:
+ plain[id(target)] = node.value
+ augmented = {id(node.target) for node in nodes if isinstance(node, ast.AugAssign)}
+ values: dict[str, list[ast.AST | None]] = {}
+ for node in nodes:
+ if isinstance(node, ast.arg):
+ values.setdefault(node.arg, []).append(None)
+ elif isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store) and id(node) not in augmented:
+ values.setdefault(node.id, []).append(plain.get(id(node)))
+ clocks: frozenset[str] = frozenset()
+ while True:
+ grown = frozenset(name for name, found in values.items() if all(
+ isinstance(v, ast.Constant) or (v is not None and _clock_value(v, clocks)) for v in found)
+ and not all(isinstance(v, ast.Constant) for v in found))
+ if grown == clocks:
+ return clocks
+ clocks = grown
+
+
+def _turns_on_condition(test: ast.expr, value: bool, clocks: frozenset[str]) -> bool:
+ """Whether ``test`` can become ``value`` on something other than the clock.
+
+ Only an operand that is neither a constant nor clock-only (``_clock_only``) is a condition, so
+ ``time.monotonic() < a and time.monotonic() < b`` only waits. ``or`` becomes true when any
+ operand does but false only when all do (``and`` the reverse), so a ``while not done() or
+ time.monotonic() < end`` test still waits out the clock.
+ """
+ if isinstance(test, ast.UnaryOp) and isinstance(test.op, ast.Not):
+ return _turns_on_condition(test.operand, not value, clocks)
+ if isinstance(test, ast.BoolOp):
+ parts = [_turns_on_condition(operand, value, clocks) for operand in test.values]
+ return any(parts) if isinstance(test.op, ast.Or) == value else all(parts)
+ return not isinstance(test, ast.Constant) and not _clock_only(test, clocks)
+
+
+def _blocks(stmt: ast.stmt) -> Iterator[list[ast.stmt]]:
+ """The statement lists a non-loop, non-``if`` compound statement runs in its own frame."""
+ for name in ("body", "orelse", "finalbody"):
+ yield getattr(stmt, name, None) or []
+ for part in (*getattr(stmt, "handlers", ()), *getattr(stmt, "cases", ())):
+ yield part.body
+
+
+def _exits_on_condition(body: list[ast.stmt], clocks: frozenset[str], conditioned: bool = False,
+ own: bool = True) -> bool:
+ """A ``break`` that ends THIS loop, or a ``return``, in a branch taken on a non-clock
+ condition. A ``break`` in a nested loop's body ends that loop (``own=False``), while one in
+ its ``else:`` is ours again; nested defs and classes run elsewhere and are skipped."""
+ for stmt in body:
+ if isinstance(stmt, ast.Return) or (own and isinstance(stmt, ast.Break)):
+ if conditioned:
+ return True
+ elif isinstance(stmt, ast.If):
+ branches = ((stmt.body, True), (stmt.orelse, False))
+ if any(_exits_on_condition(block, clocks, conditioned or _turns_on_condition(stmt.test, taken, clocks),
+ own) for block, taken in branches):
+ return True
+ elif isinstance(stmt, _LOOPS):
+ if (_exits_on_condition(stmt.body, clocks, conditioned, own=False)
+ or _exits_on_condition(stmt.orelse, clocks, conditioned, own)):
+ return True
+ elif isinstance(stmt, (ast.Try, ast.TryStar)) and stmt.handlers:
+ # the try body's exit is taken only when nothing raised: `try: return probe()` retries
+ probes = any(isinstance(node, ast.Call) and _call_name(node) not in _SLEEPS
+ for part in stmt.body for node in _eager(part))
+ if (_exits_on_condition(stmt.body, clocks, conditioned or probes, own)
+ or any(_exits_on_condition(block, clocks, conditioned, own) for block in _blocks(stmt))):
+ return True
+ elif not isinstance(stmt, (*_FUNCS, ast.ClassDef)):
+ if any(_exits_on_condition(block, clocks, conditioned, own) for block in _blocks(stmt)):
+ return True
+ return False
+
+
+def _deadline_poll(loop: ast.AST, clocks: frozenset[str]) -> bool:
+ """A loop polling a condition under a bound: a ``while`` that reads a clock and can end on
+ the condition, or ``for _ in range(n)`` that can (n rounds bound it; load only stretches
+ them). ``while time.monotonic() < end: sleep(.1)`` alone is a fixed delay."""
+ if isinstance(loop, ast.For):
+ bounded = isinstance(loop.iter, ast.Call) and _call_name(loop.iter) == "range"
+ return bounded and _exits_on_condition(loop.body, clocks)
+ if not isinstance(loop, ast.While):
+ return False
+ clock = _reads_clock(loop.test, clocks) or any(_reads_clock(stmt, clocks) for stmt in loop.body)
+ return clock and (_turns_on_condition(loop.test, False, clocks) or _exits_on_condition(loop.body, clocks))
+
+
+def _sleep_loops(tree: ast.Module) -> Iterator[tuple[ast.Call, ast.AST | None, ast.AST]]:
+ """Each call in ``tree`` with the loop whose BODY runs it in the same function (or None),
+ and that function (or the module). A loop's ``else:``, ``for`` iterable and ``while`` test
+ run outside its body, so they belong to the enclosing loop."""
+ stack: list[tuple[ast.AST, ast.AST | None, ast.AST]] = [(tree, None, tree)]
+ while stack:
+ node, loop, scope = stack.pop()
+ body = {id(stmt) for stmt in node.body} if isinstance(node, _LOOPS) else set()
+ for child in ast.iter_child_nodes(node):
+ here = node if id(child) in body else loop
+ if isinstance(child, ast.Call):
+ yield child, here, scope
+ if isinstance(child, (*_FUNCS, ast.Lambda)):
+ stack.append((child, None, child))
+ else:
+ stack.append((child, here, scope))
+
+
+def wall_clock_sleep(tree: ast.Module, ctx: Ctx) -> Iterable[int]:
+ """``time.sleep(x)`` / ``asyncio.sleep(x)`` (any alias) with ``x`` not a literal zero,
+ unless it is the interval of a loop polling a condition under a deadline or round bound.
+
+ Every other non-zero delay counts, however small: the sub-10 ms ones on main are poll
+ intervals without a deadline and timestamp-separation hacks, which a Windows runner's
+ ~15.6 ms clock already breaks. A non-literal delay counts too.
+ """
+ clocks: dict[int, frozenset[str]] = {}
+ for node, loop, scope in _sleep_loops(tree):
+ names = _SLEEPS.get(_call_name(node))
+ if names is None:
+ continue
+ delay = _delay(node, names)
+ if names == ("timeout",) and (delay is None or (
+ isinstance(delay, ast.Constant) and delay.value is None)):
+ continue # an Event wait without a deadline hangs; it does not sleep
+ if _zero(delay):
+ continue
+ if loop is not None:
+ if id(scope) not in clocks:
+ clocks[id(scope)] = _clock_names(scope)
+ if _deadline_poll(loop, clocks[id(scope)]):
+ continue
+ yield node.lineno
diff --git a/tests/AGENTS.md b/tests/AGENTS.md
index 175ba94d361..db77526fb73 100644
--- a/tests/AGENTS.md
+++ b/tests/AGENTS.md
@@ -32,7 +32,9 @@ scripts/run_tests.sh -v --tb=long # pytest flags pass thro
`HERMES_TEST_FILE_RETRIES=0` disables); a worker killed by signal or the file timeout is never
retried (relaunching a runaway doubles the damage). Pass-on-retry is green but printed under `⚠ FLAKY`
with both outputs — a bug to fix, not noise. Timing tests must not assume a quiet runner:
- wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)` races.
+ wall-clock bounds ≥ 2s, event-based sync, no `assert not _wait_until(...)` races. A new
+ non-zero `time.sleep`/`asyncio.sleep` in a test fails the ratchet (HX013): wait on an Event or
+ poll with `tests.waiting.wait_until` / `async_wait_until`.
- **Placement mirrors the source tree.** A test lives in `tests/<top-level source dir>/` (`tests/hermes_cli/`,
`tests/agent/`, `tests/hermes_state/`, `tests/gateway/relay/`, ...); installer/updater script tests
under `tests/scripts/{install,desktop_update}/`. Only tests of root-level modules (`batch_runner`,
diff --git a/tests/scripts/test_code_health_sleep_rule.py b/tests/scripts/test_code_health_sleep_rule.py
new file mode 100644
index 00000000000..c581e3e9b67
--- /dev/null
+++ b/tests/scripts/test_code_health_sleep_rule.py
@@ -0,0 +1,228 @@
+"""HX013: a new wall-clock sleep in a test blocks; existing ones are grandfathered (moved code keeps
+its debt) and the shared ``tests.waiting`` helper is the compliant way to wait."""
+
+from __future__ import annotations
+
+import ast
+import asyncio
+import threading
+
+import pytest
+
+from scripts.code_health.config import RULES_BY_ID, rule_applies
+from scripts.code_health.py_rules import CHECKERS, Ctx, canonical_tree
+from tests.scripts.test_code_health import _commit, _repo, _verdict
+from tests.waiting import async_wait_until, wait_until
+
+
+def _hits(src: str) -> list[int]:
+ return sorted(set(CHECKERS["HX013"](canonical_tree(ast.parse(src)), Ctx())))
+
+
[email protected]("src, flagged", [
+ ("import time\ntime.sleep(0.5)\n", True),
+ ("import time as t\nt.sleep(0.01)\n", True),
+ ("from time import sleep\nsleep(1)\n", True),
+ ("from time import sleep as nap\nnap(secs=2)\n", True),
+ ("import asyncio\nasync def f():\n await asyncio.sleep(0.05)\n", True),
+ ("from asyncio import sleep\nasync def f():\n await sleep(3600)\n", True),
+ ("import asyncio\ntask = asyncio.create_task(asyncio.sleep(60))\n", True),
+ ("import time\ndef f(interval):\n time.sleep(interval)\n", True), # a sleep whatever the value
+ # a loop that only waits out the clock, or polls with no deadline, is still a fixed delay
+ ("import time\nend = time.monotonic() + 2\nwhile time.monotonic() < end:\n time.sleep(0.1)\n",
+ True),
+ ("import time\nwhile not done():\n time.sleep(0.01)\n", True),
+ ("import time\nend = time.monotonic() + 2\nwhile True:\n time.sleep(1)\n"
+ " if time.monotonic() > end:\n break\n", True),
+ # ... but the interval of a poll under a deadline is the compliant shape
+ ("import time\nend = time.monotonic() + 5\nwhile not done() and time.monotonic() < end:\n"
+ " time.sleep(0.05)\n", False),
+ ("import time\ndef w(p):\n end = time.monotonic() + 5\n while time.monotonic() < end:\n"
+ " if p():\n return True\n time.sleep(0.5)\n", False),
+ ("import asyncio\nasync def w(p):\n loop = asyncio.get_running_loop()\n end = loop.time() + 5\n"
+ " while not p():\n assert loop.time() < end\n await asyncio.sleep(0.01)\n", False),
+ ("import asyncio\nasync def settle(r):\n for _ in range(200):\n await asyncio.sleep(0.01)\n"
+ " if not r.busy:\n return\n", False), # a round-bounded poll
+ ("import time\nfor _ in range(5):\n time.sleep(0.1)\n tick()\n", True), # five fixed delays
+ ("import time\nfor x in items:\n time.sleep(0.1)\n if x.done:\n break\n", True),
+ # a def inside the poll loop is not its interval
+ ("import time\nend = time.monotonic() + 5\nwhile not done() and time.monotonic() < end:\n"
+ " def cb():\n time.sleep(1)\n", True),
+ ("import threading\nthreading.Event().wait(0.2)\n", True), # an Event nobody can set
+ # yields and non-sleeps
+ ("import time\ntime.sleep(0)\n", False),
+ ("import asyncio\nasync def f():\n await asyncio.sleep(0.0)\n", False),
+ ("import threading\nev = threading.Event()\nev.wait(1)\n", False), # the fix shape
+ ("import threading\nthreading.Event().wait()\n", False),
+ ("def sleep(x):\n return x\nsleep(5)\n", False), # a local helper, not the API
+])
+def test_wall_clock_sleep_shapes(src, flagged):
+ assert bool(_hits(src)) is flagged, src
+
+
+_DEADLINE = "import time\nend = time.monotonic() + 5\n"
+
+
[email protected]("src, flagged", [
+ # red: a test made only of clock reads and constants waits out the clock
+ (_DEADLINE + "other = time.monotonic() + 9\nwhile time.monotonic() < end and time.monotonic() < other:\n"
+ " time.sleep(0.1)\n", True),
+ (_DEADLINE + "while time.monotonic() < end or False:\n time.sleep(0.1)\n", True),
+ (_DEADLINE + "while not time.monotonic() >= end:\n time.sleep(0.1)\n", True),
+ (_DEADLINE + "now = time.monotonic()\nwhile now < end:\n time.sleep(0.1)\n"
+ " now = time.monotonic()\n", True), # locals assigned only from the clock
+ (_DEADLINE + "while True:\n if time.monotonic() > end and True:\n break\n"
+ " time.sleep(0.1)\n", True),
+ # red: `or` ends the loop only when every operand is false, so the clock still decides
+ (_DEADLINE + "while not done() or time.monotonic() < end:\n time.sleep(0.1)\n", True),
+ # green: any non-clock operand is a condition
+ (_DEADLINE + "while time.monotonic() < end and not done():\n time.sleep(0.05)\n", False),
+ (_DEADLINE + "now = time.monotonic()\nwhile now < end and not done():\n time.sleep(0.05)\n"
+ " now = time.monotonic()\n", False),
+ (_DEADLINE + "while time.monotonic() < end:\n if done() or time.monotonic() > end:\n"
+ " break\n time.sleep(0.05)\n", False),
+ (_DEADLINE + "while time.monotonic() < end:\n if not r.busy:\n break\n"
+ " else:\n time.sleep(0.05)\n", False),
+ (_DEADLINE + "while True:\n left = alive()\n if not left or time.monotonic() >= end:\n"
+ " return left\n time.sleep(0.1)\n", False),
+ # red: a timestamp kept in a dict or on an object is still the clock (fails closed)
+ ("import time\nt = {'at': time.time()}\nwhile time.time() - t['at'] < 0.5:\n time.sleep(0.005)\n", True),
+ (_DEADLINE + "while time.monotonic() < self.end and time.monotonic() < end:\n time.sleep(0.1)\n", True),
+ ("import asyncio\nasync def drain():\n end = asyncio.get_event_loop().time() + 0.15\n"
+ " while asyncio.get_event_loop().time() < end:\n await asyncio.sleep(0.01)\n", True),
+ # green: an age read from observed state is a condition
+ (_DEADLINE + "while True:\n age = time.time() - path.stat().st_mtime\n if age > 5:\n"
+ " return\n assert time.monotonic() < end\n time.sleep(0.02)\n", False),
+ # green: only time arithmetic makes a clock local; a value merely built from one is state
+ ("import time\nnonce = time.time_ns()\npid = spawn(f'x{nonce}')\nend = time.monotonic() + 5\n"
+ "while time.monotonic() < end:\n if not alive(pid):\n break\n time.sleep(0.05)\n", False),
+ # red: a `try` that only sleeps cannot fail, so its `break` is unconditional
+ ("import time\nfor _ in range(10):\n try:\n time.sleep(0.5)\n break\n"
+ " except OSError:\n pass\n", True),
+ # green: a `try` body's `return` is taken only when the probe did not raise
+ (_DEADLINE + "while time.monotonic() < end:\n try:\n return probe()\n"
+ " except OSError:\n time.sleep(0.1)\n", False),
+ # red: the same chain of clock locals with no state in it
+ ("import time\nstart = time.monotonic()\nend = start + 5\nnow = start\nwhile now < end:\n"
+ " time.sleep(0.1)\n now = time.monotonic()\n", True),
+])
+def test_condition_must_read_more_than_the_clock(src, flagged):
+ assert bool(_hits(src)) is flagged, src
+
+
[email protected]("src, flagged", [
+ # red: a `break` in a nested loop ends that loop, not the clock-only wait around it
+ (_DEADLINE + "while time.monotonic() < end:\n for x in items:\n if x.done:\n break\n"
+ " time.sleep(0.1)\n", True),
+ (_DEADLINE + "while time.monotonic() < end:\n while busy():\n if ready():\n break\n"
+ " time.sleep(0.1)\n", True),
+ ("import time\nfor _ in range(5):\n for x in items:\n if x.done:\n break\n"
+ " time.sleep(0.1)\n", True),
+ # red: a nested def's `return` is not the loop's exit
+ (_DEADLINE + "while time.monotonic() < end:\n def check():\n if done():\n return True\n"
+ " time.sleep(0.1)\n", True),
+ # red: a loop's `else:` runs once after the loop; it is no poll interval
+ ("import time\nfor _ in range(3):\n if ready():\n break\nelse:\n time.sleep(1)\n", True),
+ (_DEADLINE + "while not done() and time.monotonic() < end:\n pass\nelse:\n time.sleep(1)\n", True),
+ # ... nor are a `while` test or a `for` iterable
+ (_DEADLINE + "while not done() and time.monotonic() < end and time.sleep(1) is None:\n pass\n", True),
+ # red: an outer round loop whose only exit is the inner wait's `break` (tests/tools/test_approval.py)
+ ("import time\nfor i in range(n):\n if i == 0:\n for _ in range(400):\n if ready():\n"
+ " break\n time.sleep(0.005)\n else:\n time.sleep(0.05)\n", True),
+ # green: the poll's own exits, wherever they sit in its body
+ ("import time\nfor _ in range(50):\n try:\n if ready():\n break\n except OSError:\n"
+ " pass\n time.sleep(0.05)\n", False),
+ ("import time\nfor _ in range(50):\n with lock:\n if ready():\n return_value = 1\n"
+ " break\n time.sleep(0.05)\n", False),
+ ("import time\ndef w():\n for _ in range(50):\n for x in items:\n if x.done:\n"
+ " return x\n time.sleep(0.05)\n", False), # a `return` ends every loop
+ ("import time\nfor _ in range(50):\n for x in items:\n pass\n else:\n if ready():\n"
+ " break\n time.sleep(0.05)\n", False), # an inner `else:` break ends the outer loop
+ # green: a poll interval inside the loop body, beside a nested loop
+ (_DEADLINE + "while not done() and time.monotonic() < end:\n for x in items:\n x.poke()\n"
+ " time.sleep(0.05)\n", False),
+])
+def test_exit_belongs_to_the_loop_and_the_interval_to_its_body(src, flagged):
+ assert bool(_hits(src)) is flagged, src
+
+
[email protected]("path, applies", [
+ ("tests/gateway/test_x.py", True),
+ ("tests/e2e/core/test_y.py", True),
+ ("tests/conftest.py", True),
+ ("plugins/foo/tests/test_z.py", True),
+ ("gateway/run.py", False), # production sleeps are not this rule's business
+ ("scripts/release.py", False),
+])
+def test_scope_is_tests_only(path, applies):
+ assert rule_applies(RULES_BY_ID["HX013"], path) is applies
+
+
+_OLD = ("import time\n\n\ndef test_old():\n time.sleep(0.2)\n assert True\n\n\n"
+ "def test_other():\n time.sleep(0.5)\n assert 1\n")
+_NEW = "import time\n\n\ndef test_new():\n time.sleep(0.5)\n assert 2\n"
+
+
+def _judge(tmp_path, capsys, head: dict[str, str | None]):
+ repo, base = _repo(tmp_path)
+ base = _commit(repo, {"tests/test_a.py": _OLD})
+ return _verdict(repo, base, head, capsys)
+
+
[email protected]("head, blocks", [
+ # red: a new sleep, in an old file or a new one
+ ({"tests/test_a.py": _OLD + "\n\n" + _NEW.split("\n\n\n", 1)[1]}, True),
+ ({"tests/test_b.py": _NEW}, True),
+ # red: deleting one old sleep does not pay for a new one elsewhere
+ ({"tests/test_a.py": _OLD.replace(" time.sleep(0.5)\n", ""), "tests/test_b.py": _NEW}, True),
+ # red: copying an old test keeps the original's debt where it is; the copy is new
+ ({"tests/test_b.py": _OLD.replace("test_old", "test_copy").split("\n\n\ndef test_other")[0]
+ + "\n"}, True),
+ # green: the old sleeps untouched while the file changes around them
+ ({"tests/test_a.py": _OLD + "\n\ndef test_more():\n assert 3\n"}, False),
+ # green: an old test moved to another file keeps its debt
+ ({"tests/test_a.py": "import time\n\n\n" + _OLD.split("\n\n\n", 2)[2],
+ "tests/test_b.py": _OLD.split("\n\n\ndef test_other")[0] + "\n"}, False),
+ # green: a renamed file keeps its debt
+ ({"tests/test_a.py": None, "tests/test_renamed.py": _OLD}, False),
+ # green: a waiver with a reason, a yield, and sleeps outside tests/
+ ({"tests/test_b.py": _NEW.replace("(0.5)", "(0.5) # health: allow HX013 -- the delay is the"
+ " behaviour under test")}, False),
+ ({"tests/test_b.py": _NEW.replace("(0.5)", "(0)")}, False),
+ ({"pkg/backoff.py": _NEW.replace("test_new", "backoff")}, False),
+])
+def test_verdict(tmp_path, capsys, head, blocks):
+ code, out = _judge(tmp_path, capsys, head)
+ assert code == (1 if blocks else 0), out
+ if blocks:
+ assert "HX013" in out and "tests.waiting.wait_until" in out, out
+
+
+def test_bare_waiver_does_not_count(tmp_path, capsys):
+ code, out = _judge(tmp_path, capsys,
+ {"tests/test_b.py": _NEW.replace("(0.5)", "(0.5) # health: allow HX013")})
+ assert code == 1 and "needs a reason" in out, out
+
+
+# --- the helper the fix text names ---
+
+def test_wait_until_returns_the_first_truthy_value():
+ done = threading.Event()
+ threading.Timer(0.05, done.set).start()
+ assert wait_until(lambda: done.is_set() and "ok", timeout=10) == "ok"
+
+
+def test_wait_until_names_what_never_happened():
+ with pytest.raises(AssertionError, match="timed out after 0.05s waiting for the flag"):
+ wait_until(lambda: False, timeout=0.05, what="the flag")
+
+
+def test_async_wait_until():
+ async def scenario():
+ box: list[int] = []
+ asyncio.get_running_loop().call_later(0.05, box.append, 1)
+ assert await async_wait_until(lambda: box, timeout=10) == [1]
+ with pytest.raises(AssertionError, match="waiting for nothing"):
+ await async_wait_until(lambda: None, timeout=0.05, what="nothing")
+
+ asyncio.run(scenario())
diff --git a/tests/waiting.py b/tests/waiting.py
new file mode 100644
index 00000000000..02e9255c748
--- /dev/null
+++ b/tests/waiting.py
@@ -0,0 +1,58 @@
+"""Wait for a condition instead of the clock (the HX013 fix).
+
+A fixed ``time.sleep(0.2)`` before an assertion is a bet that the code under test finishes within
+0.2 s; on a loaded CI runner it loses and the test flakes. Poll the condition with a generous
+deadline instead: a fast run returns in milliseconds, a slow one still passes, and a real hang
+fails with a message naming what never happened.
+
+ from tests.waiting import wait_until, async_wait_until
+
+ wait_until(lambda: worker.done, what="worker finished")
+ row = wait_until(lambda: db.get(key), timeout=10) # returns the truthy value
+ await async_wait_until(lambda: adapter.sent, what="message sent")
+
+Prefer an Event the code under test sets (``threading.Event`` / ``asyncio.Event`` with
+``.wait(timeout=...)``) when there is one; poll when the only signal is observable state.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Callable
+from typing import TypeVar
+
+T = TypeVar("T")
+
+DEFAULT_TIMEOUT = 10.0 # a deadline, not a delay: only a hang ever waits this long
+DEFAULT_INTERVAL = 0.01
+
+
+def _timed_out(what: str | None, timeout: float) -> AssertionError:
+ return AssertionError(f"timed out after {timeout}s waiting for {what or 'the condition'}")
+
+
+def wait_until(predicate: Callable[[], T], timeout: float = DEFAULT_TIMEOUT,
+ interval: float = DEFAULT_INTERVAL, what: str | None = None) -> T:
+ """Return ``predicate()``'s first truthy value; raise AssertionError after ``timeout`` s."""
+ deadline = time.monotonic() + timeout
+ while True:
+ value = predicate()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise _timed_out(what, timeout)
+ time.sleep(interval)
+
+
+async def async_wait_until(predicate: Callable[[], T], timeout: float = DEFAULT_TIMEOUT,
+ interval: float = DEFAULT_INTERVAL, what: str | None = None) -> T:
+ """``wait_until`` for a coroutine: yields to the event loop between polls."""
+ deadline = time.monotonic() + timeout
+ while True:
+ value = predicate()
+ if value:
+ return value
+ if time.monotonic() >= deadline:
+ raise _timed_out(what, timeout)
+ await asyncio.sleep(interval)