diff --git a/dokimi/scripts/check_test_timing.py b/dokimi/scripts/check_test_timing.py index cb0a791d9..62f25763f 100644 --- a/dokimi/scripts/check_test_timing.py +++ b/dokimi/scripts/check_test_timing.py @@ -7,8 +7,12 @@ on a fast machine and fails on a busy runner: wait on the condition with ``tests/waiting.py`` instead. This counts, per file under ``tests/``, the calls the file's imports resolve to ``time.sleep`` or ``threading.Timer`` (``import time``, ``import time as t``, ``from time import -sleep as nap``, ``from time import *``, and the same for ``threading``). Only imports are followed: a -name assigned from them (``nap = time.sleep``) is not. Where branches meet (``if``/``else``, ``try``/ +sleep as nap``, ``from time import *``, and the same for ``threading``), and the calls on a module +loaded by name with a string literal: ``__import__("time").sleep(1)``, ``importlib.import_module("time").sleep(1)`` +and ``import_module("time").sleep(1)`` after ``from importlib import import_module``. Only imports are +followed: a name assigned from them (``nap = time.sleep``, ``mod = __import__("time")``) is not, and +neither is a module named by anything but one positional literal and no other argument +(``import_module(name="time")`` and ``__import__("time", globals())`` are not). Where branches meet (``if``/``else``, ``try``/ ``except``, ``case``), a name counts when any branch binds it to a sleep or timer. A ``sleep`` in a string, such as a child's shell command, is not a call. ``tests/waiting.py`` is the one file not counted. @@ -30,7 +34,7 @@ import re import sys import tokenize -from collections.abc import Sequence +from collections.abc import Callable, Sequence from pathlib import Path from typing import NamedTuple @@ -41,7 +45,11 @@ #: The helper module is where the polling loop lives, so it alone may sleep. EXEMPT = "waiting.py" TARGETS = {"time": {"sleep"}, "threading": {"Timer"}} +#: Names the imports are followed for: the targets, and the loader that can fetch one by its name. +WATCHED = {**TARGETS, "importlib": {"import_module"}} +COUNTED = {f"{module}.{name}" for module, names in TARGETS.items() for name in names} WAIVER = re.compile(r"#\s*timing-ok\b(?::(?P.*))?$") +MARKERS = re.compile("|".join([*(re.escape(n) for names in TARGETS.values() for n in names), "timing-ok"])) HINT = "(python scripts/check_test_timing.py --update)" @@ -189,11 +197,11 @@ def _bind_import(node: ast.Import | ast.ImportFrom, names: Names, path: Arms) -> if isinstance(node, ast.Import): bound = alias.asname or alias.name.split(".")[0] full = alias.name if alias.asname else alias.name.split(".")[0] - _note(names, bound, pos, full if full in TARGETS else None, path=path) - elif node.module in TARGETS and node.level == 0 and alias.name == "*": - for target in TARGETS[node.module]: + _note(names, bound, pos, full if full in WATCHED else None, path=path) + elif node.module in WATCHED and node.level == 0 and alias.name == "*": + for target in WATCHED[node.module]: _note(names, target, pos, f"{node.module}.{target}", path=path) - elif node.module in TARGETS and node.level == 0 and alias.name in TARGETS[node.module]: + elif node.module in WATCHED and node.level == 0 and alias.name in WATCHED[node.module]: _note(names, alias.asname or alias.name, pos, f"{node.module}.{alias.name}", path=path) else: _note(names, alias.asname or alias.name, pos, None, path=path) @@ -317,12 +325,27 @@ def meanings(name: str) -> list[str | None]: func = call.func if isinstance(func, ast.Name): - return next((m for m in meanings(func.id) if m and "." in m), None) - if isinstance(func, ast.Attribute) and isinstance(func.value, ast.Name): - for module in meanings(func.value.id): - if module in TARGETS and func.attr in TARGETS[module]: - return f"{module}.{func.attr}" - return None + return next((m for m in meanings(func.id) if m in COUNTED), None) + if not isinstance(func, ast.Attribute): + return None + modules = (meanings(func.value.id) if isinstance(func.value, ast.Name) + else [_loaded(func.value, meanings)] if isinstance(func.value, ast.Call) else []) + return next((f"{m}.{func.attr}" for m in modules if m in TARGETS and func.attr in TARGETS[m]), None) + + +def _loaded(load: ast.Call, meanings: Callable[[str], list[str | None]]) -> str | None: + """The module ``__import__("m")`` or ``importlib.import_module("m")`` loads, for a literal ``m``; the + builtin is a name no scope binds, and ``import_module`` is one an import of it binds.""" + arg = load.args[0] if len(load.args) == 1 and not load.keywords else None + if not (isinstance(arg, ast.Constant) and isinstance(arg.value, str)): + return None + fn = load.func + if isinstance(fn, ast.Name): + found = fn.id == "__import__" and not meanings(fn.id) or "importlib.import_module" in meanings(fn.id) + else: + found = (isinstance(fn, ast.Attribute) and fn.attr == "import_module" and isinstance(fn.value, ast.Name) + and "importlib" in meanings(fn.value.id)) + return arg.value if found else None def _outer_parts(node: ast.AST) -> list[ast.AST]: @@ -421,9 +444,8 @@ def _waivers(text: str) -> tuple[set[int], list[int]]: return ok, bare -def scan(text: str, filename: str) -> tuple[dict[str, int], list[int]]: - """``({"time.sleep": n, "threading.Timer": m}, bare waiver lines)`` of one file's source.""" - tree = ast.parse(text, filename=filename) +def count(tree: ast.Module, text: str) -> tuple[dict[str, int], list[int]]: + """``scan`` of a parsed file, without the shortcut for a file that cannot hold a call.""" ok, bare = _waivers(text) counts: dict[str, int] = {} for node, target in _calls(tree): @@ -433,6 +455,16 @@ def scan(text: str, filename: str) -> tuple[dict[str, int], list[int]]: return counts, bare +def scan(text: str, filename: str) -> tuple[dict[str, int], list[int]]: + """``({"time.sleep": n, "threading.Timer": m}, bare waiver lines)`` of one file's source. A call and a + waiver both spell ``sleep``, ``Timer`` or ``timing-ok``, so an ASCII file with none of them (identifiers + are NFKC-folded, so a non-ASCII one may) is parsed, for its syntax, and not walked.""" + tree = ast.parse(text, filename=filename) + if text.isascii() and not MARKERS.search(text): + return {}, [] + return count(tree, text) + + def measure(root: Path) -> tuple[dict[str, int], dict[str, int], list[str]]: """``(calls per file, calls per target, problems)`` over every ``*.py`` under ``root``.""" per_file: dict[str, int] = {} diff --git a/dokimi/scripts/growth_baseline.json b/dokimi/scripts/growth_baseline.json index 96c532fce..aa33535f8 100644 --- a/dokimi/scripts/growth_baseline.json +++ b/dokimi/scripts/growth_baseline.json @@ -5,7 +5,7 @@ "dokimi/report/model_compare.py": {"lines": 1124, "rationale": "grew on main in #73 (judge-validity --context stored) before the ratchet landed; split it in its own PR"}, "tests/test_arm_runner.py": {"lines": 1175, "rationale": "pre-existing when the gate was introduced"}, "tests/test_benchflow_harness.py": {"lines": 1716, "rationale": "pre-existing when the gate was introduced"}, - "tests/test_container_agent.py": {"lines": 1235, "rationale": "pre-existing when the gate was introduced"}, + "tests/test_container_agent.py": {"lines": 1233, "rationale": "pre-existing when the gate was introduced"}, "tests/test_judge_reliability.py": {"lines": 1680, "rationale": "grew on main in #73 (judge-validity --context stored), 1505 -> 1695, before the ratchet landed; split it in its own PR"}, "tests/test_judge_validity.py": {"lines": 2234, "rationale": "grew on main in #73 (judge-validity --context stored), 1423 -> 2235, before the ratchet landed; split it in its own PR"}, "tests/test_pipeline_question_set.py": {"lines": 1223}, diff --git a/dokimi/tests/test_check_test_timing.py b/dokimi/tests/test_check_test_timing.py index 323a48f35..b7099d347 100644 --- a/dokimi/tests/test_check_test_timing.py +++ b/dokimi/tests/test_check_test_timing.py @@ -5,6 +5,7 @@ from __future__ import annotations +import ast import json import sys from pathlib import Path @@ -278,6 +279,63 @@ def test_a_name_bound_differently_in_each_branch_counts_when_any_branch_makes_it assert ctt.scan(source, "x.py") == (expected, []) +@pytest.mark.parametrize(("source", "expected"), [ + ('__import__("time").sleep(1)\n', {"time.sleep": 1}), + ('import importlib\nimportlib.import_module("time").sleep(1)\n', {"time.sleep": 1}), + ('import importlib as il\nil.import_module("time").sleep(1)\n', {"time.sleep": 1}), + ('from importlib import import_module\nimport_module("time").sleep(1)\n', {"time.sleep": 1}), + ('from importlib import import_module as load\nload("time").sleep(1)\n', {"time.sleep": 1}), + ('__import__("threading").Timer(1, print)\n', {"threading.Timer": 1}), + ('import importlib\nimportlib.import_module("threading").Timer(1, print)\n', {"threading.Timer": 1}), + ('__import__("time").sleep(1) # timing-ok: the child must outlive the parent\n', {}), + ('__import__(name).sleep(1)\n', {}), + ('__import__("ti" + "me").sleep(1)\n', {}), + ('__import__("time", fromlist=["sleep"]).sleep(1)\n', {}), + ('__import__("os").getcwd()\n', {}), + ('__import__("time").monotonic()\n', {}), + ('__import__("time").Timer(1, print)\n', {}), + ('def test_a(__import__):\n __import__("time").sleep(1)\n', {}), + ('def test_a():\n def __import__(name):\n pass\n __import__("time").sleep(1)\n', {}), + ('__import__ = print\n__import__("time").sleep(1)\n', {}), + ('import importlib\n\n\ndef test_a(importlib):\n importlib.import_module("time").sleep(1)\n', {}), + ('from importlib import import_module\n\n\ndef test_a():\n import_module = print\n' + ' import_module("time").sleep(1)\n', {}), + ('import importlib\nimportlib.import_module(name).sleep(1)\n', {}), + ('import_module("time").sleep(1)\n', {}), + ('import mylib\nmylib.import_module("time").sleep(1)\n', {}), + ('from importlib import import_module\nimport_module("time")\n', {}), + ('from importlib import *\nimport_module("time").sleep(1)\n', {"time.sleep": 1}), + ('__import__("time", globals()).sleep(1)\n', {}), + ('import importlib\nimportlib.import_module(name="time").sleep(1)\n', {}), + ('__import__(name="time").sleep(1)\n', {}), + ('mod = __import__("time")\nmod.sleep(1)\n', {}), + ('import importlib\nt = importlib.import_module("time")\nt.sleep(1)\n', {}), +]) +def test_a_module_loaded_by_a_literal_name_counts_like_an_imported_one(source, expected): + assert ctt.scan(source, "x.py") == (expected, []) + + +@pytest.mark.parametrize(("source", "expected"), [ + ("def test_a():\n assert 1 + 1 == 2\n", ({}, [])), + ("import time\nprint(time.monotonic())\n", ({}, [])), + ("import time\ntime.sleep(1)\n", ({"time.sleep": 1}, [])), + ("x = 1 # timing-ok\n", ({}, [1])), + ("import time\ntime.sleep(1)\n", ({"time.sleep": 1}, [])), + ("from threading import Timer\nTimer(1, print)\n", ({"threading.Timer": 1}, [])), +]) +def test_a_file_that_cannot_hold_a_call_is_not_walked_and_scans_as_if_it_were(source, expected, monkeypatch): + assert ctt.count(ast.parse(source), source) == expected + assert ctt.scan(source, "x.py") == expected + if source.isascii() and not any(word in source for word in ("sleep", "Timer", "timing-ok")): + monkeypatch.setattr(ctt, "_calls", lambda tree: pytest.fail("walked a file with no marker")) + assert ctt.scan(source, "x.py") == expected + + +def test_a_file_with_no_marker_is_still_parsed_for_its_syntax(): + with pytest.raises(SyntaxError): + ctt.scan("def (:\n", "x.py") + + def test_a_waiver_with_a_reason_is_not_counted(): source = "import time\ntime.sleep(60) # timing-ok: child must outlive the parent\n" assert ctt.scan(source, "x.py") == ({}, []) diff --git a/dokimi/tests/test_container_agent.py b/dokimi/tests/test_container_agent.py index 50de16ee3..d753574ed 100644 --- a/dokimi/tests/test_container_agent.py +++ b/dokimi/tests/test_container_agent.py @@ -37,6 +37,7 @@ from dokimi.harnesses.registry import create_harness from dokimi.process import reply from docker_cli_fake import DockerCLI +from tests.waiting import poll_until @pytest.fixture(autouse=True) @@ -1100,10 +1101,7 @@ def test_proxy_logs_plain_http_failures_with_host_and_normalised_names(): sock.sendall(req) sock.recv(1024) sock.close() - for _ in range(50): - if len(proxy.log) >= 4: - break - __import__("time").sleep(0.05) + poll_until(lambda: len(proxy.log) >= 4, 2.5, interval=0.05) finally: proxy.stop() rows = [(r["host"], r["port"], r["decision"]) for r in proxy.log]