#4629·ty

AsyncGenerator return annotation causes large slowdown for async context manager yielding a recursive protocol

Author: jelle-openaiCreated Sep 30, 2026Updated Sep 30, 2026
Labelsperformanceoverloadsprotocols

Summary

With ty 0.0.84, a correct AsyncGenerator[Node, None] return annotation on an @asynccontextmanager function takes increasingly long to check as the recursive Node protocol grows. The equivalent AsyncIterator[Node] annotation checks quickly. The body of the function is identical, both variants pass without diagnostics, and no third-party dependencies are involved.

To reproduce, put ty 0.0.84 on PATH, save the following as repro.py, and run python3 repro.py from anywhere. Alternatively set TY to the executable's path. It generates a fresh source file in an empty temporary directory to avoid picking up any project configuration. The generated Python is deliberately repetitive to show how run time scales with the number of protocol members.

python
"""Run with Python 3.12+ and ty 0.0.84 on PATH, or set TY to the ty executable."""
import os
from pathlib import Path
import subprocess
import tempfile
import time

ty = os.environ.get("TY", "ty")
print(subprocess.check_output([ty, "--version"], text=True).strip(), flush=True)

with tempfile.TemporaryDirectory() as directory:
    for members in (24, 48, 96, 192):
        for annotation in ("AsyncIterator[Node]", "AsyncGenerator[Node, None]"):
            source = (
                "from __future__ import annotations\n"
                "from collections.abc import AsyncGenerator, AsyncIterator\n"
                "from contextlib import asynccontextmanager\n"
                "from typing import Any, Protocol\n\n"
                "class Node(Protocol):\n"
            )
            for i in range(members):
                source += (
                    f"    def edit_{i}(self, nodes: list[Node]) -> list[Node]: ...\n"
                )
            source += (
                "\n@asynccontextmanager\n"
                f"async def acquire(factory: Any) -> {annotation}:\n"
                "    async with factory() as value:\n"
                "        yield value\n"
            )
            path = Path(directory) / "example.py"
            path.write_text(source)
            start = time.monotonic()
            try:
                result = subprocess.run(
                    [ty, "check", "--python-version", "3.13", str(path)],
                    cwd=directory,
                    env={**os.environ, "TY_MAX_PARALLELISM": "1"},
                    capture_output=True,
                    text=True,
                    timeout=60,
                )
                seconds = time.monotonic() - start
                print(f"{members:3} {annotation:27} {seconds:8.3f}s exit={result.returncode}", flush=True)
                if result.returncode:
                    print(result.stdout, result.stderr)
                    raise SystemExit(result.returncode)
            except subprocess.TimeoutExpired:
                print(f"{members:3} {annotation:27} >60s TIMEOUT", flush=True)

Observed (Linux, ty 0.0.84, --python-version 3.13, TY_MAX_PARALLELISM=1):

ty 0.0.84
 24 AsyncIterator[Node]            0.033s exit=0
 24 AsyncGenerator[Node, None]     0.043s exit=0
 48 AsyncIterator[Node]            0.030s exit=0
 48 AsyncGenerator[Node, None]     0.132s exit=0
 96 AsyncIterator[Node]            0.030s exit=0
 96 AsyncGenerator[Node, None]     1.152s exit=0
192 AsyncIterator[Node]            0.036s exit=0
192 AsyncGenerator[Node, None]    13.693s exit=0

Expected: both valid return annotations should check in roughly comparable time for the same protocol and body. Some extra checking for AsyncGenerator is fine, but a few hundred protocol members should not make annotation-only changes cause timeouts in otherwise passing projects.

Actual: at 192 members the generator annotation takes ~380x as long as the iterator annotation. Doubling the protocol from 96 to 192 members increases that time from ~1.15s to ~13.69s. Timing varies with hardware; the trend is the issue.

Notes:

  • The protocol uses list[Node] in both parameter and return position.
  • No protocol implementation needs to be checked: the context manager receives its input as Any.
  • The script prints ty's version, both exit codes, and elapsed time for each size.

Version

No response