← Back to Pull requests

[ty] Detect more invalid partially quoted unions, and improve diagnostics #31321

Open
AlexWaygood opened this pull request with 286 lines diff across 3 files
View on GitHub
AlexWaygood AlexWaygood commented on Dec 03, 2026 14:55 UTC
Author

Summary

On Python 3.13, defining f below raises a TypeError. ty already caught this if you wrote int | "Foo" directly, but missed it when the string came from a PEP 613 type alias.

from typing import TypeAlias

Alias: TypeAlias = "Foo"

def f(x: int | Alias): ...

class Foo: ...

ty now reports unsupported-operator and suggests quoting the whole union ("int | Alias") to avoid the error when defining f.

Python 3.14 and later defer function annotations by default, but still evaluate the right-hand side of an assignment like X = list["int" | None] immediately. ty now suggests quoting the whole union there too.

The check also now catches string operands combined with enum classes, PEP 695 aliases, type[int], and existing unions such as int | None. That last case depends on the Python version. On Python 3.13, int | None | "str" fails because int | None produces a types.UnionType. On Python 3.14, int | None produces a typing.Union, which accepts being |'d with the string (implicitly converting the string to a forward reference).

This also fixes false positives for user-defined generic classes. Given class Stream[T]: ..., Stream[bytes] is a typing._GenericAlias, so Stream[bytes] | "str" accepts the string as a forward reference. list[bytes] is a types.GenericAlias, so list[bytes] | "str" raises a TypeError.

We don't generally track which kind of generic alias subscripting a class produces. To avoid false positives, therefore, this PR introduces a heuristic where we only assume a generic alias rejects strings if the class being subscripted is one we recognize from builtins or types. This means we'll continue to miss some invalid unions.

The distinction also matters in chained unions. For example, Dulwich uses BufferedIOBase | IO[bytes] | "_GitFile". Because IO[bytes] is a typing._GenericAlias, the first | produces a typing.Union even before Python 3.14. The second | can therefore accept "_GitFile" as a forward reference. An early version of this PR introduced false positives on this code; distinguishing between builtins aliases (that we know are types.GenericAliases at runtime) and other aliases helps avoid those new false positives.

Diff: 286 lines (+238 / -48) across 3 files Reviewer: AlexWaygood Review duration: 2312m
All Vouch review confidence checks passed
Residual risk 0.10 = Change Risk (0.54) × (1 − Review Confidence (0.81)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.54 · 286 lines diff across 3 files
0.54
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.84 · 5 substantive comment(s)
0.84
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
81%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.339
Self Review self_review
0.140
Real PR Conversation Timeline
14 items
astral-automations-bot[bot] astral-automations-bot[bot] commented on Dec 03, 2026 14:58 UTC
Bot

<!-- generated-comment typing-conformance -->
<!-- report-run:47161351731:1 -->

Typing conformance results

No changes detected ✅

<details>
<summary>Current numbers</summary>

<br>
The percentage of diagnostics emitted that were expected errors held steady at <b>98.60%</b>. The percentage of expected errors that received a diagnostic held steady at <b>98.86%</b>. The number of fully passing files held steady at <b>137/146</b>.

</details>

---

Results for 7bc2d6e · Workflow run

astral-automations-bot[bot] astral-automations-bot[bot] commented on Dec 03, 2026 14:59 UTC
Bot

<!-- generated-comment memory -->
<!-- report-run:47161351765:1 -->

Memory usage report

Memory usage unchanged ✅

---

Results for 7bc2d6e · Workflow run

astral-automations-bot[bot] astral-automations-bot[bot] commented on Dec 03, 2026 15:01 UTC
Bot

<!-- generated-comment ty-ecosystem -->
<!-- report-run:47161351939:1 -->

ecosystem-analyzer results

No diagnostic changes detected ✅

Full report with detailed diff · Timing results

---

Results for 7bc2d6e · Workflow run

codspeed[bot] codspeed[bot] commented on Dec 03, 2026 15:09 UTC
Bot

<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->

Merging this PR will degrade performance by 5.96%

❌ 1 regressed benchmark
✅ 362 untouched benchmarks
⏩ 92 skipped benchmarks[^skipped]

[!WARNING]

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ❌ | Walltime | ` simple_script | 16.2 ms | 17.3 ms | -5.96% |

[!TIP]

Investigate this regression by commenting @codspeedbot fix this regression` on this PR, or directly use the CodSpeed MCP with your agent.

---

<sub>Comparing <code>alex/partially-quoted-unions</code> (7bc2d6e) with <code>main</code> (72366af)</sub>

<a href="https://app.codspeed.io/astral-sh/ruff/branches/alex%2Fpartially-quoted-unions?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>

[^skipped]: 92 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

AlexWaygood AlexWaygood commented on code on Dec 03, 2026 17:38 UTC
Code Review
crates/ty_python_semantic/resources/mdtest/annotations/string.md:1
@@ -168,14 +169,52 @@ from typing import TypeAlias
 
 Alias: TypeAlias = "Foo"
 
-# TODO: Report [unsupported-operator] here.
+# snapshot: unsupported-operator
 def f(x: int | Alias):
     reveal_type(x)  # revealed: int | Foo
 
 def g(x: "int | Alias"):  # ok
     reveal_type(x)  # revealed: int | Foo
 ```
 
+```snapshot
+error[unsupported-operator]: Unsupported `|` operation
+  --> src/mdtest_snippet.py:24:10
+   |
+24 | def f(x: int | Alias):
+   |          ---^^^-----
+   |          |     |
+   |          |     Has type `str`
+   |          Has type `<class 'int'>`
+info: All parameter annotations are evaluated at runtime by default on Python <3.14
+info: Python 3.13 was assumed when inferring types because it was specified on the command line
+help: Put quotes around the whole union rather than just certain elements

it would be great to also show the definition of the alias here in a secondary annotation, but it's a bit more work; I'll do that in a followup. (It would also be great to have an autofix, but that's also going to be a followup!)

AlexWaygood AlexWaygood commented on Dec 03, 2026 21:00 UTC
Author

that benchmark has generally been pretty flaky recently, and I don't see any reason why this would cause any regressions, so I disbelieve that there's really a regression here.

carljm carljm commented on code on Dec 03, 2026 23:17 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1345,6 +1349,62 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
         left_type_value: Type<'db>,
         right_type_value: Type<'db>,
     ) {
+        /// Typeshed annotates `__or__` and `__ror__` on `type` and `types.GenericAlias` as
+        /// accepting `Any`, so dunder lookup can miss invalid unions with non-enum literals,
+        /// including strings bound to PEP 613 aliases.
+        fn rejects_literal<'db>(
+            db: &'db dyn Db,
+            env: &ProgramEnvironment<'db>,
+            ty: Type<'db>,
+        ) -> bool {
+            match ty {
+                // `typing._GenericAlias`es are actually more lenient than `types.GenericAlias`es.
+                // We don't generally try to distinguish between the two, but we do happen to know
+                // that everything in these specific modules is implemented in C, so it'll be a
+                // `types.GenericAlias` when parametrized rather than a `typing._GenericAlias`.
+                Type::GenericAlias(alias) => alias.origin(db).known(db).is_some_and(|class| {
+                    matches!(
+                        class.canonical_module(env.python_version(db)),
+                        KnownModule::Builtins | KnownModule::Types
+                    )
+                }),
+
+                // `typing.Type[]` is actually more lenient than `type[]` here:
+                // the first can be unioned with strings using `|`, while the
+                // second cannot. But `typing.Type[]` is deprecated since 3.9,
+                // so we don't try to account for that here.
+                Type::KnownInstance(KnownInstanceType::TypeGenericAlias(_)) => true,
+
+                Type::KnownInstance(KnownInstanceType::TypeAliasType(_)) => true,
+
+                Type::KnownInstance(KnownInstanceType::UnionType(instance)) => {
+                    // if `rejects_literal` returns `false` for any element, it probably means
+                    // that the element is a `TypeVar` or similar. If that's the case, the union
+                    // will be a `typing.py` union rather than a `types.UnionType` union, and
+                    // `typing.py` unions can be `|`'d with a string literal even on Python <3.14
+                    env.python_version(db) < PythonVersion::PY314
+                        && instance
+                            .value_expression_types(db, env)

I think we need to preserve the distinction between typing.Union and types.UnionType here. We now report unsupported-operator for all three of these on Python 3.13, but they all work at runtime.

from typing import Optional, Union

def f(
    x: Optional[int] | "str",
    y: Union[int, bytes] | "str",
    z: bytes | Optional[int] | "str",
): ...

carljm carljm commented on code on Dec 03, 2026 23:17 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1345,6 +1349,62 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
         left_type_value: Type<'db>,
         right_type_value: Type<'db>,
     ) {
+        /// Typeshed annotates `__or__` and `__ror__` on `type` and `types.GenericAlias` as
+        /// accepting `Any`, so dunder lookup can miss invalid unions with non-enum literals,
+        /// including strings bound to PEP 613 aliases.
+        fn rejects_literal<'db>(
+            db: &'db dyn Db,
+            env: &ProgramEnvironment<'db>,
+            ty: Type<'db>,
+        ) -> bool {
+            match ty {
+                // `typing._GenericAlias`es are actually more lenient than `types.GenericAlias`es.
+                // We don't generally try to distinguish between the two, but we do happen to know
+                // that everything in these specific modules is implemented in C, so it'll be a
+                // `types.GenericAlias` when parametrized rather than a `typing._GenericAlias`.
+                Type::GenericAlias(alias) => alias.origin(db).known(db).is_some_and(|class| {

The limitation mentioned below for typing.Type also applies to e.g. typing.List. We now get new false positives for both of these on Python 3.13.

from typing import List, TypeAlias

Alias: TypeAlias = "str"

def f(x: List[int] | Alias, y: bytes | List[int] | "str"): ...

Both work at runtime.

I realize these are deprecated, but that doesn't mean they aren't still used. I don't think we should cause these false positives until these aliases are actually gone from all supported versions.

carljm carljm commented on code on Dec 03, 2026 23:17 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1345,6 +1349,62 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
         left_type_value: Type<'db>,
         right_type_value: Type<'db>,
     ) {
+        /// Typeshed annotates `__or__` and `__ror__` on `type` and `types.GenericAlias` as
+        /// accepting `Any`, so dunder lookup can miss invalid unions with non-enum literals,
+        /// including strings bound to PEP 613 aliases.
+        fn rejects_literal<'db>(
+            db: &'db dyn Db,
+            env: &ProgramEnvironment<'db>,
+            ty: Type<'db>,
+        ) -> bool {
+            match ty {
+                // `typing._GenericAlias`es are actually more lenient than `types.GenericAlias`es.
+                // We don't generally try to distinguish between the two, but we do happen to know
+                // that everything in these specific modules is implemented in C, so it'll be a
+                // `types.GenericAlias` when parametrized rather than a `typing._GenericAlias`.
+                Type::GenericAlias(alias) => alias.origin(db).known(db).is_some_and(|class| {
+                    matches!(
+                        class.canonical_module(env.python_version(db)),
+                        KnownModule::Builtins | KnownModule::Types
+                    )
+                }),
+
+                // `typing.Type[]` is actually more lenient than `type[]` here:
+                // the first can be unioned with strings using `|`, while the
+                // second cannot. But `typing.Type[]` is deprecated since 3.9,
+                // so we don't try to account for that here.
+                Type::KnownInstance(KnownInstanceType::TypeGenericAlias(_)) => true,
+
+                Type::KnownInstance(KnownInstanceType::TypeAliasType(_)) => true,

I found a case where an operand rejects a string itself but produces a union that accepts one. With Python 3.11 and typing_extensions 4.16, the first of these raises and the second works. We now flag both.

from typing_extensions import TypeAliasType

A = TypeAliasType("A", int)
def f(x: A | "str"): ...
def g(x: A | bytes | "str"): ...

The backport's __or__ returns a typing.Union.

carljm carljm commented on code on Dec 03, 2026 23:17 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1447,14 +1490,21 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
                             &mut diagnostic,
                             "inferring types",
                         );
-                        if binary.left.is_string_literal_expr()
-                            || binary.right.is_string_literal_expr()
-                        {
-                            diagnostic.help(
-                                "Put quotes around the whole union \
+                    }
+                    let is_likely_stringized_annotation = |expr: &ast::Expr, ty: Type<'db>| {

Could we move the help outside the match on scope kind? For example, on Python 3.13 we now diagnose this but only give the unrelated note about lazy evaluation of type parameters.

from typing import TypeAlias

Alias: TypeAlias = "str"

def f[T](x: T, y: int | Alias): ...

There's already a TODO in the mdtest about fixing that note. It seems like we could give the same help for generic and non-generic functions independently of that.

carljm carljm commented on code on Dec 03, 2026 23:17 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1356,35 +1416,20 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
         )
         .is_err();
 
-        // As well as trying the normal dunder lookup,
-        // we also check for the case where one of the operands is a class-literal type
-        // or generic-alias type and the other is a string literal. The normal dunder lookup
-        // fails to catch this error, since typeshed annotates `type.__(r)or__` as accepting `Any`.
-        // ABCMeta and _ProtocolMeta inherit these operators unchanged. The typeshed
-        // protocol fallback does not establish a custom operator either.
-        let should_emit_error = if dunder_fails {
-            true
-        } else {
-            let literal = match (left_type_value, right_type_value) {
-                (Type::ClassLiteral(class), Type::LiteralValue(literal))
-                | (Type::LiteralValue(literal), Type::ClassLiteral(class))
-                    if matches!(
-                        class
-                            .inferred_metaclass(db)
-                            .for_inheritance(db, env)
-                            .to_class_type(db)
-                            .and_then(|metaclass| metaclass.known(db)),
-                        Some(KnownClass::Type | KnownClass::ABCMeta | KnownClass::ProtocolMeta)
-                    ) =>
-                {
-                    Some(literal)
+        let should_emit_error = dunder_fails
+            || match (left_type_value, right_type_value) {
+                (Type::LiteralValue(literal), other) | (other, Type::LiteralValue(literal)) => {
+                    // arbitrary enum members can overload `__(r)or__`, so we don't know that they definitely
+                    // cannot be combined with other literal types using `|` (and `dunder_fails` will probably
+                    // already be `false` in the earlier check if their custom `__(r)or__` rejects strings)

I think the boolean in the parenthetical is backwards? If neither operator accepts the operands, wouldn't dunder_fails be true and we'd skip this match? Maybe just drop the parenthetical?

carljm carljm commented on Dec 03, 2026 23:40 UTC
Reviewer

This PR does two things, "detect more invalid partially-quoted unions" and "improve diagnostics." The second one is great, and I'm all in favor of it. But "catching more cases" I think offers little practical value, and wades into areas where we cannot avoid adding false positives. I don't think we should be emitting this diagnostic in cases which require us to attempt an unreliable heuristic distinction between typing._GenericAlias and types.GenericAlias, or between types.UnionType and typing.Union. I would prefer we scale back the ambition here and keep this diagnostic (which other type checkers don't even attempt, and which I have not seen users express high demand for) as high-confidence as possible, strongly preferring false negatives over false positives. (It seems somewhat ironic that the user-reported issue that prompted looking into this in the first place was a false-positive report, and this PR would respond to that report by making the diagnostic more aggressive and adding some false positives.)

carljm carljm commented on code on Dec 03, 2026 23:47 UTC
Code Review
crates/ty_python_semantic/src/types/infer/builder/type_expression.rs:1
@@ -1345,6 +1349,62 @@ impl<'db> TypeInferenceBuilder<'db, '_> {
         left_type_value: Type<'db>,
         right_type_value: Type<'db>,
     ) {
+        /// Typeshed annotates `__or__` and `__ror__` on `type` and `types.GenericAlias` as
+        /// accepting `Any`, so dunder lookup can miss invalid unions with non-enum literals,
+        /// including strings bound to PEP 613 aliases.
+        fn rejects_literal<'db>(
+            db: &'db dyn Db,
+            env: &ProgramEnvironment<'db>,
+            ty: Type<'db>,
+        ) -> bool {
+            match ty {
+                // `typing._GenericAlias`es are actually more lenient than `types.GenericAlias`es.
+                // We don't generally try to distinguish between the two, but we do happen to know
+                // that everything in these specific modules is implemented in C, so it'll be a
+                // `types.GenericAlias` when parametrized rather than a `typing._GenericAlias`.
+                Type::GenericAlias(alias) => alias.origin(db).known(db).is_some_and(|class| {
+                    matches!(
+                        class.canonical_module(env.python_version(db)),
+                        KnownModule::Builtins | KnownModule::Types

I agree with erring on the side of avoiding false positives for user-defined generics. One cost of this particular heuristic is that we now lose some existing diagnostics on main for fairly common stdlib types. For example, main catches all three of these, and they all raise on Python 3.13.

import re
from collections import deque
from collections.abc import Sequence

def f(
    x: deque[int] | "str",
    y: Sequence[int] | "str",
    z: re.Pattern[bytes] | "str",
): ...

So the approach in this PR adds some true positives, but also adds some false positives and loses some true positives.

Reviewers
Assignees
AlexWaygood AlexWaygood
Labels
risk: low confidence: 81.3% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 53.8% (MEDIUM) · Higher = larger blast radius
53.8%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 81.3% · Lower = rushed or shallow review
81.3%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 10.1% · Safe to merge
10.1%
Repository