Commit Graph
93 Commits
Author SHA1 Message Date
Charlie Marsh 247e0f618c [ty] Reuse generic call solutions with expected return types and bounds (#30909)
## Summary

ty [reuses inferred type
arguments](https://github.com/astral-sh/ruff/pull/30815) across calls
with the same argument types. It skips the cache when the caller expects
a particular return type, since that can change the answer. It also
skips bounded type variables to avoid solving rejected overloads twice.

We now key the cache on the expected type and how it guides inference,
and reuse solutions for bounded type variables too. In
[Pydantic](https://github.com/pydantic/pydantic/blob/560f0f96a37d6913afdfddb2de22030ef08e68c3/pydantic/experimental/pipeline.py#L486),
several branches assign `s.copy()` back to a `CoreSchema`. We can infer
the return type once for each of the 59 possible types of `s`, while
still checking arguments and reporting errors at each call site.

| Platform | Workers | [Base
instructions](https://github.com/astral-sh/ruff/commit/0cc5087b01b99157a18429c5115a98ba393fcbcf)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/8fc2de0ff07fbc0a546e52838fff0ba82e67d7d3)
| Change | Paired range |
| --- | --- | ---: | ---: | ---: | ---: |
| Linux (x86-64) | Default | 38,012,906,501 | 36,818,217,807.5 | -3.11%
| -3.22% to -3.05% |
| Linux (x86-64) | One | 37,919,447,354 | 36,714,177,437 | -3.18% |
-3.18% to -3.18% |
| macOS (ARM64) | Default | 46,732,258,132 | 45,305,441,196 | -3.46% |
-3.72% to -2.80% |
| macOS (ARM64) | One | 45,137,917,098 | 43,589,956,935 | -3.47% |
-3.68% to -3.07% |

<details>
<summary>Instruction counts by project</summary>

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/0cc5087b01b99157a18429c5115a98ba393fcbcf)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/8fc2de0ff07fbc0a546e52838fff0ba82e67d7d3)
| Change | Paired range | Peak RSS change |
| --- | ---: | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| 3,339,984,697 | 3,295,731,576.5 | -1.32% | -1.33% to -1.26% | -0.10% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| 8,024,761,617 | 7,863,043,758 | -2.01% | -2.10% to -1.91% | +0.40% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 175,347,669,898.5 | 172,621,949,396 | -1.61% | -1.78% to -1.33% |
+0.32% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| 1,785,818,931 | 1,759,137,529 | -1.53% | -1.67% to -1.46% | +0.01% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| 1,986,576,533.5 | 1,958,664,078 | -1.38% | -1.42% to -1.30% | -0.07% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 28,435,311,732.5 | 27,820,742,462 | -2.18% | -2.38% to -1.91% | +1.07%
|
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
| 3,226,177,326.5 | 3,216,437,115.5 | -0.31% | -1.18% to -0.02% | +0.40%
|
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
| 5,614,953,208.5 | 5,572,525,040.5 | -0.76% | -0.83% to -0.69% | +0.29%
|
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 97,849,686,826 | 95,577,225,341 | -2.40% | -2.68% to -2.30% | +0.40% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
| 1,781,448,156.5 | 1,750,390,415 | -1.71% | -1.79% to -1.26% | +0.00% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 9,196,192,190.5 | 9,174,892,667 | -0.23% | -0.33% to -0.21% | +0.49% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 3,269,196,964.5 | 3,254,199,025 | -0.38% | -0.77% to -0.31% | -0.02% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| 20,663,315,100 | 20,200,133,451.5 | -2.23% | -2.39% to -2.16% | +0.54%
|
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
| 2,880,195,548.5 | 2,841,066,026 | -1.34% | -2.39% to -0.65% | +0.25% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 15,112,163,787 | 15,037,107,637 | -0.45% | -3.97% to +0.57% | +0.29% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| 45,099,532,310.5 | 43,620,889,561 | -3.43% | -3.64% to -3.07% | -0.21%
|
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| 16,984,636,041.5 | 16,620,622,667.5 | -2.11% | -2.34% to -1.98% |
+1.20% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 9,368,713,672 | 8,797,702,205 | -6.02% | -6.41% to -5.99% | +0.52% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
| 4,190,028,893 | 4,119,314,906.5 | -1.69% | -1.78% to -1.43% | +0.08% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| 14,999,362,992.5 | 14,702,488,320.5 | -1.76% | -2.50% to -1.46% |
+0.11% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
| 3,465,389,284 | 3,472,496,220.5 | -0.11% | -3.77% to +1.83% | -0.08% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| 5,127,744,625.5 | 5,043,931,163.5 | -1.63% | -1.90% to -1.18% | +0.23%
|
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| 34,770,603,802 | 33,970,353,416.5 | -2.39% | -2.48% to -2.15% | +0.77%
|
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| 16,327,349,515 | 15,733,765,711.5 | -3.44% | -3.86% to -3.41% | +0.72%
|
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| 10,434,492,896.5 | 7,471,098,959 | -28.44% | -28.59% to -28.30% |
+1.06% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| 55,682,598,909.5 | 52,605,795,798 | -5.46% | -5.67% to -5.37% | +2.13%
|
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| 9,610,778,990 | 9,492,443,887.5 | -1.24% | -1.26% to -1.20% | +0.67% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 102,409,356,294 | 100,208,355,859.5 | -2.04% | -2.33% to -1.98% |
+1.08% |

</details>

<!-- ty-pinned-project-instructions:start -->

Across 28 projects, the mean change in instructions was −2.50% and the
median was −1.46%.

We compared cold checks against [main at
d83eb73b](https://github.com/astral-sh/ruff/commit/d83eb73b279c28ff94a6b8fbc30690f816221ba5).
These tables measure [the PR revision before the
rebase](https://github.com/astral-sh/ruff/commit/d603145ef0574465914e9f061c7180bb2d1c5391)
applied to that commit. They predate #30480. Any figures above are from
earlier runs.

Output varied across runs on Django.

The [eight-alternative overload
benchmark](https://github.com/astral-sh/ruff/blob/b7ada1f7d7972c18563be77af8e4942e488589e6/crates/ruff_benchmark/benches/ty_constraint_set.rs#L441)
flagged by CodSpeed also used more instructions. The increase was 17.66%
on the original base and 17.62% on the base used for the project tables.

We repeated this benchmark after #30480. Median instructions rose from
147,927,648 on
[main](https://github.com/astral-sh/ruff/commit/96c09ab6e37ce7608ae420cb8de243c1ee9b7d98)
to 173,874,462.5 on [this
revision](https://github.com/astral-sh/ruff/commit/b7ada1f7d7972c18563be77af8e4942e488589e6)
(+17.54%) in four paired Cachegrind runs. Both builds reported zero
diagnostics. In a separate Callgrind profile, the [second pass over the
arguments](https://github.com/astral-sh/ruff/blob/b7ada1f7d7972c18563be77af8e4942e488589e6/crates/ty_python_semantic/src/types/call/bind.rs#L7385)
used 25.92 million instructions. The total rose by 25.90 million.

In the single-worker Django checks in these tables, the PR changed
`Divergent` to `Unknown` in two assignment errors and a note in
`django/db/models/sql/query.py`. Both builds produced both variants with
default parallelism. After the rebase we repeated the diagnostic checks
against #30480. The 907-file run and a separate 29-file reproducer
matched on both builds, including with the file order reversed.

<details>
<summary>Instruction counts by project on Linux</summary>

Both builds use the linked main commit, with this PR applied to the
second. Counts are medians of four single-worker Cachegrind runs on
Linux (x86-64). Change is the median of four paired percentages. We
marked a result inconclusive when the pairs disagreed in direction or
the change was within the variation between runs of either build.

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/d83eb73b279c28ff94a6b8fbc30690f816221ba5)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/d603145ef0574465914e9f061c7180bb2d1c5391)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| 2,757,244,751 | 2,723,159,538 | -1.24% | -1.25% to -1.23% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| 6,716,778,631 | 6,597,157,138 | -1.78% | -1.79% to -1.77% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 137,625,332,518.5 | 135,618,822,551.5 | -1.46% | -1.46% to -1.46% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| 1,511,901,166 | 1,490,137,332 | -1.44% | -1.46% to -1.43% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| 1,634,155,350.5 | 1,613,949,015.5 | -1.24% | -1.26% to -1.23% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 23,942,348,667.5 | 23,461,116,838.5 | -2.01% | -2.01% to -2.01% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,652,446,682 | 2,652,533,646.5 | 0.00% | -0.03% to
+0.05% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
| 4,462,930,368 | 4,435,700,718 | -0.61% | -0.62% to -0.60% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 81,832,013,096 | 80,091,523,956.5 | -2.13% | -2.13% to -2.13% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
| 1,420,924,076.5 | 1,401,965,263 | -1.34% | -1.34% to -1.33% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 8,021,462,168.5 | 8,010,827,193.5 | -0.13% | -0.14% to -0.09% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 2,635,429,107.5 | 2,623,242,150 | -0.46% | -0.48% to -0.45% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| 17,436,369,264.5 | 17,104,711,481 | -1.90% | -1.91% to -1.90% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
| 2,380,509,531 | 2,348,256,478.5 | -1.36% | -1.38% to -1.34% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 11,779,031,574.5 | 11,659,480,633.5 | -1.01% | -1.02% to -1.01% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| 37,749,282,500 | 36,578,881,897 | -3.10% | -3.11% to -3.10% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| 13,797,577,156.5 | 13,501,124,113 | -2.15% | -2.15% to -2.15% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 7,668,458,592 | 7,241,937,602 | -5.57% | -5.57% to -5.55% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
| 3,547,804,159.5 | 3,495,735,886.5 | -1.47% | -1.47% to -1.46% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| 12,325,858,647.5 | 12,140,307,805.5 | -1.51% | -1.51% to -1.50% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
| 2,612,822,795.5 | 2,599,997,107 | -0.49% | -0.49% to -0.49% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| 4,174,976,363.5 | 4,127,292,877.5 | -1.14% | -1.15% to -1.14% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| 29,059,090,407 | 28,429,859,380 | -2.16% | -2.18% to -2.15% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| 13,344,587,573.5 | 12,922,794,185.5 | -3.16% | -3.17% to -3.15% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| 8,636,893,834 | 6,656,026,577.5 | -22.94% | -22.94% to -22.93% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| 46,537,676,726.5 | 44,153,994,664.5 | -5.12% | -5.12% to -5.12% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| 7,825,056,603 | 7,738,437,010 | -1.11% | -1.11% to -1.10% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 85,117,709,720.5 | 83,503,048,436.5 | -1.90% | -1.91% to -1.89% |

</details>

<details>
<summary>Memory by project on Linux</summary>

Peak RSS is the median paired change in MiB. We ran 16 pairs with
default parallelism and four with one worker. The last column estimates
retained query storage from two separate single-worker pairs. It
excludes some allocations.

| Project | Peak RSS (MiB) | Pairs with higher RSS | Peak RSS, one
worker (MiB) | Estimated query storage (MiB) |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| +0.80 (+0.73%) | 11/16 | +0.27 | −0.18 (−0.27%) |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
| +0.84 (+0.44%) | 13/16 | +1.16 | +0.39 (+0.29%) |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| +10.67 (+0.32%) | 16/16 | +13.49 | +2.46 (+0.08%) |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| +0.34 (+0.47%) | 9/16 | +0.37 | −0.32 (−0.90%) |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| +0.71 (+0.88%) | 13/16 | +0.32 | +0.08 (+0.22%) |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| +7.12 (+1.35%) | 14/16 | +5.14 | +3.80 (+0.85%) |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
| −0.40 (−0.29%) | 7/16 | +0.15 | 0.00 (+0.01%) |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
| +0.58 (+0.29%) | 13/16 | +0.47 | +0.39 (+0.27%) |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| +6.61 (+0.45%) | 12/16 | +5.48 | −1.99 (−0.15%) |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
| +0.16 (+0.18%) | 9/16 | +0.24 | +0.02 (+0.05%) |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| −0.25 (−0.11%) | 8/16 | +0.55 | +0.11 (+0.07%) |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| +0.77 (+0.63%) | 9/16 | +0.38 | +0.11 (+0.15%) |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
| +3.68 (+1.02%) | 14/16 | +3.70 | +2.47 (+0.84%) |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
| −0.51 (−0.49%) | 6/16 | +0.13 | +0.07 (+0.12%) |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| +0.40 (+0.14%) | 12/16 | +0.91 | +0.14 (+0.06%) |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| +3.49 (+0.54%) | 14/16 | +4.01 | −0.43 (−0.08%) |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| +1.07 (+0.35%) | 13/16 | +1.69 | +0.99 (+0.42%) |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| +1.62 (+0.74%) | 14/16 | +1.60 | +0.70 (+0.44%) |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
| +0.65 (+0.56%) | 13/16 | +0.26 | −0.13 (−0.18%) |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| +0.06 (+0.02%) | 8/16 | +1.15 | +0.08 (+0.04%) |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
| −0.29 (−0.27%) | 4/16 | +0.12 | +0.04 (+0.06%) |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| +0.73 (+0.52%) | 14/16 | +0.38 | +0.14 (+0.15%) |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| +4.54 (+0.79%) | 16/16 | +4.73 | +2.93 (+0.61%) |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| +0.90 (+0.33%) | 14/16 | +1.46 | +0.23 (+0.11%) |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
| +1.72 (+1.36%) | 14/16 | +1.73 | +0.19 (+0.25%) |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| +10.48 (+1.77%) | 16/16 | +11.25 | +7.31 (+1.36%) |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| −0.13 (−0.06%) | 8/16 | +0.39 | +0.30 (+0.19%) |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| +5.96 (+0.40%) | 14/16 | +4.87 | +0.80 (+0.06%) |

</details>

<!-- ty-pinned-project-instructions:end -->
2026-11-25 08:16:17 -05:00
Ibraheem Ahmed 96c09ab6e3 [ty] Less aggressive generic call narrowing (#30480)
When inferring a generic call with gradual arguments, we should avoid
inferring overly narrow results that only succeed under gradual
assignability.

```py
from typing import Any

def first_or_none[T](items: list[T]) -> T | None:
    raise NotImplementedError

def _(value: Any):
    x1: int | None = reveal_type(first_or_none([value]))  # before: None, after: int | None
```

When expanding the call above into individual inference attempts against
`int` and `None`, we now use the wider type `int | None` inferred during
the first inference attempt as evidence that the chosen expansion
targets are too narrow, and so fall back to inferring against the wider
union. Previously, we discarded the `int` attempt due to failing to
narrow to a subtype of `int`, and preserved only the successful `None`
attempt, despite only succeeding under gradual assignability.

Note that this fix is currently limited to generic calls in annotated
assignment expressions, due to false positives exposed in the ecosystem
that will eventually be fixed by
https://github.com/astral-sh/ruff/pull/30593, as well as performance
concerns.

Partially addresses https://github.com/astral-sh/ty/issues/4841 (we can
close that issue once we remove the annotated assignment gate).
2026-11-24 22:19:56 -05:00
Carl Meyer ce19ae70ee [ty] Preserve peer context for collection literals in boolean and conditional expressions (#30911)
Since #30478, ty rejects a safe append when a fresh list is used as a
fallback.

```py
def f(values: list[int] | None):
    result = values or [None]
    result.append(1)
```

Before this change, ty infers `list[None]` for the fallback and rejects
`append(1)`. With this change, the fallback can hold `int | None`, so
the append succeeds. We still reject `append(None)` because `result`
could be the original `list[int]`.

The same reasoning applies to conditional expressions. Another branch
can suggest element types without requiring the fresh collection to be
assignable to that branch. We distinguish this context from an
assignment target and skip the retry that discards contextual bounds.
Incompatible assignments retain the diagnostics from #30478.

## Ecosystem report

On
[`343133ff`](https://github.com/astral-sh/ruff/commit/343133ff2739a4a6f1bef660c77fbde1d8687752),
eight existing Pandera errors show `DataFrame | str` in place of `str |
DataFrame`. Only the display order changed. No diagnostics were added or
removed, and the [full
analysis](https://github.com/astral-sh/ruff/pull/30911#issuecomment-7144425467)
found no regression.
2026-11-24 18:00:45 -08:00
Ibraheem Ahmed bbe650f3df [ty] Ignore declared type for failed collection literal assignments (#30478)
When inferring a collection literal that is incompatible with its
declared type, we should ignore the declared bounds to avoid confusing
diagnostics.

```diff
- error [invalid-assignment]: Object of type `list[int | str]` is not assignable to `list[int]`
+ error [invalid-assignment]: Object of type `list[str]` is not assignable to `list[int]`
x: list[int] = reveal_type(["a"])  # revealed: list[int | str]
```

Resolves https://github.com/astral-sh/ty/issues/3777.
2026-11-24 11:43:50 -05:00
Charlie Marsh 9d4cd222d5 [ty] Reuse the inferred value in augmented assignments to unions (#30746)
## Summary

For `flags |= 2 if enabled else 0`, ty infers the right-hand side once
to report diagnostics, then infers it again for each possible value of
`flags`.

Reuse the first result whenever a union member requests the same type
context. An in-place method that supplies a different parameter type
still gets its own inference.

Cold checks of all 3,032 Python files in [Hydrogram
0.2.0](https://pypi.org/project/hydrogram/0.2.0/) used 11.81–11.86%
fewer Cachegrind instructions in opposite orders, with identical
diagnostics. Median peak RSS went from 354 to 356 MiB. On [Pyrogram
2.0.106](https://pypi.org/project/Pyrogram/2.0.106/) and [Kurigram
2.2.18](https://pypi.org/project/kurigram/2.2.18/), instructions fell by
10.77–10.90% and 12.10–12.13%, respectively. These measurements are
independent of #30733.

<!-- ty-pinned-project-instructions:start -->
| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/943f623f55c9aa625b0b1b21af731e451819accc)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/ad41a43210dc493d619acc309c29f09a1f700b4f)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
| 3,111,432,861.5 | 3,106,987,232 | -0.14% | -0.15% to -0.13% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
(inconclusive) | 7,982,824,012.5 | 7,985,919,661 | +0.04% | -0.07% to
+0.15% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 153,606,801,126.5 | 153,619,604,507.5 | +0.01% | 0.00% to +0.01% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
| 1,821,991,264 | 1,806,332,041 | -0.86% | -0.87% to -0.85% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
| 1,901,199,499 | 1,899,945,890 | -0.07% | -0.08% to -0.05% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 27,660,437,899.5 | 27,639,038,185.5 | -0.08% | -0.09% to -0.06% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,874,786,574 | 2,879,327,689 | +0.16% | -0.08% to
+0.40% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
(inconclusive) | 4,867,665,759 | 4,867,447,750.5 | 0.00% | -0.03% to
+0.03% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
(inconclusive) | 93,366,576,567 | 93,280,280,726.5 | -0.09% | -0.18% to
0.00% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
(inconclusive) | 1,651,607,300 | 1,651,951,001 | +0.02% | -0.04% to
+0.09% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 8,215,666,556 | 8,246,219,279 | +0.37% | +0.19% to +0.55% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
(inconclusive) | 2,945,270,182 | 2,948,073,718.5 | +0.10% | +0.04% to
+0.15% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
(inconclusive) | 20,743,347,188 | 20,706,966,684 | -0.18% | -0.22% to
-0.13% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
(inconclusive) | 2,675,169,452 | 2,672,138,432 | -0.11% | -0.26% to
+0.03% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
(inconclusive) | 13,387,668,563.5 | 13,382,950,844 | -0.04% | -0.12% to
+0.05% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
| 44,781,928,388 | 44,515,769,040.5 | -0.59% | -0.60% to -0.59% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
| 15,429,908,754 | 15,446,170,680.5 | +0.11% | +0.10% to +0.11% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 8,584,280,557 | 8,603,718,525 | +0.23% | +0.21% to +0.25% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
(inconclusive) | 4,065,516,071.5 | 4,059,651,532.5 | -0.14% | -0.24% to
-0.05% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
(inconclusive) | 14,018,836,842.5 | 14,003,879,311.5 | -0.11% | -0.13%
to -0.08% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
(inconclusive) | 2,934,906,286.5 | 2,934,155,492 | -0.03% | -0.04% to
-0.01% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
(inconclusive) | 4,647,856,232.5 | 4,650,882,946.5 | +0.07% | +0.04% to
+0.09% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
(inconclusive) | 32,508,616,530.5 | 32,478,415,568 | -0.09% | -0.11% to
-0.08% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| 15,209,837,729.5 | 15,173,774,828.5 | -0.24% | -0.27% to -0.20% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
(inconclusive) | 12,880,720,290.5 | 12,890,463,033 | +0.08% | +0.04% to
+0.11% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| 58,213,246,251.5 | 58,037,790,726 | -0.30% | -0.30% to -0.30% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
(inconclusive) | 8,732,083,412 | 8,736,233,365.5 | +0.05% | +0.04% to
+0.05% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 96,550,522,801 | 96,431,491,920 | -0.12% | -0.16% to -0.09% |
<!-- ty-pinned-project-instructions:end -->
2026-11-21 22:25:59 -05:00
Ibraheem Ahmed 4f89436b29 [ty] Avoid preferring inferred attribute types during call inference (#30151)
An inferred attribute type should not provide a declared type preference
to later assignments, allowing it to be overwritten by a gradual type
without being restricted to the original concrete type:

```py
from typing import Any

def identity[T](value: T) -> T:
    return value

class Fields:
    class_value = None

    def __init__(self, value: Any):
        self.value = None
        self.value = identity(value)
        reveal_type(self.value)  # main: None, now: Any
```

Resolves https://github.com/astral-sh/ty/issues/4974. Part of
https://github.com/astral-sh/ty/issues/4988.
2026-11-13 17:38:14 -05:00
Ibraheem Ahmed 11272cf447 [ty] Preserve type context kind when propagating to nested expressions (#30280)
The `TypeContextKind` of a given `TypeContext` should be preserved when
propagated to a nested expression. For example, an upper bound `T:
Payload` does not provide a solver preference for gradual types, and so
should not provide a preference to any fields of the `TypedDict`:

```py
from typing import TypedDict, Any

class Payload(TypedDict):
    value: int

def payload[T: Payload](value: T) -> T:
    return value

def identity[T](value: T) -> T:
    return value

def _(value: Any):
    payload(reveal_type(identity(value)))  # revealed: Any
    payload({"value": reveal_type(identity(value))})  # main: int, now: Any
```

There are a few places where we are incorrectly constructing a
`TypeContext` with the default `TypeContextKind` instead of preserving
it from the outer `TypeContext`, which this PR fixes.
2026-11-13 17:03:33 -05:00
David Peter df9ba2cd09 [ty] Test contextual inference for constructors with explicitly annotated receivers (#30363)
## Summary

Add bidirectional inference tests for generic constructors with an
explicitly annotated `self`.

These are test cases for https://github.com/astral-sh/ty/issues/4993 and
https://github.com/astral-sh/ty/issues/4977
2026-11-13 08:38:18 +00:00
Carl Meyer d5d5ca18a6 [ty] Infer value types for bare Final and ClassVar (#30293)
A bare `Final` or `ClassVar` leaves the value type to inference.
Previously, ty passed `Unknown` as the expected type of the initializer.
This could change the result of a generic call and let assignments to a
mutable class variable accept values incompatible with its initializer.

Track whether a qualifier has a type argument. For example, `header:
ClassVar = bytes.fromhex("fd")` exposes `bytes` on the class and accepts
subsequent `bytes` assignments through the class. An explicit
`ClassVar[Unknown]` still exposes `Unknown`.

A bare `Final` instance attribute gets its type from the declaring
class's initializer. A subclass cannot initialize that same final
attribute. For a bare final dataclass field with an ordinary default,
the generated constructor accepts the inferred field type.

A generic call can infer its type arguments from its inputs when it
appears in `yield` or `yield from` in a generator without a return
annotation. The same applies when the call is passed to a callable with
an unknown signature. An explicit parameter or yielded element type of
`Any` still supplies type context.

Split from #30244, which changes generic type-argument inference. The
ordinary dataclass default case overlaps #29576, which also handles
field specifiers and missing defaults. #30255 covers public reads of
module-level finals with an explicit type argument.

Fixes astral-sh/ty#4989.

## Ecosystem report

At
[`28a3e59`](https://github.com/astral-sh/ruff/commit/28a3e5901958260777e605b2ce27477f995dbbab),
ty detects 43 incompatible class-variable overrides across six projects,
removes two false return warnings in pytest, and updates the messages
for three existing errors. All 48 stable changes are expected. [Full
report and
examples](https://github.com/astral-sh/ruff/pull/30293#issuecomment-6782994357)
2026-11-12 14:49:39 -08:00
Carl Meyer a23abce010 [ty] Respect return constraints when promoting literal arguments (#30153)
ty rejected this assignment even though `max` returns one of the two
input tuples and both contain only `"red"` and `"blue"`.

```python
from typing import Literal

short = ("red",)
long = ("red", "blue")
longest: tuple[Literal["red", "blue"], ...] = max([short, long], key=len)
```

ty widened the tuple elements to `str` while inferring the list passed
to `max`, so it reported `invalid-assignment` for a result of type
`tuple[str] | tuple[str, str]`. The annotation on `longest` already
supplies an upper bound that rules out that widening. This change checks
proposed promotions against that bound and preserves the literals in
this example.

When a union in the expected return type gives the solver several
constraint paths, ty widens type arguments together only if one path
permits all those promotions. If the paths disagree on which arguments
can widen, ty tries the promotions they share and checks that a complete
path still permits them. This preserves literals where needed and keeps
the result independent of type-variable declaration order.

Fixes astral-sh/ty#4968.

## Test plan

Bisected the original Python 3.12 example to #26680 and checked that
this change accepts it.
2026-11-12 14:07:50 -08:00
Alex WaygoodandMicha Reiser 22e77392fb [ty] Split invalid-return-type into 3 focussed rules; rename empty-body and unsound-return (#29947)
Co-authored-by: Micha Reiser <micha@reiser.io>
2026-11-11 16:59:57 +00:00
Alex WaygoodandBrent Westbrook ce0077c3e5 [ty] Distinguish attributes missing from some union members (#29944)
## Summary

Users can now suppress an attribute error that affects only some union
members and still catch names that are missing from every member. For
example, both lines below previously reported `unresolved-attribute`:

```python
def clean(value: str | int) -> str:
    value.stirp()          # missing-attribute: neither str nor int has stirp
    return value.strip()   # missing-union-attribute: str has strip, int does not
```

The motivation is that a project adopting ty may want `value.strip()` on
`str | None` to only warn while a typo remains an error-severity
diagnostic.

Both rules default to errors. The same distinction applies to optional
values such as `str | None` and to attribute deletion. Attributes
defined only conditionally on a class continue to use
`possibly-missing-attribute`.

### Comparison to other type checkers

Pyright distinguishes between `reportOptionalMemberAccess` (which is
specifically for unions with `None`) and `reportAttributeAccessIssue`,
which is for all other unions. mypy, meanwhile, distinguishes between
`union-attr` (which is an error code for all attribute-access errors on
union types) and `attr-defined` (which is an error code for all
attribute-access errors on non-union types). So this new split doesn't
_exactly_ align with either precedent -- but I _do_ think it's probably
the most useful split we can do, and it's the one that makes the most
sense _a priori_ in my opinion.

### Compatibility

`unresolved-attribute` remains an alias for `missing-attribute` in
configuration and inline ignores. To preserve a setting such as
`unresolved-attribute = "warn"` for both cases, also set
`missing-union-attribute = "warn"`. On an access that fails for only
some union members, replace `# ty: ignore[unresolved-attribute]` with `#
ty: ignore[missing-union-attribute]`. Tools that consume diagnostic
codes should recognize both new names.

Fixes astral-sh/ty#2839 and fixes astral-sh/ty#2471.

## Test Plan

A comparison with ty 0.0.96 on typeshed-stats, docstring-adder,
sphinx-lint, and typing_extensions found the same messages, locations,
and severities. Eight diagnostics received `missing-union-attribute`
across those four projects (two in sphinx-lint and six in
typing_extensions).

---------

Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-06 14:46:50 -05:00
Alex WaygoodandDavid Peter d65c056994 [ty] Split invalid-key into three TypedDict diagnostic rules (#29955)
## Summary

Given a `Movie` TypedDict with a `title` field, ty currently reports
`invalid-key` for three cases. This PR gives each its own rule.

| Example | Rule |
| --- | --- |
| `movie["titel"]` reads a misspelled key | `invalid-typed-dict-key` |
| `movie[key]` reads a key whose type is `str` and whose value is
unknown | `non-literal-typed-dict-key` |
| `Movie(title="Alien", titel="Alien")` supplies an unknown key during
construction | `unknown-typed-dict-constructor-key` |

Both subscript rules apply to reads and assignments. An invalid
non-string key such as `movie[0]` reports `invalid-typed-dict-key`. The
constructor rule reports the extra `titel` key in `movie: Movie =
{"title": "Alien", "titel": "Alien"}`. For a closed TypedDict, it flags
`{key: value}` when `key` has type `str` and might introduce an extra
item.

Projects migrating to ty lose typo detection if they disable
`invalid-key` to allow dynamic TypedDict lookups. In mypy, disabling
`literal-required` allows `movie[key]` while `movie["titel"]` still
produces a `typeddict-item` error. Pyright allows the dynamic lookup by
default and also flags the typo. To keep that behavior in ty, set
`non-literal-typed-dict-key` to `ignore` and leave
`invalid-typed-dict-key` enabled.

All three rules default to `error`. With the alias handling from #29960,
`invalid-key` maps to `invalid-typed-dict-key` in configuration, inline
ignores, and existing baselines. Previously baselined diagnostics can
therefore reappear under either of the other two rule names. To preserve
a custom severity across the split, set all three rules to the same
level. For inline ignores, use the rule or rules reported on that line.

---------

Co-authored-by: David Peter <mail@david-peter.de>
2026-11-06 15:34:17 +00:00
Ibraheem Ahmed 45d1a3a4eb [ty] Solve generic call type context through constraint sets (#26680)
When inferring a generic call, there are two types of constraints: the
constraints inferred from the arguments to the call, and the constraints
inferred from the declared type of the call expression. We currently
infer these two sets of constraints separately, and manually inject
"preferred" types from the declared type into the solution through a
legacy type-mapping. After this PR, we now combine both declared and
inferred constraints into a single constraint set, allowing us to take
full advantage of the constraint solver for more complex generic calls.
Note that we still retain the legacy path for calls involving
`ParamSpec` or `TypeVarTuple`, but eventually we will be able to migrate
generic calls entirely to the new solver.

The most prominent pattern fixed by this change is that we now solve a
generic call directly to the declared type when no inferred evidence is
present, even if the declared type is covariant over its type parameter:

```py
def example() -> frozenset[int]:
    return reveal_type(frozenset())   # frozenset[int]
```

We previously inferred `frozenset[Unknown]` for such a call, leading to
a number of `unsound-return-statement` being removed throughout the
ecosystem.

Much of the complexity of this PR is due to solver heuristics around
declared type preference. Constraints originating from the declared type
are tagged with `ConstraintProvenance::Declared`, a third variant of
constraint provenance, which this PR also changes to be represented as a
bit-set. We now also apply the mutual-assignability heuristic when
choosing the solution to a given type variable in a generic call: if the
inferred and declared solutions are mutually-assignable, we prefer the
declared solution, otherwise, we prefer the inferred solution.

```py
from typing import Any

def identity[T](value: T) -> T:
    return value

def _(dynamic: Any, number: int):
    reveal_type(identity(number))  # revealed: int
    reveal_type(identity(dynamic))  # revealed: Any

    x1: Any = reveal_type(identity(number))  # revealed: Any
    reveal_type(x1)  # revealed: Any

    x2: int = reveal_type(identity(dynamic))  # revealed: int
    reveal_type(x2)  # revealed: int
```

Note that this heuristic applies independently to each type variable in
the generic call, meaning that the declared type may be preferred for
one type variable, why the inferred type is preferred for another:

```py
def pair[T, U](first: T, second: U) -> tuple[list[T], list[U]]:
    return [first], [second]

def _(first: int, second: str):
    # revealed: tuple[list[Any], list[str]]
    result: tuple[Sequence[Any], Sequence[object]] = reveal_type(pair(first, second))
```

The primary limitation of this PR is that we do not extend the same
approach to collection-literal inference, which still build a set of
legacy type-mappings. However, collection literals form a much simpler
constraint solver problem than generic calls in general, and so that
should be a straightforward follow up after this PR lands.

Resolves https://github.com/astral-sh/ty/issues/3559.
Resolves https://github.com/astral-sh/ty/issues/3236.
Resolves https://github.com/astral-sh/ty/issues/2615.
Resolves https://github.com/astral-sh/ty/issues/4016.
Resolves https://github.com/astral-sh/ty/issues/4294.
Resolves https://github.com/astral-sh/ty/issues/4311.
Resolves https://github.com/astral-sh/ty/issues/4736.
2026-11-06 02:27:34 -05:00
Ibraheem Ahmed 40a0e02c60 [ty] Fix call argument validation for variadic parameters (#30086)
Fixes a small bug in argument validation involving variadic parameter
types where we sometimes use the type inferred without type context
rather than the type inferred against the parameter:
```py
@overload
def pair[T: int, U](*args: *tuple[list[T], list[U]]) -> tuple[T, U]: ...
@overload
def pair(first: list[str], second: list[int], /) -> tuple[str, int]: ...
def pair(*args: object) -> object:
    raise NotImplementedError

reveal_type(pair([42], ["x"]))  # main: tuple[Unknown, Unknown], now: tuple[int, str]
```
2026-11-05 22:10:17 -05:00
Ibraheem Ahmed 4b0b407bfc [ty] Preserve unions inferred during fixpoint iteration (#29927)
During fixpoint iteration, we sometimes use the type inferred for a
given argument as type context for the same argument in a subsequent
round. If the inferred type is a union, this can sometimes trigger
generic call narrowing, which may lead to a different type than was
inferred earlier due to our narrowing heuristics. We should instead
respect the types inferred from the arguments directly and be less
aggressive about narrowing in this case.

```py
def choose[T](x: T, y: T) -> T:
    return x

def make_list[U = str]() -> list[U] | list[int]:
    raise NotImplementedError

def _(ints: list[int]):
    x = choose(make_list(), ints)
    reveal_type(x)  # revealed: list[str] | list[int]
    
    y = choose(make_list(), ints)
    reveal_type(y)  # main: list[int], now: list[str] | list[int]
```

This also allows us to make use of sibling type context in more cases.
For example, the following snippet no longer errors after this PR:

```py
def pair_with_list[T](x: T, y: list[T]) -> T:
    return x
    
def copy_or_none[T](items: list[T]) -> list[T] | None:
    raise NotImplementedError

def _(
    rows: list[list[int] | list[str] | None],
) -> None:
    pair_with_list(reveal_type(copy_or_none([1])), rows)  # revealed: list[int] | None
```
2026-11-05 18:09:56 +00:00
Ibraheem Ahmed 32be8e7258 [ty] Skip fixpoint iteration for simple generic calls (#30054)
A generic call of the form `def f[T, U, ...](x: T, y: U, ...)` does not
require fixpoint iteration, as each argument can be inferred
independently without ever receiving type context from a sibling
argument. We should skip fixpoint iteration in this case.

Note that importantly, this means we no longer perform fixpoint
iteration on calls to `reveal_type`, which avoids exposing
inconsistencies in generic inference that can lead to a different type
being inferred with or without the `reveal_type`.
https://github.com/astral-sh/ruff/pull/29666 and
https://github.com/astral-sh/ruff/pull/29927 attempt to fix these
inconsistencies, but some remain, and this should mean we run into them
less often (as well as being a useful optimization in general).

Removing the fixpoint iteration introduced by `reveal_type` also catches
a couple small preexisting generic inference limitations in our mdtests,
which are also fixed by this PR.
2026-11-05 11:46:37 -05:00
Ibraheem Ahmed 3e4c0c40eb [ty] Retain all successful generic call narrowing attempts (#29666)
When inferring a generic call or collection literal against a union
declared type, we currently attempt to narrow the call to the first
member of the union to which the call/literal is assignable when
inferred using that member as type context.

```py
x: list[int] | list[int | str] = list((1,))
reveal_type(x)  # revealed: list[int]

y: list[int] | list[int | str] = [1]
reveal_type(y)  # revealed: list[int]
```

However, choosing the first member is somewhat arbitrary, as there may
be multiple valid specializations of the call for multiple members of
the union. Notably, this behavior is inconsistent with two other
heuristics:
1. When inferring a dictionary literal against a union of `TypedDict`
types, we infer the valid subset of the union as opposed to the first
matching element.
2. When inferring the specialization of a type variable `T <: A | ...`,
we choose the entire union as opposed to an arbitrary element.

This can lead to issues where wrapping an existing call or dictionary
literal in an identity function (such as `reveal_type`) can trigger
fixpoint iteration, and narrow what was previously a union to an
arbitrary element of that union. Note that this is not necessarily
incorrect (and perhaps even more permissive behavior), but it can be
somewhat unintuitive (see
https://github.com/astral-sh/ruff/pull/26680#discussion_r4229611697),
and I think it has become clear that we should be consistent here.

This PR changes all our generic call/collection literal narrowing logic
to infer the union of all valid narrowing attempts, as opposed to
choosing the first attempt arbitrarily.

```py
x: list[int] | list[int | str] = list((1,))
reveal_type(x)  # revealed: list[int] | list[int | str]

y: list[int] | list[int | str] = [1]
reveal_type(y)  # revealed: list[int] | list[int | str]
```

Resolves https://github.com/astral-sh/ty/issues/3053.
Resolves https://github.com/astral-sh/ty/issues/4829.
Partially addresses https://github.com/astral-sh/ty/issues/3935.
2026-11-04 14:00:17 -05:00
Carl Meyer 2c6359372b [ty] Infer return intersections from correlated call specializations (#28303)
## Summary

This PR builds on the intersection constraint collection in #28677. It
improves the precision of our inferred return types in cases when an
argument-side intersection (or overloaded callable) results in multiple
independent valid solutions.

When an argument to a generic function is an intersection (or an
overloaded callable), this often results in multiple valid solutions for
the call. For example, if you pass `Sequence[A] & Sequence[B]` to `def
first[T](value: Sequence[T]) -> T`, the constraint solver will correctly
report that both `T = A` and `T = B` are equally valid independent
solutions.

Currently we union these valid solutions together, resulting in the
overly-conservative inference `T = A | B`, even though the returned
object in this case must be both `A` and `B`. This means that narrowing
the argument (e.g. from just `Sequence[A]` to `Sequence[A] &
Sequence[B]`) can actually widen the return type (from just `A` to `A |
B`), leading to false positives.

Other type checkers just arbitrarily pick either `A` or `B` as the
return type in this scenario, which leads to fewer false positives than
our current `A | B`, but is unsatisfyingly arbitrary, and can still lead
to some false positives, because it can effectively ignore narrowing. We
can do better (at least in some cases).

It's tempting to say that we should just intersect the valid solutions
instead, giving `T = A & B` as our single solution. For the simple `->
T` case above, that gives the correct result `A & B`. But if we had
instead `def boxed_first[T](value: Sequence[T]) -> Box[T]` with
covariant `Box`, the correct return type is `Box[A] & Box[B]`, not
`Box[A & B]`. (It is true for some covariant types, but not all, that
`Box[A & B]` is equivalent to `Box[A] & Box[B]`.)

So we cannot solve `T` directly to `A & B`, but we can say that if `T =
A` and `T = B` are both valid solutions, then `Box[A]` and `Box[B]` are
both independently valid inferences for the overall return type of the
call, thus `Box[A] & Box[B]` is a valid inference for the call: the
returned object must be both a `Box[A]` and a `Box[B]`.

Fixes astral-sh/ty#4716.

Partially addresses
[astral-sh/ty#3557](https://github.com/astral-sh/ty/issues/3557); the
union migration and the documented precision limitations below remain
separate work.

## Caveats

Most of the code in this PR is identifying and carving out cases where
the above logic is not (yet) safe to apply.

### Solver limitations and deferrals

This can be because of limitations in the inference machinery (e.g.
return refinement does not yet support `ParamSpec` or `TypeVarTuple`).
It can also be just because we've deferred some complex cases to future
work (constructors, `functools.partial`).

We also fall back to conservative union-merged specialization in case
the constraint solver exceeded its budget, in which case it may have an
incomplete solution.

For intersection refinement to be valid, each solution must validate
every argument (result in a valid call if it specializes the function
parameter types). This would be a given if the constraint solver were
perfect at collecting all relevant constraints, but it isn't yet. In
particular, we can infer constraints from incompatible arguments (e.g.
`list[int] | None` vs `list[T]` infers `T = int`, `tuple[int, str]` vs
`tuple[U, int]` infers `U = int`) and in general we can have "solutions"
that correspond to calls which failed. Also some unsupported cases drop
constraints, e.g. `list[int] | set[str]` vs `list[T] | set[T]` infers no
constraints at all.

We therefore, for now, revalidate each specialization against the
original arguments (that is, for each candidate solution, specialize the
parameter and argument types accordingly, then re-check each
argument/parameter pair) before deciding to intersect them. This should
be removable in the future when the solver is more complete.

Currently we treat overloaded callables in constraint collection as if
they were intersections of callables, and collect constraints from all
overloads, but this is not quite right, since overloads are ordered; in
overlapping cases we should prefer the first match. Incompatible
overlapping return types can currently intersect to `Never`, including
for `operator.mul` with a `Fraction`.

### Inherent

There are also some caveats which are inherent, rather than due to any
temporary solver limitation.

#### Gradual types

If one argument establishes that `int` and `str` are possibilities for
`T`, and another argument assigns `Any` to `T`, it is not safe to
intersect `int` and `str` specializations of the return type: the
assignability of `Any` to `T` could rely on different materializations
for different specializations of `T`. In other words, the `Any` might
materialize to something which would have ruled out either `int` or
`str` as a solution. So this reliance on gradual assignability prevents
us from being confident that the returned value satisfies both
specialized return types.

For now, we catch this gradual case in the "argument revalidation"
described above, by using subtyping instead of assignability to
revalidate any argument-to-parameter assignment that involves an
inferrable typevar, so we will not consider a specialization that
requires gradual assignability as a candidate for intersecting. In the
future, if the constraint solver preserves the fact that gradual
evidence was required for a given solution, we can consume that directly
instead of needing revalidation.

Currently if no candidate specialization survives argument revalidation,
we fall back to the union-merged specialization, but this should also be
improved in future work: ideally gradual evidence would result in
gradual output (more like an `AnyOf` type), not a strict union.

#### Invariant difference

There are cases where e.g. both `list[A]` and `list[B]` could be valid
but mutually exclusive inferences for a generic call, for example if the
function returns an empty list:

```py
def fresh[T](type_source: Sequence[T]) -> list[T]:
    return []
```

If we call this function with an argument of type `Sequence[A] &
Sequence[B]`, then `T = A` and `T = B` are both valid solutions, but
they are mutually exclusive inferences. The runtime object `[]` (with
different static type tags) can inhabit either `list[A]` or `list[B]`,
and the return type of a call to `fresh()` could be validly considered
either a `list[A]` or a `list[B]`, but it cannot be considered both at
once (that intersection would simplify to `Never`, but the call can
return.)

Similar cases can occur with structural types: `TypedDict`, `Protocol`,
and callable types.

Currently, we handle this by avoiding intersecting return types whenever
valid alternatives differ in an invariant component of the return type.
In these cases we try falling back to the union-merged specialization
(`T = A | B`), but if that specialization would fail the call, we
instead union the specialized return types from the valid alternatives
(infer e.g. `list[A] | list[B]`.)

## Ecosystem report

The [full ecosystem
report](https://github.com/astral-sh/ruff/pull/28303#issuecomment-5701401704)
for head `48f5f1dbf604` confirms expected precision improvements in
Prefect, Spark, Rich, pip, and scipy-stubs. Sixteen diagnostics are
removed; one Spark return error becomes an `unsound-return-statement`
warning because a pre-existing loop-inference limitation still
contributes `Unknown`. No ecosystem regressions were identified.
2026-10-20 13:19:06 -07:00
David Peter e03746cbf4 [ty] Prepare mdtests for return type inference (#29295)
## Summary

This PR prepares our mdtests for return type inference. For example, we
had some definitions like
```py
def flag(): ...
```
which were supposed to be used in `if flag()` tests of ambiguous
truthiness. However, with return type inference, ty would understand
that this function returns `None`, which is falsy.

I'm pulling this out so as to reduce the diff on the upcoming return
type inference PR.

## Test Plan

Tested by running the return type inference implementation against these
changes.
2026-10-12 15:15:57 +02:00
Ibraheem Ahmed 9afd56f70a [ty] Solve validity type context through constraint sets (#28909)
We currently flatten all type context into a single `Type` instance,
which can lose important information about a given type context
constraint. Eventually, we would like `TypeContext` to store a
`ConstraintSet` directly (see
https://github.com/astral-sh/ty/issues/3933 for details), but this PR
takes a small step towards that by adding an addition bit of information
about the origin of a given type context constraint.

Type context originating from a concrete declared type is stored as
`TypeContextKind::Declared`, while type context originating from the
declared upper bound of an outer type variable is stored as
`TypeContext::Validity`, and solved as a validity constraint through the
constraint solver. This slightly changes our heuristics around using
these constraints during generic call inference. In particular, it means
that we don't necessarily prefer the declared type specialization if it
originated from a validity constraint, as opposed to a declared
constraint.

```py
def singleton[T](value: T) -> Sequence[T]:
    return [value]

def bounded[T: Sequence[int]](value: T) -> T:
    return value

def _(value: Any):
    x: Sequence[int] = reveal_type(singleton(value))  # revealed: Sequence[int]
    
    # TODO: This should be `Sequence[Any & int]`
    reveal_type(bounded(singleton(value))))  # revealed: Sequence[Any]
```

This PR also improves our generic call inference in various places due
to partially migrating to the new solver, e.g.,

```py
def bounded[T: list[int]](value: T) -> T:
    return value

def from_callback[T](f: Callable[[T], None]) -> list[T]:
    return []

def _(f: Callable[[object], None]):
    reveal_type(bounded(from_callback(f)))  # main: Unknown, now: list[int]
```

The full migration for all type context will be completed by
https://github.com/astral-sh/ruff/pull/26680.
2026-10-06 14:05:42 -04:00
Douglas Creager 6dc81766a7 [ty] Don't quantify away non-inferable typevars before solving, take 3 (#28884)
This is a cleanup PR that is part of the [scoped
quantifier](https://gist.github.com/dcreager/679132607be4c7cfb08ddc8ad1076982)
work.

When solving a constraint set, we only care about solutions for the
typevars that are _inferable_. Before, we would handle this by using
quantification to _remove_ the non-inferable typevars from the
constraint set, relying on our sequent map implementation to propagate
constraints on non-inferable typevars over to inferable typevars where
appropriate.

We now skip this step, and generate solution paths for the original
constraint set directly as part of our custom BDD path-walker.
2026-10-05 21:25:34 -04:00
David Peter f183d34dca [ty] Add opt-in truthiness-test-of-none-union rule (#28889)
## Summary

Add a new opt-in `truthiness-test-of-none-union ` rule which flags
truthiness checks on types like `int | None` or `str | None`. For
example, it will emit an error on the following (problematic) `if not
limit` check:

```py
def take(items: list[str], limit: int | None = None) -> list[str]:
    if not limit:  # error: [truthiness-test-of-none-union]
        return items
    return items[:limit]
```

Related to https://github.com/astral-sh/ruff/discussions/8757 and
inspired by Pyrefly's `implicit-bool` rule (but narrower in scope).

## Test strategy

New test suite
2026-09-25 22:06:20 +02:00
Ibraheem Ahmed 5e8172852d [ty] Avoid leaking Unknown from unconstrained collection use-sites (#28659)
During full-scope collection literal inference, we collect constraints
from generic method calls on a given collection literal binding. If a
method call does not introduce any constraints, we default specialize
the call to `Unknown`, which can incorrectly introduce an `Unknown` type
into an otherwise concrete collection literal. We should instead default
specialize to the `UnspecializedTypeVar` marker type, which is ignored
during inference.

```py
x = [1]
x.reverse()
reveal_type(x)  # main: list[int | Unknown], now: list[int]
```
2026-09-17 15:56:31 -04:00
Shunsuke ShibayamaandCarl Meyer 160ffbf2cf [ty] Introduce Recursive types and fully support recursive implicit type aliases (#28425)
## Summary

Closes https://github.com/astral-sh/ty/issues/1738
(While this PR also resolves the error in the code provided in
https://github.com/astral-sh/ty/issues/1846, I consider the broader
issue under discussion to still be unresolved)

To fully support implicit type aliases, this PR introduces `Recursive`
types. These represent *structural recursive types*. In other words,
they are anonymous recursive types implicitly constructed through type
inference, rather than a nominally defined recursive type like PEP 695
recursive type aliases.

This is what was being discussed in
https://github.com/astral-sh/ruff/pull/24252#issuecomment-4172655350. We
are not introducing recursive types solely for implicit type aliases;
this is the first step toward completely replacing the current
`Divergent`-based approximate recursive type inference with a full
implementation.

Initially, I planned to completely remove the `Divergent` type alongside
the introduction of `Recursive` types, but because the scope of the
impact was far too large, I decided to replace it incrementally. Both
will coexist until the replacement is complete, but eventually,
everything should be replaced by `Recursive` types.

Following this PR, I plan to use the newly introduced `Recursive` types
to replace various forms of recursive type inference.

## Design

Currently, we approximate and treat recursive type structures generated
by recursive type inference as gradual types containing `Divergent`. For
example, a subscript on `x: Divergent` results in `x[n]: Divergent`.
Consequently, we get:

```
x: list[Divergent]
x[n]: Divergent
x[n][n]: Divergent
```

As a result, the type after subscripting loses the information that `x`
was a recursive list type. We solve this problem by introducing
recursive types.

`RecursiveType` is a binder for a body type that contains a recursive
variable. In other words, it roughly has the following structure:

```rust
struct RecursiveType<'db> {
    id: salsa::Id,
	body: Type<'db>,
	arguments: Option<Specialization<'db>>,
}

struct RecursiveVar<'db> {
    id: salsa::Id,
    arguments: Option<Specialization<'db>>,
}

enum Type<'db> {
    Recursive(RecursiveType<'db>),
    RecursiveVar(RecursiveVar<'db>),
    ...
}
```

For example, for the following implicit type alias:

```python
Tree = tuple[T, "Tree[list[T]] | None"]
# = μF. λT. tuple[T, F[list[T]] | None]
```

the constructed `RecursiveType` looks like this:

```rust
RecursiveType {
    id,
    body: tuple[T, RecursiveVar { id, arguments: [list[T]] } | None],
    arguments: [T]
}
```

Unlike `Divergent`, the recursive variable `RecursiveVar` has no type
properties on its own. Attempting to access this variable immediately
unfolds the recursive type, so questioning the typing properties of the
variable itself is meaningless. Therefore, if any type operation on
`RecursiveVar` appears, it should be a bug.

To infer the container subscript `x[1]` for `x: Tree[int]`, first unfold
`x`'s type. Unfolding replaces references to the recursive binder with
the recursive type itself. Writing `B[a := R]` for capture-avoiding
substitution of `R` for `a` in `B`:

```text
unfold(μa. B) = B[a := μa. B]
```

For `Tree[int]`, substitute the constructor for `F`, then apply `T :=
int`:

```text
unfold((μF. λT. tuple[T, F[list[T]] | None])[int])
= tuple[int, (μF. λT. tuple[T, F[list[T]] | None])[list[int]] | None]
(= tuple[int, Tree[list[int]] | None])
```

Tuple subscripting then selects the element at index 1: `x[1]:
Tree[list[int]] | None`.

## Test Plan

mdtest updated

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2026-09-18 04:01:49 +09:00
Ibraheem Ahmed acbae6584c [ty] Narrow type context during tuple inference (#28658)
When a tuple literal is inferred against a union type context, we should
narrow the union to the first compatible element.

```py
x: tuple[int, list[str]] | tuple[str, list[int]] = ("1", [True])
reveal_type(x)  # revealed: tuple[str, list[int]]
```
2026-09-17 01:51:20 +00:00
Ibraheem Ahmed 773a425dbe [ty] Infer conditional literals from peers in unspecialized contexts (#28633)
The type of one branch of a conditional expression may provide type
context for a collection literal in another, when no other type context
is present. This PR extends that to prefer peer context over
unspecialized type context in a generic call,
e.g.,`list[UnspecializedTypeVar]`, which provides no useful element
type.

```py
def f[T](values: list[T]) -> list[T]:
    return values

def _(values: list[object], flag: bool):
    reveal_type(f(values if flag else [1]))  # main: list[Unknown], now: list[object]
```
2026-09-16 14:16:34 -04:00
Carl Meyer 7ae3af9e7d [ty] Preserve tuple shapes during concatenation (#28617)
Tuple concatenation currently discards element positions and tuple
length, so adding two fixed-length tuples produces a variable-length
tuple. Preserve the concatenated shape, including known prefixes and
suffixes around variable-length portions.

As with tuple slicing and iteration, this (unsoundly) assumes values
annotated as `tuple` behave like ordinary tuples, even though a subclass
could override `__add__` and/or `__radd__` incompatibly. Explicitly
known subclasses continue to use their operator methods.

Keep inference bounded by approximating large tuple combinations and
widening tuple lengths when their alternatives change between cycle
iterations. Stable tuple unions, including those supplied by collection
type context, retain their shapes. Some cycles with finite but changing
tuple lengths can still lose precision to ensure convergence.

Fixes https://github.com/astral-sh/ty/issues/3413.

## Ecosystem impact

- Removes tuple-shape false positives in Hydra-zen, Trio, Spark, and
SymPy, and two unsoundness warnings in pandas.
- Most other changes make existing diagnostics more precise. New errors
expose overly narrow tuple attributes and collection element types in
zope.interface and SymPy, including invariant dictionary key types.
- One new xarray false positive exposes existing dictionary-key
inference that incorrectly restricts keys to strings. This limitation is
left for separate work. Cycle widening also loses finite tuple
alternatives in Apprise, consolidating existing errors without changing
which operations are rejected.

[Full ecosystem
analysis](https://github.com/astral-sh/ruff/pull/28617#issuecomment-5687202176).

## Performance

The `many_tuple_assignments` microbenchmark increases from 141.1 ms to
159.7 ms in simulation and from 6.4 MB to 6.9 MB in memory. This is an
expected cost of preserving tuple shapes; the tradeoff is acceptable for
this change. See the [benchmark
report](https://github.com/astral-sh/ruff/pull/28617#issuecomment-5684963921).

## Test plan

- Mdtests cover fixed and empty tuples, variable-length prefixes and
suffixes, aliases, union operands, subclass overrides, and
`TypeVarTuple` concatenation with both typing syntaxes.
- Exercise ordinary and augmented concatenation, large unions with
custom operators, repeated doubling, and recursively growing local
variables and instance attributes.
- Preserve finite alternating tuple shapes and fixed-length tuple unions
supplied by an empty list's return context.
- Verify incompatible augmented assignment to `tuple[Any, Any]` and
instance-layout conflicts detected through concatenated `__slots__`.
- Unit tests cover tuple widening across cycle results, including equal
lengths, changing lengths, discarded alternatives, avoiding relation
queries, and `Never` elements.
2026-09-15 13:24:13 -07:00
David Peter eacd85e79b [ty] Respect descriptor protocol for __set__ itself (#28408)
## Summary

This PR properly models the fact that implicit `__set__` calls should
also go through the descriptor protocol themselves, which handles edge
cases like `__set__` methods that are `@staticmethod`s. We also add
bidirectional inference support for (more) descriptor attribute
assignments, which is where the ecosystem improvement comes from:

```py
class DataDescriptor:
    def __set__(self, instance: object, value: list[int | None]) -> None:
        pass

class Meta(type):
    x: DataDescriptor = DataDescriptor()

class C(metaclass=Meta): ...

C.x = [1]  # now accepted, previously an error (Expected `list[int | None]`, found `list[int]`)
```

closes https://github.com/astral-sh/ty/issues/4485.

## Ecosystem

25 false positives removed!

## Test Plan

New Markdown tests
2026-09-09 15:32:33 +02:00
Ibraheem Ahmed 115657a25f [ty] Preserve gradual type context during generic call inference (#28091)
We currently ignore type context containing dynamic types entirely
during generic call inference. This was historically necessary to avoid
unsolved type variables from polluting future fixpoint iterations with
`Unknown` types. This PR distinguishes unsolved type variables from
dynamic types inferred from arguments with a dynamic marker type,
allowing us to retain applicable type context more often. This removes a
number of false positives, e.g.,
```py
from typing import Any

def append[T](items: list[T], value: T) -> None:
    items.append(value)

def example(value: str | Any) -> None:
    append([1], value)  # before: invalid-argument-type, after: ok
```
2026-09-02 22:09:59 -04:00
Carl Meyer 30334bcf03 [ty] Avoid repeated inference for literal union call results (#28196)
Checking a `TypedDict.get()` call with a default could become very slow
when its result was passed to a function expecting a large union of
literals. Contextual inference retried the call for each literal in the
expected type, even though the selected overload already returned a
compatible literal union.

Accept a literal-valued call result when it is a subtype of the complete
expected type. This avoids the redundant retries while preserving
contextual inference for gradual and nonliteral results. Resolve
explicit type aliases before checking whether the result consists of
literals.

On a generated reproduction with 1,036 literal members, checking time
falls from about 3 seconds to 0.04 seconds with an optimized debug
build.

I suspect this fix may be obsoleted by planned changes to bidirectional
inference, but it's a small enough fix, and effective, that it seems
worth applying now anyway.

Fixes astral-sh/ty#4419.

## Test plan

- Add mdtests for `TypedDict.get()` with optional fields, incompatible
defaults, and required fields with an explicit type alias.
- Cover precise nested generic calls, return types containing `Any`,
literal-union results in optional contexts, and expected unions
containing a generic collection alternative.
- Add a benchmark for a `TypedDict.get()` call with a 1,024-member
literal union.
2026-08-31 15:18:30 -07:00
Alex Waygood ad6cf1776e [ty] Preserve list literal positions in starred unpacking (#28061)
## Summary

Fix false-positive `invalid-assignment` diagnostics when unpacking list
literals, and consolidate the sequence matching, expansion, and
capture-list inference used for tuples and lists:

```python
first: int
first, *rest = [1, "wrong"]
```

Previously, unpacking the inferred `list[int | str]` lost the positions
of the individual elements and checked `int | str` against the
annotation on `first`. Preserving the literal's positions gives
`Literal[1]` for `first` and `list[str]` for `rest`.

The implementation shares the underlying operations across their
consumers:

- `Tuple::unpack` matches fixed and variable source sequences to fixed
and starred targets. Assignment unpacking, tuple resizing, and
sequence-pattern analysis use this matching logic.
- `TupleBuilder<T, V>` generalizes tuple construction and provides
shared concatenation through `concat_with`. Tuple inference can retain
symbolic `TypeVarTuple` segments, while assignment unpacking can retain
source expressions.
- A shared literal-expansion traversal serves assignment inference,
tuple-expression inference, and source-expression lookup for
diagnostics. It preserves nested literal positions and known prefixes
and suffixes around expansions without assigning persistent fixed-length
types to mutable lists.
- Starred assignments and sequence-pattern captures use the same helper
to infer their new lists, sharing literal and tuple-size promotion rules
with ordinary mutable-collection inference.

List literals now receive the same length-mismatch diagnostics and
unknown-type recovery as tuples. Starred captures from tuples also
follow mutable-list promotion rules, including `list[Unknown]` for empty
captures. The existing large-tuple precision limit counts elements
contributed by literal expansions, and its widening is preserved through
nested unpacking.

## Out of scope: contextual inference for unpacking

Unpacking does not currently use annotations on assignment targets as
type context when inferring the right-hand side. This is a pre-existing
limitation for both tuple and list right-hand sides. For example, these
valid assignments still produce false positives:

```python
from typing import Literal

value: list[Literal[1]]
value, other = ([1], 0)  # Inferred list[int] is rejected.
value, other = [[1], 0]  # Inferred list[int] is rejected.
```

In both cases, the nested list is inferred without the target's
annotation. Fixing this missing contextual inference is out of scope for
this PR.
2026-08-28 10:51:03 +01:00
Malkin0xb8 d894723886 [ty] Infer lambda parameters through callable type aliases (#28109) 2026-08-27 16:21:04 +01:00
Charlie MarshandShunsuke Shibayama 7e31571759 [ty] Propagate narrowing through statically known branches (#27752)
## Summary

Previously, narrowing was lost after a statically known branch because
the unreachable control-flow path still contributed its original type:

```python
def narrow(value: int | None) -> None:
    if 1 + 1 == 2:
        if value is None:
            return

    reveal_type(value)  # Previously: int | None; now: int
```

We now gate narrowing constraints with their corresponding reachability
conditions and reuse predicate identities across both analyses. This
allows narrowing to propagate through constant conditions, short-circuit
expressions, match guards, and statically non-empty `range()` loops
while preserving ambiguous branches.

Statement-level calls now participate in normal reachability analysis in
every scope, replacing the separate scope-wide narrowing machinery for
module- and class-level calls. As a result, the improved narrowing also
works inside module- and class-level loops, while preserving
terminal-call analysis, overload selection, and loop-carried forward
references.

Because these calls now contribute to reachability graphs, we raise the
nested-binding cutoff from 2,048 to 4,096 to preserve precision in
call-heavy scopes. The loop-reachability and loop-inference cutoffs
remain unchanged to protect performance on loop-heavy projects such as
isort and parso.

We also track the places each predicate can narrow, avoiding unnecessary
constraint inference and preventing unrelated reachability gates from
introducing cycles through deferred annotations. Lambda and generator
conditions are resolved without inferring their bodies, avoiding
recursive-callable inference cycles.

This also fixes exhaustive nested checks where proving that an outer
branch terminates depends on narrowing a separate inner value,
preventing spurious `assert_never` errors.

Based on @mtshiba's work in #27207 and #23201.

Closes https://github.com/astral-sh/ty/issues/4240.

---------

Co-authored-by: Shunsuke Shibayama <sbym1346@gmail.com>
2026-08-20 08:42:07 -04:00
Dhruv Manilawala c876a953dd [ty] Fix variadic signature display (#27869)
## Summary

Preserve the unpacking `*` in named variadic annotations and avoid
adding a redundant bare `*` before keyword-only parameters when `*args`
is already present. This fixes malformed revealed signatures without
changing signature storage or inference.

## Test plan

- Add a directly declared mixed-signature regression.
- Update TypeVarTuple partial, lambda, and bidirectional reveal
expectations.
- Regenerate existing single-line and multiline signature-display
snapshots.
2026-08-19 10:59:10 +05:30
Ibraheem Ahmed 4f5cc6e4df [ty] Preserve static upper bounds of gradual solutions (#27664)
We currently ignore concrete upper bounds when inferring a gradual
solution. We should instead be intersecting the gradual type with its
upper bound, e.g.,

```py
from typing import Any, Callable

def infer[T](lower: T, upper: Callable[[T], None]) -> T:
    return lower

def _(x: Any, upper: Callable[[int], None]):
    reveal_type(infer(x, upper))  # revealed: int & Any
```
2026-08-17 18:14:58 -04:00
5428c216bf [ty] Expand nested union aliases when finding a TypedDict or callable (#27740)
## Summary

A union-valued type alias nested inside another union stayed unexpanded,
hiding a TypedDict or callable from inference. Fixed by expanding
aliases before shape checks.

## Test Plan

Added mdtest.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Carl Meyer <carl@astral.sh>
2026-08-15 09:26:53 -07:00
Charlie Marsh 3115cba9a4 [ty] Preserve contextual inference for declarations in loops (#27594)
## Summary

Previously, a declaration inside a loop could be validated against a
prior iteration's assignment before that assignment received the
declaration's contextual type:

```python
from typing import TypedDict

class Record(TypedDict):
    value: int

while True:
    record: Record
    record = {"value": 1}
```

The dictionary was inferred as `dict[str, int]`, so we incorrectly
reported `invalid-declaration` and discarded the `TypedDict` context.

We now initialize declaration-only inference cycles with the declared
type when a synthetic loop-header binding is visible.

Ordinary assignments already initialize their cycles directly in
`DefinitionInference::cycle_initial`; for collection literals, this can
seed types such as `list[Divergent]`. Annotated declarations require a
separate builder path because resolving the annotation must respect
postponed evaluation, Python 3.14 forward references, qualifiers,
diagnostics, and metadata. `infer_annotated_assignment_cycle_initial`
therefore infers only the annotation and preserves its builder state
without performing full region inference.

This applies to both `while` and `for` loops and preserves genuine
declaration errors for incompatible pre-loop bindings.

Closes https://github.com/astral-sh/ty/issues/4206.
2026-08-08 13:59:30 -04:00
Charlie Marsh 9501d97402 [ty] Simplify numeric tower displays (e.g., float over int | float) (#27406)
## Summary

PEP 484's numeric tower means we represent a `float` annotation as the
semantic union `int | float*` and `complex` as `int | float* |
complex*`. We previously rendered those internal unions directly, which
exposed an implementation detail in user-facing output:

```python
def f() -> float:
    return 1

reveal_type(f())  # Before: int | float; after: float
```

This change recognizes complete numeric-tower unions during display and
renders them using their canonical annotation spelling, `float` or
`complex`.

The implementation does _not_ preserve explicit unions, e.g., if the
user writes out `int | float`, we still collapse that rather than trying
to preserve it, mostly for simplicity (as per
https://github.com/astral-sh/ty/issues/2184#issuecomment-4345219164).

Closes https://github.com/astral-sh/ty/issues/2184.
2026-08-05 21:29:29 +00:00
Charlie Marsh 8c30182896 [ty] Normalize unpacked callable signatures for assignability (#27450)
## Summary

Previously, we compared unpacked callable parameters in inconsistent
forms: the positional fast path inspected the original signatures, while
later matching sometimes expanded only the source. This could panic on
valid code or reject compatible assignments such as:

```python
from typing import Callable, Unpack

def callback(*args: str | None) -> None: ...

target: Callable[[Unpack[tuple[str, ...]], None], None] = callback
```

We now normalize both callable signatures before comparing them. Empty
and fixed-length unpacked tuples become positional parameters,
homogeneous tuples become variadic parameters with the correct element
type, and required target suffixes can be matched against source
variadics. The positional fast path, `ParamSpec` handling,
gradual-callable checks, and `TypeVarTuple` inference all use the same
normalized representation.

This also fixes previously unsupported `TypeVarTuple` inference for
nested unpacked parameters, callable protocols, and both legacy and PEP
695 callable aliases.

Closes https://github.com/astral-sh/ty/issues/4172.
2026-08-05 11:04:38 -04:00
Carl Meyer a4f873dfc5 [ty] Preserve exact numeric types in covariant collections (#27311)
## Summary

Fixes astral-sh/ty#4111.

Collection inference promotes exact runtime `float` and `complex`
elements to their numeric-tower unions, which can introduce types that
violate a covariant `Sequence` or `Iterable` context. Preserve the
original inferred element when it satisfies that context but the
promoted type does not.

This fixes the original `Sequence[str | Just[float]]` false positive
without changing `Just` protocol matching, invariant collection
inference, or ordinary mutable-list numeric widening.

## Test plan

Added focused bidirectional mdtests covering exact-float `Sequence` and
`Iterable` contexts, exact-complex sequence contexts, the original
`Just[float]` union, tuples, invariant and explicitly annotated lists,
rejection of actual integer and float mismatches, and preserved widening
for mutable float lists.

The full `ty_python_semantic` test suite and all applicable file-scoped
repository hooks pass.
2026-07-29 12:55:05 -07:00
Charlie MarshandCarl Meyer 8576b6f024 [ty] treat bivariance as covariant (#24319)
## Summary

Fixes https://github.com/astral-sh/ty/issues/1728.

Bivariance is confusing, not useful, and not in the spec. Fall back to
covariant when we would otherwise infer bivariance.

This is primarily a revival of
https://github.com/astral-sh/ruff/pull/23779, with a few preliminary
fixes in prior PRs.

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2026-07-25 01:22:51 -07:00
Ibraheem Ahmed e84ac0f592 [ty] Remove inferable typevar artifacts recursively (#26787)
Fixes the issues identified in
https://github.com/astral-sh/ruff/pull/26782#issuecomment-4963166161 by
improving our inferable typevar artifact detection, e.g.,
```py
from typing import Literal, Mapping

# error[invalid-assignment] Object of type `dict[str, str]` is not assignable to `Mapping[str, Literal["+", "-"]]`
operators: Mapping[str, Literal["+", "-"]] = {
    "plus": "+",
    "minus": "-",
}
```

Note that these were fixed indirectly by
https://github.com/astral-sh/ruff/pull/26782, but that PR did not solve
the underlying a problem, instead avoiding the solver path entirely.
2026-07-16 19:10:34 +00:00
Dhruv Manilawala 54acbcde56 [ty] Support TypeVarTuple and Unpack (#25240)
## Summary

closes: astral-sh/ty#156
closes: astral-sh/ty#1746

This PR adds initial support for `TypeVarTuple` and `Unpack` in ty.

### Supported

- Legacy `TypeVarTuple(...)` definitions from `typing` and
`typing_extensions`, including defaults, variance, and version
validation.
- PEP 695 `[*Ts]`, `Unpack[...]`, and starred unpack forms, with
diagnostics for invalid uses.
- Explicit specialization and substitution for generic classes and
aliases.
- Fixed and variable-length tuple construction, relations, display,
hover, and goto-type-definition.
- Legacy-solver inference from tuple arguments and returns,
constructors, and positional callable signatures.
- A `ParamSpec` following an unpacked variadic prefix.

### Representation and inference

A `TypeVarTuple` occupies one generic specialization slot and is
represented by a `TupleType`. Tuple specifications preserve a fixed
prefix and suffix around a variable middle and an unresolved / invalid
`TypeVarTuple` resolves as `tuple[Unknown, ...]`.

Callable inference constructs `ConstraintSet`s while matching positional
parameters in the signature relation. This keeps callable compatibility
and inference in the same loop instead of adding a separate
TypeVarTuple-specific path to `SpecializationBuilder`.

The work was briefly split into a [type-form
foundation](https://github.com/astral-sh/ruff/pull/26126) and generic
logic PR. I recombined them because the foundation alone caused
conformance and ecosystem regressions and did not represent complete,
independently reviewable behavior.

### Deliberate follow-ups

Call binding does not yet aggregate arguments matched to `*args` into a
`tuple`, or validate calls against concrete unpacked tuple annotations.
Per-argument inference is skipped because it would create incorrect
scalar mappings.

Nested tuple unpacking in callable parameter lists and some correlations
involving generic, overloaded, union, and inherited callables also
remain follow-ups. The ecosystem results show these callable cases
account for the main remaining false positives.

## Test Plan

- Added shared semantic coverage to the PEP 695 tests.
- Added legacy definition and specialization coverage.
- Kept the standalone `Unpack` coverage focused on its distinct syntax
paths.
- Reviewed the semantic suite, conformance results, and ecosystem
changes.
2026-07-16 16:17:11 +05:30
Ibraheem Ahmed 29344141c4 [ty] Implement unified generic call inference (#26141)
Generic call inference faces the problem of how to provide unspecialized
parameter types as type context to call arguments. We currently
specialize parameter types based on the annotated type of the call
expression. However, for unannotated calls, we fail to account for
constraints contributed by sibling arguments, for example:

```py
def f[T](x: T, y: list[T]) -> T:
    return x

def _(x: int | str, y: int):
    f(x, [y]) # error[invalid-argument-type]: Expected `list[int | str]`, found `list[int]`
```

Or a more complex example, which pyright is also unable to solve:
```py
def f[T](x: T, y: list[T], z: list[T]) -> T:
    return x

def _(x: int | str, y: int, z: int | str | None):
    f(x, [y], [z]) # error[invalid-argument-type]: Expected `list[int | str | None]`, found `list[int]`
```

We also fail to provide useful type coverage for lambda expressions in
generic signatures:
```py
x = map(lambda x: reveal_type(x) + 2, [1, 2, 3]) # revealed: Unknown
reveal_type(x) # revealed: map[Unknown]
```

This PR extends generic call inference to perform fixpoint iteration,
allowing inferred argument types to contribute type context constraints
to future iterations, until convergence. This allows us solve all the
examples above, as well as handle complex chains of dependencies such as
the following, which no other type checker currently supports:
```py
def chain[A, B, C, D](
    first: Callable[[C], D],
    second: Callable[[B], C],
    third: Callable[[A], B],
    source: list[A],
) -> D:
    return first(second(third(source[0])))

reveal_type(chain(  # revealed: int
    lambda c: reveal_type(c) + 1, # revealed: int
    lambda b: reveal_type(b) + 1, # revealed: int
    lambda a: reveal_type(a) + 1, # revealed: int
    [1, 2, 3],
))
```

Resolves https://github.com/astral-sh/ty/issues/2521, which I split into
a few sub-issues that remain as limitations of the fixpoint scheme. This
also resolves https://github.com/astral-sh/ty/issues/3469.

To avoid the overhead of multi-inference during fixpoint iteration, this
PR extends our local expression caching to support caching entire
inference region results, including diagnostics. This allows results
from speculative inference rounds to be reused during the final round of
fixpoint iteration. As a result, this PR is able to resolve
https://github.com/astral-sh/ty/issues/3597 with relatively minimal
overhead, which accounts for some of the new previously-suppressed
ecosystem diagnostics.

This also removes a significant part of the code added in
https://github.com/astral-sh/ruff/pull/24934, as the `ParamSpec`
re-inference path now naturally falls out of fixpoint iteration. I also
ended up reverting https://github.com/astral-sh/ruff/pull/26252 as part
of this change, as the performance implications seemed negligible, and I
don't think it warrants the extra complexity that it grew into (which
accounts for the small memory usage regression).
2026-07-15 17:48:49 -04:00
Ibraheem Ahmed 00b431e5a3 [ty] Remove transitive typevar artifacts during collection inference (#26714)
Use the `remove_inferable_typevar_artifacts_from_solution` helper from
https://github.com/astral-sh/ruff/pull/26099, instead of the current
naive union filtering during collection inference, to eliminate
unnecessary inferable type variables that prevent the constraint solver
from determining bidirectional inference type mappings. I also
reorganized the relevant tests slightly.

Resolves
https://github.com/astral-sh/ty/issues/3956#issuecomment-4940028081.
Note that the diagnostics there were a little misleading because the
callable types and concrete function types are rendered identically if
they have the same signature, despite being distinct types.
2026-07-10 19:45:36 -04:00
Ibraheem Ahmed eca693732f [ty] Reorganize bidirectional inference tests (#26675)
These tests are currently split across `assignment/annotations.md` and
`bidirectional.md` somewhat arbitrarily. I merged the two and
reorganized some of the larger snippets which had devolved into
catch-all sections.
2026-07-09 15:51:47 -04:00
Charlie Marsh 71541d4743 [ty] Infer empty collection constructors from later uses (#26389)
## Summary

Unannotated collection literals participate in full-scope bidirectional
inference, but empty constructor calls (`list()`, `set()`, and `dict()`)
did not. For example, we previously accepted this function because
`result` remained `set[Unknown]`:

```python
def make_set() -> set[str]:
    result = set()
    result.add(1)
    reveal_type(result)  # revealed: set[int | str]
    return result  # error: [invalid-return-type]
```

This PR treats bare, zero-argument `list()`, `set()`, and `dict()`
assignment values as collection initializers in the semantic index and
reuses the existing collection-use constraint inference. (For now, we
don't support aliased or attribute-accessed calls.)

Closes https://github.com/astral-sh/ty/issues/3573.
2026-06-26 06:39:45 -04:00
Charlie Marsh 95ddc340b7 [ty] Avoid cross-TypeVar leakage in generic inference (#26099)
## Summary

Generic return-type context can introduce relationships between type
variables while solving a call. We need those relationships during
constraint solving, but we previously reused them as concrete preferred
types during argument inference.

For example, inferring `dict(zip(keys, values))` against `Mapping[float,
int]` can derive a key solution containing the value TypeVar and a value
solution containing the key TypeVar. Treating those intermediate
relationships as final solutions causes both `dict` parameters to widen
to `int | float`. This fails on `main`:

```python
from collections.abc import Iterable, Mapping

def build(
    keys: Iterable[float],
    values: Iterable[int],
) -> Mapping[float, int]:
    return dict(zip(keys, values))
```

This projects inferable TypeVar artifacts within each source binding
context before using solutions as preferred types. Relationships across
separate generic contexts remain intact, preserving constructor `self`
remapping and similar inference.
2026-06-17 10:01:26 -04:00
Charlie Marsh 966bc5e029 [ty] Avoid oscillating collection-use constraints (#26031)
## Summary

Full-scope collection inference can introduce a Salsa cycle when
multiple unannotated collections are constrained by the same container
literal:

```python
from typing import Any

def run(cond: bool, d: dict[Any, Any]) -> list[Any]:
    a = {}
    b = {}
    if cond:
        b = d
    return [a.get("x", 0), b.get("x", 0)]
```

To infer `a = {}` and `b = {}`, we collect constraints from later uses
such as `a.get(...)` and `b.get(...)`. This creates a cycle because
inferring the literals requires inferring the return statement, while
inferring the calls requires resolving the literal definitions.

The conditional assignment makes `b`'s collection-use constraint
unstable across fixed-point iterations. Without that constraint, `b`
remains `dict[Unknown, Unknown]`, which exposes a single class
specialization at `b.get(...)` and records the constraint on the next
iteration. Once recorded, the literal refines to `dict[Unknown, int |
Unknown]`; joining it with `d` produces `dict[Unknown, int | Unknown] |
dict[Any, Any]`, which no longer exposes a single class specialization,
so the constraint disappears again. The constraint map therefore
alternates between `{a}` and `{a, b}` even after the expression and
binding types converge, eventually reaching Salsa's cycle-iteration
limit and panicking. The existing cycle-initial values let evaluation
begin but do not make this metadata monotonic.

Once the initial tainted iterations have passed, this preserves
collection-use constraints from previous iterations across scope,
definition, expression, and statement inference. The constraint map now
grows monotonically and reaches a fixed point, while definition
inference expands compact metadata only when needed and preserves its
other retained fields. The regression coverage includes both direct
returns and annotated assignments.

Closes https://github.com/astral-sh/ty/issues/3778.
2026-06-15 22:03:02 -04:00