Repository: python/mypy
Issue category: Bug Report

Crash on sequence match statement in generic class with restricted type variable bound to sequence
<!--
  Use this form only if mypy reports an "INTERNAL ERROR" and/or gives a traceback.
  Please include the traceback and all other messages below (use `mypy --show-traceback`).
-->

**Crash Report**

mypy crashes when the following conditions are met:
1. A generic class is present.
2. The generic class refers to a typevar `T` that is bound to a sequence.
3. The generic class has a method that attempts to pattern match a method parameter of type `T`
4. One of the pattern matching cases is a sequence pattern such as `_, _`.

This crash is similar to but distinct from this issue: https://github.com/python/mypy/issues/12448

**Traceback**

```
$ mypy mypy_mre.py --show-traceback
mypy_mre.py:7: error: INTERNAL ERROR -- Please try using mypy master on GitHub:
https://mypy.readthedocs.io/en/stable/common_issues.html#using-a-development-mypy-build
Please report a bug at https://github.com/python/mypy/issues
version: 1.14.0+dev.05a9e79068a5830e57264390c9f6bca859e92053
Traceback (most recent call last):
  File "~/venv-3.11.6/bin/mypy", line 8, in <module>
    sys.exit(console_entry())
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/__main__.py", line 15, in console_entry
    main()
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/main.py", line 109, in main
    res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/main.py", line 193, in run_build
    res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 194, in build
    result = _build(
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 269, in _build
    graph = dispatch(sources, manager, stdout)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 2937, in dispatch
    process_graph(graph, manager)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 3335, in process_graph
    process_stale_scc(graph, scc, manager)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 3436, in process_stale_scc
    graph[id].type_check_first_pass()
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/build.py", line 2306, in type_check_first_pass
    self.type_checker().check_first_pass()
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 483, in check_first_pass
    self.accept(d)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 592, in accept
    stmt.accept(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/nodes.py", line 1196, in accept
    return visitor.visit_class_def(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 2461, in visit_class_def
    self.accept(defn.defs)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 592, in accept
    stmt.accept(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/nodes.py", line 1277, in accept
    return visitor.visit_block(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 2951, in visit_block
    self.accept(s)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 592, in accept
    stmt.accept(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/nodes.py", line 827, in accept
    return visitor.visit_func_def(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 1046, in visit_func_def
    self._visit_func_def(defn)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 1050, in _visit_func_def
    self.check_func_item(defn, name=defn.name)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 1084, in check_func_item
    self.check_func_def(defn, typ, name, allow_empty)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 1360, in check_func_def
    self.accept(item.body)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 592, in accept
    stmt.accept(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/nodes.py", line 1277, in accept
    return visitor.visit_block(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 2951, in visit_block
    self.accept(s)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 592, in accept
    stmt.accept(self)
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/nodes.py", line 1661, in accept
    return visitor.visit_match_stmt(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 5298, in visit_match_stmt
    pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checker.py", line 5298, in <listcomp>
    pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checkpattern.py", line 129, in accept
    result = o.accept(self)
             ^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/patterns.py", line 93, in accept
    return visitor.visit_sequence_pattern(self)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checkpattern.py", line 345, in visit_sequence_pattern
    new_type = self.construct_sequence_child(current_type, new_inner_type)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "~/venv-3.11.6/lib/python3.11/site-packages/mypy/checkpattern.py", line 766, in construct_sequence_child
    assert isinstance(proper_type, Instance)
AssertionError: 
mypy_mre.py:7: : note: use --pdb to drop into pdb
```

**To Reproduce**

Here is an MRE:

```python
from typing import Generic, TypeVar, Sequence, Any

T = TypeVar("T", bound=Sequence[Any])

class C(Generic[T]):
    def f(self, x: T) -> None:
        match x:
            case _, _:
                pass
            case _:
                pass
```

**Your Environment**

<!-- Include as many relevant details about the environment you experienced the bug in -->

- Mypy version used: 1.14.0+dev.05a9e79068a5830e57264390c9f6bca859e92053 (current master)
- Mypy command-line flags: None
- Mypy configuration options from `mypy.ini` (and other config files):
```toml
check_untyped_defs = true
disallow_any_generics = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
extra_checks = true
no_implicit_reexport = true
python_version = "3.11"
strict_equality = true
warn_redundant_casts = true
warn_return_any = true
warn_unused_configs = true
warn_unused_ignores = true
  ```
- Python version used: 3.11.6
- Operating system and version: AlmaLinux 9.4 under WSL 2 on Windows 10

<!--
You can freely edit this text, please remove all the lines
you believe are unnecessary.
-->



Functions to edit:
mypy/checkpattern.py:PatternChecker.visit_sequence_pattern
Functions added: mypy/checkpattern.py:PatternChecker.narrow_sequence_child

Patch:
diff --git a/mypy/checkpattern.py b/mypy/checkpattern.py
index 6b4fa35f9c49..f54b3c53f907 100644
--- a/mypy/checkpattern.py
+++ b/mypy/checkpattern.py
@@ -46,6 +46,7 @@
     TypedDictType,
     TypeOfAny,
     TypeVarTupleType,
+    TypeVarType,
     UninhabitedType,
     UnionType,
     UnpackType,
@@ -342,13 +343,11 @@ def visit_sequence_pattern(self, o: SequencePattern) -> PatternType:
             new_inner_type = UninhabitedType()
             for typ in new_inner_types:
                 new_inner_type = join_types(new_inner_type, typ)
-            new_type = self.construct_sequence_child(current_type, new_inner_type)
-            if is_subtype(new_type, current_type):
-                new_type, _ = self.chk.conditional_types_with_intersection(
-                    current_type, [get_type_range(new_type)], o, default=current_type
-                )
+            if isinstance(current_type, TypeVarType):
+                new_bound = self.narrow_sequence_child(current_type.upper_bound, new_inner_type, o)
+                new_type = current_type.copy_modified(upper_bound=new_bound)
             else:
-                new_type = current_type
+                new_type = self.narrow_sequence_child(current_type, new_inner_type, o)
         return PatternType(new_type, rest_type, captures)
 
     def get_sequence_type(self, t: Type, context: Context) -> Type | None:
@@ -447,6 +446,16 @@ def expand_starred_pattern_types(
 
         return new_types
 
+    def narrow_sequence_child(self, outer_type: Type, inner_type: Type, ctx: Context) -> Type:
+        new_type = self.construct_sequence_child(outer_type, inner_type)
+        if is_subtype(new_type, outer_type):
+            new_type, _ = self.chk.conditional_types_with_intersection(
+                outer_type, [get_type_range(new_type)], ctx, default=outer_type
+            )
+        else:
+            new_type = outer_type
+        return new_type
+
     def visit_starred_pattern(self, o: StarredPattern) -> PatternType:
         captures: dict[Expression, Type] = {}
         if o.capture is not None:

Test patch: diff --git a/test-data/unit/check-python310.test b/test-data/unit/check-python310.test
index 58b70d7b74d8..f6f4c9cf167f 100644
--- a/test-data/unit/check-python310.test
+++ b/test-data/unit/check-python310.test
@@ -2343,3 +2343,30 @@ def test(xs: Tuple[Unpack[Ts]]) -> None:
             reveal_type(b3)  # N: Revealed type is "builtins.list[builtins.object]"
             reveal_type(c3)  # N: Revealed type is "builtins.int"
 [builtins fixtures/tuple.pyi]
+
+[case testMatchSequencePatternTypeVarBoundNoCrash]
+# This was crashing: https://github.com/python/mypy/issues/18089
+from typing import TypeVar, Sequence, Any
+
+T = TypeVar("T", bound=Sequence[Any])
+
+def f(x: T) -> None:
+    match x:
+        case [_]:
+            pass
+[builtins fixtures/tuple.pyi]
+
+[case testMatchSequencePatternTypeVarBoundNarrows]
+from typing import TypeVar, Sequence
+
+T = TypeVar("T", bound=Sequence[int | str])
+
+def accept_seq_int(x: Sequence[int]): ...
+
+def f(x: T) -> None:
+    match x:
+        case [1, 2]:
+            accept_seq_int(x)
+        case _:
+            accept_seq_int(x)  # E: Argument 1 to "accept_seq_int" has incompatible type "T"; expected "Sequence[int]"
+[builtins fixtures/tuple.pyi]