Fine-tune LLMs from one YAML. Layer streaming trains an 8B model on a 4 GB laptop GPU.
Python cliconsumer-gpudpofine-tuningggufhuggingfacellmllmopslocal-ailocal-llmloralow-vrammachine-learningollamapeftpythonpytorchqlorasfttransformers
test(guards): source-scanning guards parse src once per module (#1796)
Alpamys Makazhan0de3c5e7e649
diff --git a/tests/_source_scan.py b/tests/_source_scan.pynew file mode 100644index 00000000..9a2e5300--- /dev/null+++ b/tests/_source_scan.py@@ -0,0 +1,192 @@+"""THE parse / walk / memo cache for guards that scan ``src/soup_cli`` or ``tests/``. One copy.++About a hundred test files walk a whole tree and ``ast.parse`` every file in it, and the slow+ones do it several times: once per test, per parametrised case, or per registry entry. Measured+on the dev box (one process, no coverage), one pass costs:++========= ===== ====== ======== ========= =========+tree files list read parse ast.walk+========= ===== ====== ======== ========= =========+src 542 4-8 ms 27-47 ms 1.1-1.9 s 0.5 s+tests 876 8 ms 72 ms 1.9-2.5 s 1.8 s+========= ===== ====== ======== ========= =========++Listing and reading are about 2% of a pass, so **they are not cached**: a guard keeps its own+``sorted(root.rglob("*.py"))`` and its own ``read_text``. What is cached is what costs:++``parse_source(text, filename="<unknown>", *, keep=False)``+ ``ast.parse(text, filename)``. By default the tree is remembered only while its text is+ one of the last two parsed, which is enough for the scanners that look at one file back+ to back to share a parse. ``keep=True`` holds it until ``release()``.+``walk_nodes(tree)``+ ``tuple(ast.walk(tree))`` without the generators: same nodes, same order. Kept for a tree+ ``parse_source`` still remembers, rebuilt each call for any other node.+``memoized_scan``+ Decorator for a pure ``scanner(text) -> findings``: one run per distinct input, and every+ caller gets its own shallow copy of the result.++**``keep=True`` has a price that outlives the module.** Private bytes of one process (Windows,+Python 3.12.10):++========================== ====== ===================+what the process held peak after ``release()``+========================== ====== ===================+nothing (parse and drop) 65 MB 23 MB+every tree of ``src`` 283 MB 266 MB+every tree of ``tests`` 551 MB 524 MB+========================== ====== ===================++``release()`` frees the trees (pinned by a weakref test) but the allocator keeps the pages, so+a worker that held a whole tree once stays that much larger until it exits. The walk tuples+are not the cost (3 MB of the 283). Hence the rule: **keep a whole tree only where several+whole-tree passes share it**, and never ``tests/``. Today that is ``src`` in ``test_issue748_*``+(seven-fold faster for it), ``test_issue616_*`` and ``test_issue752_*``, whose scan held every+tree before this helper existed. A guard whose tests each make one pass gains nothing from+``keep``; prefer ``memoized_scan`` on its findings, which holds no tree at all.++**What may be relied on.** ``parse_source`` is keyed on the *text* the caller read, never on a+path or an mtime, and ``memoized_scan`` on the scanner's own arguments. A file that changes on+disk between two guards is therefore a different key and is parsed again; a seeded violation+written to ``tmp_path`` and rewritten in place is scanned for what it now contains.++**What is NOT supported.**++- A memoised scanner that reads anything but its arguments (a file, a global table): a file+ that changes on disk between two calls is then served stale until the module ends. Pass the+ text in. One scanner is knowingly keyed on a file LIST instead: ``_dead_function_inputs`` in+ ``test_issue748_*``, next to the ``_consumed_cached`` that already was. Both are right within+ one unchanged tree, which is all a test run needs; neither notices a module edited mid-run.+- Editing a tree from ``parse_source``. It is shared with every other caller, so a scanner+ that rewrites its tree (strips docstrings, sets ``node.parent``) must call ``ast.parse``+ itself and cache its *findings* with ``memoized_scan`` instead.+- Editing a tree while iterating ``walk_nodes``. ``ast.walk`` is lazy and sees such an edit;+ ``walk_nodes`` is a snapshot taken before the loop body runs.+- Results that nest mutable containers: the copy is one level deep.++**Lifetime: one test module.** ``tests/conftest.py`` calls ``release()`` when a module's tests+are done. While kept trees are alive every ``gc.collect()`` in the worker walks them (0.6 ms+-> 230 ms for ``src``). Call these from test bodies, not at import time: a tree kept during+collection is held until the first module finishes.+"""++from __future__ import annotations++import ast+import collections+import copy+import functools+import weakref+from typing import Any, Callable, TypeVar++_Scanner = TypeVar("_Scanner", bound=Callable[..., Any])++#: How many texts the default (``keep=False``) cache remembers: the file being scanned and+#: the one before it. Guards scan one file at a time.+RECENT_LIMIT = 2+++class _Parsed:+ """One tree ``parse_source`` handed out, and its flattened walk once someone asked."""++ __slots__ = ("tree", "nodes")++ def __init__(self, tree: ast.Module) -> None:+ self.tree = tree+ self.nodes: tuple[ast.AST, ...] | None = None+++#: source text -> its tree, for the callers that asked to keep it until ``release()``.+_KEPT: dict[str, _Parsed] = {}+#: source text -> its tree, for the last ``RECENT_LIMIT`` texts parsed without ``keep``.+_RECENT: collections.OrderedDict[str, _Parsed] = collections.OrderedDict()+#: id(tree) -> the same record, for every tree in the two maps above. The record keeps the+#: tree alive, so the id cannot be reused while the entry exists.+_BY_TREE: dict[int, _Parsed] = {}+#: Every live memoised scanner, so ``release()`` reaches them too. Weak: a scanner defined+#: inside a test goes away with that test.+_MEMOS: weakref.WeakSet[Any] = weakref.WeakSet()+++def parse_source(source: str, filename: str = "<unknown>", *, keep: bool = False) -> ast.Module:+ """``ast.parse(source, filename)``, shared between callers. Do not edit the result.++ ``keep=False``: remembered while ``source`` is one of the last ``RECENT_LIMIT`` texts+ parsed. ``keep=True``: remembered until ``release()``; read the module docstring for what+ that costs before reaching for it.++ Raises exactly what ``ast.parse`` raises, every time: a failure is not cached, so its+ message names the caller's ``filename``. A tree carries no filename, which is why the+ key is the text alone.+ """+ held = _KEPT.get(source)+ if held is not None:+ return held.tree+ held = _RECENT.get(source)+ if held is None:+ held = _Parsed(ast.parse(source, filename))+ _BY_TREE[id(held.tree)] = held+ if keep:+ _RECENT.pop(source, None)+ _KEPT[source] = held+ return held.tree+ _RECENT[source] = held+ _RECENT.move_to_end(source)+ while len(_RECENT) > RECENT_LIMIT:+ _text, dropped = _RECENT.popitem(last=False)+ del _BY_TREE[id(dropped.tree)]+ return held.tree+++def _flatten(root: ast.AST) -> tuple[ast.AST, ...]:+ """``ast.walk(root)`` as a tuple: breadth-first, children in field order.++ The list grows while it is iterated, which is the queue ``ast.walk`` keeps in a deque.+ One frame instead of three nested generators per node, which is where the time goes --+ more so under coverage, whose tracer is called on every generator resume.+ """+ nodes: list[ast.AST] = [root]+ for node in nodes:+ for name in node._fields:+ value = getattr(node, name, None)+ if isinstance(value, ast.AST):+ nodes.append(value)+ elif isinstance(value, list):+ for item in value:+ if isinstance(item, ast.AST):+ nodes.append(item)+ return tuple(nodes)+++def walk_nodes(tree: ast.AST) -> tuple[ast.AST, ...]:+ """Every node ``ast.walk(tree)`` yields, in the same order, as a tuple."""+ held = _BY_TREE.get(id(tree))+ if held is None or held.tree is not tree:+ return _flatten(tree)+ if held.nodes is None:+ held.nodes = _flatten(tree)+ return held.nodes+++def memoized_scan(scanner: _Scanner) -> _Scanner:+ """Run a pure ``scanner(*args)`` once per distinct arguments, until ``release()``.++ Each call returns ``copy.copy`` of the cached result, so a caller that sorts, extends or+ ``|=``-s what it got cannot change what the next caller gets. An exception is not cached.+ """+ cached = functools.lru_cache(maxsize=None)(scanner)+ _MEMOS.add(cached)++ @functools.wraps(scanner)+ def scan(*args: Any, **kwargs: Any) -> Any:+ return copy.copy(cached(*args, **kwargs))++ return scan # type: ignore[return-value]+++def release() -> None:+ """Drop every parsed tree, flattened walk and memoised result."""+ _KEPT.clear()+ _RECENT.clear()+ _BY_TREE.clear()+ for cached in list(_MEMOS):+ cached.cache_clear()diff --git a/tests/conftest.py b/tests/conftest.pyindex a8a9297a..f0dea438 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -9,6 +9,8 @@ from pathlib import Pathimport pytest+from tests import _source_scan+#: The skip message for a ``gpu``-marked test on a machine without CUDA (#833).GPU_SKIP_REASON = "needs a CUDA device (run the GPU subset with: pytest -m gpu --no-cov)"@@ -184,6 +186,19 @@ def _restore_working_directory():os.chdir(before)[email protected](autouse=True, scope="module")+def _release_scanned_sources():+ """Drop what a source-scanning guard parsed once its module is done.++ ``tests/_source_scan.py`` lets a guard keep the parsed trees of the files it walked,+ so that the module's next test does not parse them again. Every tree of+ ``src/soup_cli`` is 283 MB of private bytes, and while they are alive every+ ``gc.collect()`` in the worker walks them, so they go when the module goes.+ """+ yield+ _source_scan.release()++@pytest.fixturedef aten_half_matmuls(monkeypatch: pytest.MonkeyPatch):"""Keep a CPU bf16/fp16 step off oneDNN and off MKL's half-precision GEMMs.diff --git a/tests/test_cli_help_assertions_are_ansi_safe.py b/tests/test_cli_help_assertions_are_ansi_safe.pyindex c02d5e17..e269ae57 100644--- a/tests/test_cli_help_assertions_are_ansi_safe.py+++ b/tests/test_cli_help_assertions_are_ansi_safe.py@@ -77,6 +77,8 @@ import textwrapimport pytest+from tests._source_scan import parse_source, walk_nodes+TESTS_DIR = pathlib.Path(__file__).parent# A quoted CLI flag: "--noise-floor", '--gpus'.@@ -142,12 +144,12 @@ def find_raw_help_assertions(source: str) -> list[tuple[int, str]]:fails the whole guard."""try:- tree = ast.parse(source)+ tree = parse_source(source)except SyntaxError: # pragma: no cover — a broken file fails its own testsreturn []lines = source.splitlines()offenders: list[tuple[int, str]] = []- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):continueif not node.name.startswith("test"):@@ -388,7 +390,7 @@ def _assert_statement_lines(tree: ast.AST) -> set[int]:which is why both are needed."""covered: set[int] = set()- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, ast.Assert):continue# `node.test` ONLY, never `node.msg`. Reading raw output inside a@@ -418,7 +420,7 @@ def _multiline_literal_lines(tree: ast.AST) -> set[int]:follow-up, closed by the maintainer)."""covered: set[int] = set()- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, ast.Constant) or not isinstance(node.value, str):continueend = node.end_lineno or node.lineno@@ -435,14 +437,14 @@ def find_unsafe_highlighted_assertions(source: str) -> list[tuple[int, str]]:parser or asserts a multi-token substring against it."""try:- tree = ast.parse(source)+ tree = parse_source(source)except SyntaxError: # pragma: no cover — a broken file fails its own testsreturn []lines = source.splitlines()literal_lines = _multiline_literal_lines(tree)assert_lines = _assert_statement_lines(tree)offenders: list[tuple[int, str]] = []- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):continueif not node.name.startswith("test"):@@ -572,14 +574,14 @@ def _find_raw_cli_output_statements() -> list[tuple[int, int, str, bool]]:"""Return (start_line, end_line, first_line_text, has_ansi_ok) for raw output asserts."""try:- tree = ast.parse(source)+ tree = parse_source(source)except SyntaxError: # pragma: no cover — a broken file fails its own testsreturn []lines = source.splitlines()literal_lines = _multiline_literal_lines(tree)records: list[tuple[int, int, str, bool]] = []- for fn in ast.walk(tree):+ for fn in walk_nodes(tree):if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):continueif not fn.name.startswith("test"):@@ -589,7 +591,7 @@ def _find_raw_cli_output_statements(stmts = sorted([s- for s in ast.walk(fn)+ for s in walk_nodes(fn)if isinstance(s, (ast.Assign, ast.AnnAssign, ast.AugAssign, ast.Assert))],key=lambda s: s.lineno,@@ -683,7 +685,7 @@ def find_stale_ansi_ok_markers(source: str) -> list[tuple[int, str]]:"""Return ``(lineno, line_text)`` for any ``# ansi-ok:`` marker that does notactively suppress an otherwise-flagged raw CLI output assertion."""try:- tree = ast.parse(source)+ tree = parse_source(source)except SyntaxError:return []lines = source.splitlines()@@ -742,7 +744,7 @@ class TestNoRawCliOutputAssertionsInTheSuite:markers = find_stale_ansi_ok_markers(source)for lineno, text in markers:stale.append(f"{path.name}:{lineno}: {text}")- tree = ast.parse(source)+ tree = parse_source(source)lit_lines = _multiline_literal_lines(tree)total_markers += sum(1@@ -918,4 +920,3 @@ def test_safe():stale = find_stale_ansi_ok_markers(textwrap.dedent(src))assert len(stale) == 1assert "unnecessary exemption" in stale[0][1]-diff --git a/tests/test_issue616_net_guard_is_shared.py b/tests/test_issue616_net_guard_is_shared.pyindex f2479b91..ab42829e 100644--- a/tests/test_issue616_net_guard_is_shared.py+++ b/tests/test_issue616_net_guard_is_shared.py@@ -29,6 +29,8 @@ from pathlib import Pathimport pytest+from tests._source_scan import parse_source, walk_nodes+_UTILS_DIR = Path(__file__).resolve().parent.parent / "src" / "soup_cli" / "utils"_SRC_ROOT = _UTILS_DIR.parent_HOME = _UTILS_DIR / "net_guard.py"@@ -40,7 +42,7 @@ _CONSUMERS = ("hf.py", "hubs.py", "loop_stages.py", "qr_url.py", "webhooks.py",def _parse(path: Path) -> ast.Module:- return ast.parse(path.read_text(encoding="utf-8"))+ return parse_source(path.read_text(encoding="utf-8"), keep=True)def _assigned_names(node: ast.AST) -> list[str]:@@ -64,7 +66,7 @@ def _imports_net_guard(path: Path) -> bool:"""return any(isinstance(node, ast.ImportFrom) and node.module == "soup_cli.utils.net_guard"- for node in ast.walk(_parse(path))+ for node in walk_nodes(_parse(path)))@@ -91,7 +93,7 @@ def _definers(path: Path) -> list[str]:recorded once, under BUNDLED_SCORER_FINGERPRINT."""found: list[str] = []- for node in ast.walk(_parse(path)):+ for node in walk_nodes(_parse(path)):if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):if node.name.endswith(_FUNC_SUFFIX):found.append(node.name)@@ -110,7 +112,7 @@ def _builders(path: Path) -> list[str]:"""Every name assigned in ``path`` ending in the host-set suffix."""return [name- for node in ast.walk(_parse(path))+ for node in walk_nodes(_parse(path))for name in _assigned_names(node)if _normalised(name).endswith(_normalised(_SET_SUFFIX))]@@ -269,7 +271,7 @@ _HOSTNAME_CHECKS_WITHOUT_THE_REFUSAL = {def _functions(path: Path) -> list[ast.FunctionDef | ast.AsyncFunctionDef]:return [node- for node in ast.walk(_parse(path))+ for node in walk_nodes(_parse(path))if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))]@@ -324,7 +326,7 @@ def _imports_the_refusal(path: Path) -> bool:isinstance(node, ast.ImportFrom)and node.module == "soup_cli.utils.net_guard"and any(alias.name == _REFUSAL for alias in node.names)- for node in ast.walk(_parse(path))+ for node in walk_nodes(_parse(path)))diff --git a/tests/test_issue748_config_fields_reach_a_consumer.py b/tests/test_issue748_config_fields_reach_a_consumer.pyindex 907d8133..a57a588d 100644--- a/tests/test_issue748_config_fields_reach_a_consumer.py+++ b/tests/test_issue748_config_fields_reach_a_consumer.py@@ -113,9 +113,12 @@ import functoolsimport osimport pathlibimport re+import typesimport pytest+from tests._source_scan import memoized_scan, parse_source, walk_nodes+pytestmark = pytest.mark.unitSRC = pathlib.Path(__file__).resolve().parents[1] / "src" / "soup_cli"@@ -158,10 +161,10 @@ def consumed_names(paths) -> set:names: set = set()for path in paths:try:- tree = ast.parse(path.read_text(errors="ignore"))+ tree = parse_source(path.read_text(errors="ignore"), keep=True)except (SyntaxError, UnicodeDecodeError, ValueError):continue- for node in ast.walk(tree):+ for node in walk_nodes(tree):if isinstance(node, ast.Attribute):if isinstance(node.ctx, ast.Load):names.add(node.attr)@@ -201,10 +204,10 @@ def training_receiver_reads(paths, field: str) -> bool:"""for path in paths:try:- tree = ast.parse(pathlib.Path(path).read_text(errors="ignore"))+ tree = parse_source(pathlib.Path(path).read_text(errors="ignore"), keep=True)except (SyntaxError, UnicodeDecodeError, ValueError):continue- for node in ast.walk(tree):+ for node in walk_nodes(tree):if (isinstance(node, ast.Attribute)and isinstance(node.ctx, ast.Load)@@ -248,10 +251,10 @@ def schema_property_reads(schema_path: pathlib.Path) -> dict:"""out: dict = {}try:- tree = ast.parse(schema_path.read_text(errors="ignore"))+ tree = parse_source(schema_path.read_text(errors="ignore"), keep=True)except (SyntaxError, UnicodeDecodeError, ValueError): # pragma: no coverreturn out- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):continuenames = []@@ -316,12 +319,28 @@ def _consumed_in_src() -> set:`schema_property_reads`."""modules = _consumer_modules()- consumed = set(_consumed_cached(tuple(sorted(str(p) for p in modules))))+ paths_key = tuple(sorted(str(p) for p in modules))+ consumed = set(_consumed_cached(paths_key))consumed = fold_property_reads(consumed, schema_property_reads(SCHEMA_PATH))# #807: a read inside a function nothing calls is not consumption, for# the same reason an uncalled @property launders nothing.- return drop_dead_function_reads(- consumed, function_scoped_reads(modules), referenced_names(modules)+ scoped, referenced = _dead_function_inputs(paths_key)+ return drop_dead_function_reads(consumed, scoped, referenced)+++@memoized_scan+def _dead_function_inputs(paths_key) -> tuple:+ """`(function_scoped_reads, referenced_names)` of one file list, walked once.++ `_consumed_in_src()` needs both on every call and this file calls it seven+ times, which was fourteen more walks of `src/`. Keyed on the file list, like+ `_consumed_cached`, and dropped when the module finishes (`tests/_source_scan`).+ Handed out read-only: every caller shares the one mapping.+ """+ modules = [pathlib.Path(p) for p in paths_key]+ return (+ types.MappingProxyType(function_scoped_reads(modules)),+ frozenset(referenced_names(modules)),)@@ -912,7 +931,7 @@ def function_scoped_reads(paths) -> dict:out: dict = {}for path in paths:try:- tree = ast.parse(path.read_text(errors="ignore"))+ tree = parse_source(path.read_text(errors="ignore"), keep=True)except (SyntaxError, UnicodeDecodeError, ValueError):continuestack = [(tree, None)]@@ -945,10 +964,10 @@ def referenced_names(paths) -> set:names: set = set()for path in paths:try:- tree = ast.parse(path.read_text(errors="ignore"))+ tree = parse_source(path.read_text(errors="ignore"), keep=True)except (SyntaxError, UnicodeDecodeError, ValueError):continue- for node in ast.walk(tree):+ for node in walk_nodes(tree):if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):names.add(node.id)elif isinstance(node, ast.Attribute) and isinstance(node.ctx, ast.Load):diff --git a/tests/test_issue752_cli_commands_called_as_functions.py b/tests/test_issue752_cli_commands_called_as_functions.pyindex ce393dc1..14cbe2fe 100644--- a/tests/test_issue752_cli_commands_called_as_functions.py+++ b/tests/test_issue752_cli_commands_called_as_functions.py@@ -36,6 +36,8 @@ import textwrapimport pytestimport typer+from tests._source_scan import parse_source, walk_nodes+SRC = pathlib.Path(__file__).resolve().parents[1] / "src" / "soup_cli"@@ -96,14 +98,14 @@ def find_optioninfo_leaks(root: pathlib.Path) -> list[tuple[str, int, str, list[for path in sorted(root.rglob("*.py")):try:- tree = ast.parse(path.read_text(encoding="utf-8"))+ tree = parse_source(path.read_text(encoding="utf-8"), keep=True)except SyntaxError: # pragma: no cover - the tree parses todaycontinuetrees[path] = treemod = _module_name(path, root)declared[mod] = {node.name: _typer_params(node)- for node in ast.walk(tree)+ for node in walk_nodes(tree)if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}@@ -112,12 +114,12 @@ def find_optioninfo_leaks(root: pathlib.Path) -> list[tuple[str, int, str, list[mod = _module_name(path, root)local = declared.get(mod, {})imported: dict[str, tuple[str, str]] = {}- for node in ast.walk(tree):+ for node in walk_nodes(tree):if isinstance(node, ast.ImportFrom) and node.module and not node.level:for alias in node.names:imported[alias.asname or alias.name] = (node.module, alias.name)- for call in ast.walk(tree):+ for call in walk_nodes(tree):if not isinstance(call, ast.Call):continue# Bare-name calls only. `model.train()` is a method that happens todiff --git a/tests/test_issue755_backend_support_registry.py b/tests/test_issue755_backend_support_registry.pyindex d08ef924..27665574 100644--- a/tests/test_issue755_backend_support_registry.py+++ b/tests/test_issue755_backend_support_registry.py@@ -30,6 +30,7 @@ import typerfrom soup_cli.config.backend_support import REGISTRY as _REGISTRYfrom soup_cli.config.schema import DataConfig, TrainingConfig+from tests._source_scan import memoized_scanfrom tests.conftest import strip_ansiMLX_SFT = pathlib.Path(__file__).resolve().parents[1] / (@@ -460,7 +461,20 @@ def test_doctor_without_config_does_not_read_one(config_at, capsys):def _fields_read_by(path: pathlib.Path) -> set[str]:"""Attribute names and exact string constants in a module, docstrings out."""- tree = ast.parse(path.read_text(encoding="utf-8"))+ return _names_read_in(path.read_text(encoding="utf-8"))+++@memoized_scan+def _names_read_in(source: str) -> set[str]:+ """The scan behind ``_fields_read_by``, run once per distinct module text.++ ``_registry_drift`` asks for every module under ``src/`` once per registry pair,+ and three tests run it on the real tree: twelve parses of the package for one+ answer. Keyed on the text, so the synthetic trees the tests below write are each+ scanned for what they contain. ``ast.parse`` and not the shared tree, because the+ first loop edits what it walks.+ """+ tree = ast.parse(source)for node in ast.walk(tree):if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)diff --git a/tests/test_issue775_path_containment_ratchet.py b/tests/test_issue775_path_containment_ratchet.pyindex 605788bc..cbf3b971 100644--- a/tests/test_issue775_path_containment_ratchet.py+++ b/tests/test_issue775_path_containment_ratchet.py@@ -56,6 +56,8 @@ import astimport pathlibimport textwrap+from tests._source_scan import memoized_scan, walk_nodes+SRC = pathlib.Path(__file__).resolve().parents[1] / "src" / "soup_cli"_CONTAINMENT_METHODS = frozenset({"relative_to", "is_relative_to"})@@ -87,7 +89,7 @@ ALLOWLIST: dict[tuple[str, int], str] = {def _parent_map(tree: ast.AST) -> dict[ast.AST, ast.AST]:parents: dict[ast.AST, ast.AST] = {}- for node in ast.walk(tree):+ for node in walk_nodes(tree):for child in ast.iter_child_nodes(node):parents[child] = nodereturn parents@@ -132,7 +134,7 @@ def _suppress_names(tree: ast.AST) -> set[str]:``.suppress`` alone."""names = {"suppress"}- for node in ast.walk(tree):+ for node in walk_nodes(tree):if isinstance(node, ast.ImportFrom) and node.module == "contextlib":names.update(a.asname or a.name for a in node.names if a.name == "suppress")return names@@ -208,6 +210,7 @@ def _containment_reason(return None+@memoized_scandef find_containment_relative_to(source: str) -> list[tuple[int, str, str]]:"""Return ``(lineno, call text, reason)`` per containment-deciding call.@@ -222,7 +225,7 @@ def find_containment_relative_to(source: str) -> list[tuple[int, str, str]]:suppress_names = _suppress_names(tree)lines = source.splitlines()offenders: list[tuple[int, str, str]] = []- for node in ast.walk(tree):+ for node in walk_nodes(tree):if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):continueif node.func.attr not in _CONTAINMENT_METHODS:diff --git a/tests/test_source_scan_cache.py b/tests/test_source_scan_cache.pynew file mode 100644index 00000000..4cc893ee--- /dev/null+++ b/tests/test_source_scan_cache.py@@ -0,0 +1,360 @@+"""The parse / walk / memo cache the source-scanning guards share (``tests/_source_scan.py``).++A cache underneath a guard is only acceptable if it cannot change what the guard sees. What+is pinned here:++- ``parse_source`` hands back the tree ``ast.parse`` builds, and is keyed on the TEXT, so a+ file that changed on disk can not be served stale;+- by default it remembers only the last two texts, so a guard that walks a whole tree never+ holds that tree; ``keep=True`` is the explicit way to hold one;+- ``walk_nodes`` is ``ast.walk`` node for node, in the same order;+- ``memoized_scan`` runs a scanner once per input and never lets one caller's edit reach the+ next caller;+- everything is dropped when a test module finishes (``tests/conftest.py``), and "dropped"+ means the trees are freed, not merely unreachable from the cache.+"""++from __future__ import annotations++import ast+import gc+import textwrap+import weakref+from pathlib import Path++import pytest++from tests._source_scan import (+ RECENT_LIMIT,+ memoized_scan,+ parse_source,+ release,+ walk_nodes,+)++TESTS = Path(__file__).resolve().parent+SRC = TESTS.parent / "src" / "soup_cli"++#: One of most things the grammar has, in syntax every supported interpreter (3.10+) parses.+KITCHEN_SINK = textwrap.dedent(+ '''+ """Module docstring."""+ from __future__ import annotations++ import os.path as osp+ from typing import Any++ LIMIT: int = 3+ first, *rest = [1, 2, 3]+++ def decorate(func):+ return func+++ @decorate+ async def fetch(url: str, *args: Any, retries: int = LIMIT, **kwargs) -> dict:+ """Docstring."""+ global LIMIT+ async with open_session(url) as session, other() as second:+ async for chunk in session:+ yield {key: value for key, value in chunk.items() if value}+ try:+ result = await session.get(url)+ except (OSError, ValueError) as exc:+ raise RuntimeError(f"{url!r} failed: {exc:>10}") from exc+ else:+ return {"ok": result[1:-1:2], "raw": result[...]}+ finally:+ del session+++ class Widget(Base, metaclass=Meta):+ size = property(lambda self: self._size if self._size else -1)++ def grow(self, by=1, /, *, cap=None):+ nonlocal_free = [item**2 for row in self.rows for item in row if item % 2]+ while (left := self.size - by) > 0 and not cap:+ by += 1+ if left in {1, 2} or left is None:+ continue+ break+ else:+ pass+ return nonlocal_free, (yield_free for yield_free in ()), not by+++ def classify(command):+ match command:+ case {"kind": "move", "to": (x, y)} if x > y:+ return x+ case [first, *others] | Point(first=first, others=others):+ return others+ case str() as text:+ return text+ case _:+ assert command is not None, "unreachable"+ '''+)+++def _real_sources() -> list[Path]:+ """A fixed, sorted sample of the real tree: every 25th module, plus the largest one."""+ modules = sorted(SRC.rglob("*.py"))+ sample = modules[::25]+ sample.append(SRC / "config" / "schema.py")+ return sample+++class TestParseSource:+ def test_it_is_the_tree_ast_parse_builds(self) -> None:+ texts = [KITCHEN_SINK] + [path.read_text(encoding="utf-8") for path in _real_sources()]+ assert len(texts) > 20, "the real-tree sample came back short"+ for text in texts:+ assert ast.dump(parse_source(text), include_attributes=True) == ast.dump(+ ast.parse(text), include_attributes=True+ )++ def test_one_text_is_parsed_once(self) -> None:+ equal_but_distinct = "".join(["value", " = ", "1\n"])+ assert parse_source("value = 1\n") is parse_source(equal_but_distinct)++ def test_different_text_is_a_different_tree(self) -> None:+ assert parse_source("value = 1\n") is not parse_source("value = 2\n")++ def test_a_file_rewritten_on_disk_is_never_served_stale(self, tmp_path: Path) -> None:+ """The key is the text the guard just read, not the path it read it from.++ Same path, same length, rewritten immediately: the case an mtime-or-path key+ gets wrong, and the one a guard's seeded-violation self-test produces.+ """+ module = tmp_path / "module.py"+ module.write_text("alpha = 1\n", encoding="utf-8")+ before = parse_source(module.read_text(encoding="utf-8"))+ module.write_text("omega = 1\n", encoding="utf-8")+ after = parse_source(module.read_text(encoding="utf-8"))++ assert [node.targets[0].id for node in before.body] == ["alpha"]+ assert [node.targets[0].id for node in after.body] == ["omega"]++ def test_only_the_last_texts_are_remembered_by_default(self) -> None:+ """A guard that walks a whole tree through ``parse_source`` must not end up holding it.++ Holding every tree of ``tests/`` is 551 MB of private bytes, and 524 MB of it stays+ with the worker after ``release()``.+ """+ first = parse_source("first = 1\n")+ walk_nodes(first)+ alive = weakref.ref(first)+ del first+ for index in range(RECENT_LIMIT):+ assert alive() is not None, "still one of the last texts parsed"+ parse_source(f"other_{index} = 1\n")+ gc.collect()+ assert alive() is None, "a tree that fell out of the last texts must be freed"++ def test_keep_holds_a_tree_until_release(self) -> None:+ kept = parse_source("kept = 1\n", keep=True)+ nodes = walk_nodes(kept)+ for index in range(RECENT_LIMIT + 1):+ parse_source(f"other_{index} = 1\n")+ assert parse_source("kept = 1\n") is kept+ assert parse_source("kept = 1\n", keep=True) is kept+ assert walk_nodes(kept) is nodes++ def test_keep_adopts_a_tree_already_parsed(self) -> None:+ recent = parse_source("adopted = 1\n")+ nodes = walk_nodes(recent)+ assert parse_source("adopted = 1\n", keep=True) is recent+ for index in range(RECENT_LIMIT + 1):+ parse_source(f"other_{index} = 1\n")+ assert parse_source("adopted = 1\n") is recent+ assert walk_nodes(recent) is nodes++ def test_a_syntax_error_is_raised_every_time(self) -> None:+ with pytest.raises(SyntaxError) as direct:+ ast.parse("def broken(:\n")+ for _attempt in range(2):+ with pytest.raises(SyntaxError) as cached:+ parse_source("def broken(:\n")+ assert cached.value.msg == direct.value.msg+ assert cached.value.lineno == direct.value.lineno++ def test_a_syntax_error_names_the_file_the_caller_passed(self) -> None:+ """Guards that fail on an unparseable module report its path; that must survive."""+ with pytest.raises(SyntaxError) as failure:+ parse_source("def broken(:\n", filename="src/soup_cli/broken.py")+ assert failure.value.filename == "src/soup_cli/broken.py"++ tree = parse_source("value = 1\n", filename="one.py")+ assert parse_source("value = 1\n", filename="another.py") is tree+++class TestWalkNodes:+ @staticmethod+ def _same_walk(tree: ast.AST) -> None:+ ours = walk_nodes(tree)+ theirs = list(ast.walk(tree))+ assert isinstance(ours, tuple)+ assert len(ours) == len(theirs)+ assert all(mine is stdlib for mine, stdlib in zip(ours, theirs)), (+ "walk_nodes must yield ast.walk's nodes in ast.walk's order"+ )++ def test_it_is_ast_walk_on_every_kind_of_node(self) -> None:+ tree = parse_source(KITCHEN_SINK)+ kinds = {type(node).__name__ for node in ast.walk(tree)}+ assert {"AsyncFunctionDef", "Match", "Lambda", "NamedExpr", "JoinedStr"} <= kinds+ self._same_walk(tree)++ def test_it_is_ast_walk_on_the_real_tree(self) -> None:+ for path in _real_sources():+ self._same_walk(parse_source(path.read_text(encoding="utf-8")))++ def test_it_is_ast_walk_on_a_tree_it_did_not_parse(self) -> None:+ self._same_walk(ast.parse(KITCHEN_SINK))++ def test_a_subtree_is_walked_from_that_node(self) -> None:+ tree = parse_source(KITCHEN_SINK)+ function = next(node for node in tree.body if isinstance(node, ast.AsyncFunctionDef))+ self._same_walk(function)+ assert walk_nodes(function)[0] is function+ assert len(walk_nodes(function)) < len(walk_nodes(tree))++ def test_a_tree_from_parse_source_is_flattened_once(self) -> None:+ tree = parse_source(KITCHEN_SINK)+ assert walk_nodes(tree) is walk_nodes(tree)++ def test_a_tree_from_elsewhere_is_not_retained(self) -> None:+ """Only trees this module handed out are kept: nothing else has a release point."""+ foreign = ast.parse(KITCHEN_SINK)+ assert walk_nodes(foreign) is not walk_nodes(foreign)+++class TestMemoizedScan:+ def test_a_scanner_runs_once_per_distinct_input(self) -> None:+ calls: list[str] = []++ @memoized_scan+ def scan(source: str) -> list[str]:+ calls.append(source)+ return source.split()++ assert scan("a b") == ["a", "b"]+ assert scan("a b") == ["a", "b"]+ assert scan("c") == ["c"]+ assert calls == ["a b", "c"]++ def test_each_caller_gets_its_own_copy(self) -> None:+ @memoized_scan+ def scan(source: str) -> list[str]:+ return source.split()++ first = scan("a b")+ first.append("smuggled")+ assert scan("a b") == ["a", "b"]++ @memoized_scan+ def names(source: str) -> set[str]:+ return set(source.split())++ mine = names("a b")+ mine |= {"smuggled"}+ assert names("a b") == {"a", "b"}++ def test_keyword_arguments_are_part_of_the_key(self) -> None:+ @memoized_scan+ def scan(source: str, upper: bool = False) -> list[str]:+ return source.upper().split() if upper else source.split()++ assert scan("a b") == ["a", "b"]+ assert scan("a b", upper=True) == ["A", "B"]++ def test_a_failure_is_not_cached(self) -> None:+ attempts: list[str] = []++ @memoized_scan+ def scan(source: str) -> list[str]:+ attempts.append(source)+ raise SyntaxError("nope")++ for _attempt in range(2):+ with pytest.raises(SyntaxError):+ scan("x")+ assert attempts == ["x", "x"]++ def test_the_scanner_keeps_its_name_and_docstring(self) -> None:+ @memoized_scan+ def find_things(source: str) -> list[str]:+ """Find things."""+ return [source]++ assert find_things.__name__ == "find_things"+ assert find_things.__doc__ == "Find things."+++class TestRelease:+ def test_release_drops_trees_walks_and_memos(self) -> None:+ """ "Dropped" is checked with weak references: the trees have to die.++ Identity alone cannot see a cache that forgot the text and still holds the tree in+ its second map. That mutation (``release()`` without ``_BY_TREE.clear()``) passed+ the first version of this test, with every tree of the module still alive.+ """+ calls: list[str] = []++ @memoized_scan+ def scan(source: str) -> list[str]:+ calls.append(source)+ return [source]++ kept = parse_source("kept = 1\n", keep=True)+ recent = parse_source("recent = 1\n")+ kept_nodes, recent_nodes = walk_nodes(kept), walk_nodes(recent)+ # [1] is the Assign statement. Not [-1]: that is ast.Store(), one shared object.+ alive = [weakref.ref(node) for node in (kept, recent, kept_nodes[1], recent_nodes[1])]+ scan("x")++ release()++ assert parse_source("kept = 1\n", keep=True) is not kept+ assert parse_source("recent = 1\n") is not recent+ scan("x")+ assert calls == ["x", "x"]++ del kept, recent, kept_nodes, recent_nodes+ gc.collect()+ assert [ref() for ref in alive] == [None] * 4, (+ "release() must free the trees it held, not only forget their text"+ )++ def test_every_test_module_releases_when_it_finishes(+ self, request: pytest.FixtureRequest+ ) -> None:+ """The wiring in ``tests/conftest.py``: autouse, module-scoped, releases after the yield.++ Without it the trees a guard kept stay alive for the rest of the worker (283 MB of+ private bytes for ``src/soup_cli``), and every later ``gc.collect()`` in that worker+ walks them (0.6 ms -> 230 ms, measured on the dev box).+ """+ assert "_release_scanned_sources" in request.fixturenames, (+ "the release fixture must be autouse: this test did not ask for it"+ )++ conftest = ast.parse((TESTS / "conftest.py").read_text(encoding="utf-8"))+ fixture = next(+ node+ for node in conftest.body+ if isinstance(node, ast.FunctionDef) and node.name == "_release_scanned_sources"+ )+ decorator = ast.unparse(fixture.decorator_list[0])+ assert decorator.startswith("pytest.fixture(")+ assert 'scope="module"' in decorator.replace("'", '"')+ assert "autouse=True" in decorator++ statements = [ast.unparse(statement) for statement in fixture.body]+ assert "yield" in statements+ after_yield = statements[statements.index("yield") + 1 :]+ assert "_source_scan.release()" in after_yield, (+ "the cache must be released AFTER the module's tests ran, not before"+ )