Repository: python/mypy

Issue:
`AssertionError` with nested TypeVar
**Crash Report**

Encountered this issue while testing the current master branch with Home Assistant (with all requirements installed).
Bisected it to #14095.

/CC: @ilevkivskyi

**Traceback**

```
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 553, in serialize
    assert not self.id.is_meta_var()
AssertionError
```

<details>
<summary>Full traceback</summary>

```
  File "/home/runner/work/ha-core/ha-core/venv/bin/mypy", line 8, in <module>
    sys.exit(console_entry())
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/__main__.py", line 15, in console_entry
    main()
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/main.py", line 95, in main
    res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/main.py", line 174, in run_build
    res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 193, in build
    result = _build(
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 276, in _build
    graph = dispatch(sources, manager, stdout)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 2900, in dispatch
    process_graph(graph, manager)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 3288, in process_graph
    process_stale_scc(graph, scc, manager)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 3411, in process_stale_scc
    graph[id].write_cache()
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 2481, in write_cache
    new_interface_hash, self.meta = write_cache(
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/build.py", line 1571, in write_cache
    data = tree.serialize()
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/nodes.py", line 379, in serialize
    "names": self.names.serialize(self._fullname),
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/nodes.py", line 3779, in serialize
    data[key] = value.serialize(fullname, key)
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/nodes.py", line 3716, in serialize
    data["node"] = self.node.serialize()
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/nodes.py", line 1034, in serialize
    "type": None if self.type is None else self.type.serialize(),
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 1322, in serialize
    data["args"] = [arg.serialize() for arg in self.args]
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 1322, in <listcomp>
    data["args"] = [arg.serialize() for arg in self.args]
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 2016, in serialize
    "arg_types": [t.serialize() for t in self.arg_types],
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 2016, in <listcomp>
    "arg_types": [t.serialize() for t in self.arg_types],
  File "/home/runner/work/ha-core/ha-core/venv/lib/python3.9/site-packages/mypy/types.py", line 553, in serialize
    assert not self.id.is_meta_var()
AssertionError
```
</details>

I did add some debugging calls before the `AssertionError`. The serialization for this object failed
```py
{
  '.class': 'TypeVarType', 'name': '_ZhaEntityT',
  'fullname': 'homeassistant.components.zha.core.registries._ZhaEntityT',
  'id': 13429, 'namespace': '', 'values': [], 'upper_bound': {
    '.class': 'TypeType', 'item': 'homeassistant.components.zha.entity.ZhaEntity'
  }, 'variance': 0
}
```

**To Reproduce**

Unfortunately I wasn't yet able to narrow it further to a short code sample.

However, it is easily reproducible with Home Assistant
* Check out [Home Assistant](https://github.com/home-assistant/core)
* Install `attrs==21.2.0` or `types-attrs==19.1.0` (only dependency required to reproduce the error it
* Run `mypy homeassistant/components/zha/core`

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: `mypy 1.0.0+dev.a2477ff0d0cb751f27a2b38d27ce6572ead03451 `
- Mypy configuration options from `mypy.ini` (and other config files): see Home Assistant repo
- Python version used: `3.9`
- Operating system and version: `Github actions -> Ubuntu-20.04`


Discussion:
It looks like `attrs` is not important here, a simple repro for the crash:
```
[case testIncrementalNestedGenericCallableCrash]
from typing import TypeVar, Callable

T = TypeVar("T")

class B:
    def foo(self) -> Callable[[T], T]: ...

class C(B):
    def __init__(self) -> None:
        self.x = self.foo()
[out]
[out2]
```

Resolving patch:
diff --git a/mypy/checkmember.py b/mypy/checkmember.py
--- a/mypy/checkmember.py
+++ b/mypy/checkmember.py
@@ -806,6 +806,7 @@ class FreezeTypeVarsVisitor(TypeTraverserVisitor):
     def visit_callable_type(self, t: CallableType) -> None:
         for v in t.variables:
             v.id.meta_level = 0
+        super().visit_callable_type(t)
 
 
 def lookup_member_var_or_accessor(info: TypeInfo, name: str, is_lvalue: bool) -> SymbolNode | None:


Test patch:
diff --git a/test-data/unit/check-incremental.test b/test-data/unit/check-incremental.test
--- a/test-data/unit/check-incremental.test
+++ b/test-data/unit/check-incremental.test
@@ -6334,3 +6334,17 @@ reveal_type(D().meth)
 [out2]
 tmp/m.py:4: note: Revealed type is "def [Self <: lib.C] (self: Self`0, other: Self`0) -> Self`0"
 tmp/m.py:5: note: Revealed type is "def (other: m.D) -> m.D"
+
+[case testIncrementalNestedGenericCallableCrash]
+from typing import TypeVar, Callable
+
+T = TypeVar("T")
+
+class B:
+    def foo(self) -> Callable[[T], T]: ...
+
+class C(B):
+    def __init__(self) -> None:
+        self.x = self.foo()
+[out]
+[out2]