Commit Graph
121 Commits
Author SHA1 Message Date
Micha Reiser d8958d600b [ty] Use typed arena nodes in semantic and IDE queries
Use parser row IDs for stored AST references. Read the corresponding
borrowed node in inference, reference search and IDE queries.
2026-11-30 16:36:39 +00:00
David Peter d5d119bc18 [ty] attrs: Strip leading underscores for private fields (#30824)
## Summary

attrs classes have a feature where the leading underscores for a private
field like `_id` are stripped for the parameter name that corresponds to
this field, i.e. the constructor takes a keyword parameter `id` instead.
The attribute is still accessed through the original name:

Here, we implement this feature in ty:

```py
from attrs import define

@define
class User:
    _id: int
    name: str

user = User(id=1, name="John Doe")  # ty now accepts this (previously emitted two errors)
```


Closes astral-sh/ty#1742
Closes astral-sh/ty#2474

Stacked on #30823.

## Ecosystem

There are no projects in the ecosystem that would profit from this new
feature. I tested on two other projects:

jsonschema:

```diff
--- before
+++ after
@@ -16,3 +15,0 @@
-jsonschema/benchmarks/issue232.py:15:12: error[missing-argument] No arguments provided for required parameters `_path`, `_remotes`
-jsonschema/benchmarks/issue232.py:16:5: error[unknown-argument] Argument `path` does not match any known parameter
-jsonschema/benchmarks/issue232.py:17:5: error[unknown-argument] Argument `remotes` does not match any known parameter
@@ -38,4 +34,0 @@
-jsonschema/tests/_suite.py:73:16: error[missing-argument] No arguments provided for required parameters `_path`, `_remotes`
-jsonschema/tests/_suite.py:75:13: error[unknown-argument] Argument `path` does not match any known parameter
-jsonschema/tests/_suite.py:76:13: error[unknown-argument] Argument `remotes` does not match any known parameter
-jsonschema/tests/_suite.py:152:17: error[unknown-argument] Argument `remotes` does not match any known parameter
@@ -195 +188 @@
-Found 194 diagnostics
+Found 187 diagnostics
```

cattrs:

```diff
--- before
+++ after
@@ -262,2 +261,0 @@
-tests/test_converter.py:412:12: error[missing-argument] No argument provided for required parameter `_a`
-tests/test_converter.py:412:14: error[unknown-argument] Argument `a` does not match any known parameter
@@ -480 +478 @@
-Found 479 diagnostics
+Found 477 diagnostics
```
2026-11-23 15:59:14 +01:00
Charlie Marsh dffb1c0134 [ty] Reuse parent package searches for dotted imports (#30743)
## Summary

When resolving `acme.tools.power` and `acme.tools.manual`, ty searches
for `acme.tools` twice. We now reuse the same parent search that module
enumeration already caches.

Both import resolution and module enumeration walk prefixes deeper than
16 components iteratively to bound recursion. In typing mode, we also
walk the parent when extra paths are configured. A stub on one of those
paths can satisfy the import without the full search needed to save a
snapshot. Runtime lookups ignore stubs and can reuse the cached search.

In [OpenTelemetry Python
Contrib](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/ea8ef02ad1b31e688d5f481edc38f7ef54ecef9c),
`opentelemetry.instrumentation` spans 56 directories. Checking the
locked workspace used 4.62–4.71% fewer instructions across four pairs.
Median peak RSS went from 650 to 648 MiB, within run-to-run variation.
With an extra search path configured, instruction counts changed by less
than 0.06%.

Saving the parent costs more if we only look it up once. In a synthetic
check of 200 imports from one regular package, instructions fell by
6.84%. With one import from each of 200 regular packages, instructions
rose by 1.13% and ty retained 48 KiB more.

The same tradeoff applies to missing packages. If `acme` is missing, we
cache the failed searches for both `acme` and `acme.tools`. The next
import under `acme.tools` can reuse that result. If every import starts
with a different missing package, we pay to cache every prefix and reuse
none of them.

In a synthetic check of 1,500 distinct missing packages with
16-component parents, instructions rose by 26% and median peak RSS rose
by 6 MiB. Median elapsed time went from 24.1 to 28.0 ms (+16%). With
three-component parents, the increase was 0.5 ms (+2.5%).

Home Assistant’s 2,463 distinct unresolved dotted names shared just
1,034 parent prefixes, none deeper than five components. Checking those
names in isolation used 5.8% fewer instructions. Given that reuse, we
keep caching failed searches. Checking for a missing root first would
add a lookup to successful imports too.

All three projects below used fewer instructions with third-party
dependencies absent. Diagnostics matched byte for byte. Elapsed times
were too noisy to establish a speedup. These checks and the
missing-import experiments above used single-threaded macOS release
builds of
[`main`](https://github.com/astral-sh/ruff/commit/5dfd0f646e1f462623a6c6460fbb4d228dc61319)
with and without this patch. OpenTelemetry had 71 workspace source
roots.

| Project | Unresolved imports | Median change in instructions |
| --- | ---: | ---: |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 13,794 | −0.60% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 6,320 | −0.29% |
| [OpenTelemetry Python
Contrib](https://github.com/open-telemetry/opentelemetry-python-contrib/tree/ea8ef02ad1b31e688d5f481edc38f7ef54ecef9c)
| 2,074 | −8.07% |

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

Across 28 projects, the mean change in instructions was −0.15% and the
median was −0.14%.

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

Both builds use the linked base. Django used one worker to keep
diagnostics deterministic.

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/2bd2c4d36de90b37635997c9199f5df8a8fe31c3)
| [Base + PR
instructions](https://github.com/astral-sh/ruff/commit/bdfe08cd3b984efb871fbb2ee846e89e2eadf1cf)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
(inconclusive) | 3,035,805,147 | 3,035,320,212 | -0.02% | -0.03% to
0.00% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
(inconclusive) | 7,776,176,049.5 | 7,781,380,458 | +0.07% | +0.02% to
+0.11% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
| 149,766,549,803.5 | 148,835,735,567.5 | -0.62% | -0.64% to -0.60% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
(inconclusive) | 1,662,561,737.5 | 1,662,814,287 | +0.02% | -0.16% to
+0.19% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
(inconclusive) | 1,860,289,614.5 | 1,859,766,000 | -0.03% | -0.08% to
+0.03% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
| 26,543,964,589.5 | 26,483,536,241 | -0.23% | -0.25% to -0.21% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,822,552,780.5 | 2,814,102,332 | -0.30% | -0.54% to
-0.06% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
(inconclusive) | 4,786,836,243.5 | 4,785,624,338.5 | -0.03% | -0.04% to
-0.01% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 90,881,728,809 | 90,679,875,516.5 | -0.22% | -0.26% to -0.18% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
(inconclusive) | 1,615,725,340 | 1,613,354,577.5 | -0.15% | -0.25% to
-0.04% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
| 7,973,735,155.5 | 7,953,902,714.5 | -0.25% | -0.31% to -0.19% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
| 2,893,946,489.5 | 2,888,155,176 | -0.20% | -0.22% to -0.18% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
(inconclusive) | 20,123,321,494 | 20,074,533,814.5 | -0.24% | -0.44% to
-0.05% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
(inconclusive) | 2,618,802,463 | 2,607,475,358.5 | -0.43% | -0.60% to
-0.26% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 13,054,205,558.5 | 13,023,589,025.5 | -0.23% | -0.23% to -0.23% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
(inconclusive) | 43,129,882,307 | 43,089,556,170 | -0.09% | -0.10% to
-0.09% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
(inconclusive) | 14,935,956,580.5 | 14,930,184,361.5 | -0.04% | -0.04%
to -0.03% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
(inconclusive) | 8,386,846,754.5 | 8,383,351,780 | -0.04% | -0.05% to
-0.03% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
(inconclusive) | 3,876,188,847 | 3,878,577,214 | +0.06% | +0.05% to
+0.07% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
| 13,607,173,854.5 | 13,569,086,556.5 | -0.28% | -0.30% to -0.26% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
(inconclusive) | 2,871,519,569.5 | 2,865,634,780.5 | -0.20% | -0.34% to
-0.07% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
(inconclusive) | 4,544,903,543.5 | 4,538,836,358.5 | -0.13% | -0.25% to
-0.01% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
| 31,659,271,039 | 31,614,329,533 | -0.14% | -0.20% to -0.09% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
| 14,744,726,701.5 | 14,728,928,921.5 | -0.11% | -0.13% to -0.08% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
(inconclusive) | 12,190,613,602 | 12,188,584,211 | -0.02% | -0.08% to
+0.05% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
| 54,349,754,101 | 54,299,167,841 | -0.09% | -0.12% to -0.07% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
| 8,522,553,638.5 | 8,501,716,679 | -0.24% | -0.27% to -0.22% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
(inconclusive) | 93,925,737,139.5 | 93,870,896,920 | -0.06% | -0.08% to
-0.04% |

</details>

<!-- ty-pinned-project-instructions:end -->
2026-11-22 10:29:05 -05:00
Charlie Marsh cd2d973241 [ty] Cache the source scan for legacy namespace packages (#30646)
## Summary

When resolving `acme.foo` and `acme.bar`, ty checks whether
`acme/__init__.py` declares a legacy namespace package. It scans the
initializer for `pkg` or a non-ASCII character to decide whether to
inspect its AST. We now do that scan inside the existing Salsa query for
the declaration, so the second import reuses the result.

On a cold check of the ElevenLabs SDK, this reduces the number of scans
of its 395 KB initializer from 3,196 to one. Across two pairs in
opposite orders, Cachegrind counted 2.26–2.29% fewer instructions for
the full SDK, 7.90–7.95% fewer for its `types` subpackage, and
19.44–19.45% fewer for the initializer alone. Whole-process counts for
the same binary varied by less than 0.1% on the shared Linux host.
Native diagnostics and exit codes matched. Across six native full checks
per binary, median peak RSS was 290.3 MiB at each revision. [Pinned
ElevenLabs
SDK](https://github.com/elevenlabs/elevenlabs-python/tree/bc814005e4319298b3c9ae5c301c7d326f630dbd/src/elevenlabs)

## Pinned projects

A separate serial repeat of pytest on a second Linux host gave paired
changes of −0.04% and +0.02%.

| Project | [Base
instructions](https://github.com/astral-sh/ruff/commit/a866aff503fd777156c1ae4eae318a3795fa09ec)
| [PR
instructions](https://github.com/astral-sh/ruff/commit/9a67447be6b9c2f64738c2cd11c73c264851f0b0)
| Change | Paired range |
| --- | ---: | ---: | ---: | ---: |
|
[Black](https://github.com/psf/black/tree/55996d1fb8342725c8a19b6023cd9439c3c1d6f7)
(inconclusive) | 3,178,748,691 | 3,174,913,589 | -0.12% | -0.29% to
+0.05% |
|
[discord.py](https://github.com/Rapptz/discord.py/tree/65232c38702be5844cf2ce865a4777eb1928b5d0)
(inconclusive) | 8,248,744,405.5 | 8,245,299,717 | -0.04% | -0.14% to
+0.06% |
| [Home
Assistant](https://github.com/home-assistant/core/tree/c19ae285ede74cd64c3045a3a4aa43290c224f1b)
(inconclusive) | 159,260,027,629.5 | 159,225,508,155.5 | -0.02% | -0.03%
to -0.01% |
|
[isort](https://github.com/pycqa/isort/tree/a514c71ed86c2216d0040c7d60e302ed76a4f7ab)
(inconclusive) | 1,856,407,835 | 1,860,428,623.5 | +0.22% | +0.07% to
+0.37% |
|
[Jinja](https://github.com/pallets/jinja/tree/5ef70112a1ff19c05324ff889dd30405b1002044)
(inconclusive) | 1,949,337,142.5 | 1,945,417,346 | -0.20% | -0.41% to
0.00% |
|
[pandas](https://github.com/pandas-dev/pandas/tree/a0225b65720018f4654390bb16d254daa6ee5e54)
(inconclusive) | 28,826,044,230.5 | 28,826,733,581.5 | 0.00% | -0.04% to
+0.05% |
|
[pandas-stubs](https://github.com/pandas-dev/pandas-stubs/tree/8dd6d91b1c05b26e30f7ddbe3dc3d4042a92bdd6)
(inconclusive) | 2,968,379,021 | 2,969,719,812 | +0.05% | -0.06% to
+0.15% |
|
[Prefect](https://github.com/PrefectHQ/prefect/tree/a9452ac21852755311913cb27887b083b5007c03)
(inconclusive) | 4,960,102,447.5 | 4,957,131,296.5 | -0.06% | -0.09% to
-0.03% |
|
[PyTorch](https://github.com/pytorch/pytorch/tree/ab92945cea42e47ae398aead69af0872d340ea0f)
| 96,692,044,248.5 | 96,378,912,743 | -0.32% | -0.35% to -0.30% |
|
[HTTPX](https://github.com/encode/httpx/tree/b5addb64f0161ff6bfe94c124ef76f6a1fba5254)
(inconclusive) | 1,682,696,447 | 1,682,428,734 | -0.02% | -0.04% to
0.00% |
|
[NumPy](https://github.com/numpy/numpy/tree/f9f1772ce010001208475f751d19253469788410)
(inconclusive) | 8,558,491,370 | 8,499,067,443.5 | -0.30% | -1.65% to
+0.12% |
|
[FastAPI](https://github.com/fastapi/fastapi/tree/7a0a3f0b286c6c865cf4398ea0e957a87b8bffa4)
(inconclusive) | 3,009,583,978 | 3,017,346,301.5 | +0.26% | +0.05% to
+0.47% |
|
[SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy/tree/10f4d1e2d706a7722ca78e79ce05b00333a7aa5b)
(inconclusive) | 21,542,870,931.5 | 21,547,724,566.5 | +0.02% | -0.06%
to +0.11% |
|
[Rich](https://github.com/Textualize/rich/tree/9d8f9a372cc5916fd4781fec207ced7ddac2f08f)
(inconclusive) | 2,725,097,960 | 2,724,078,034.5 | -0.04% | -0.22% to
+0.14% |
|
[Django](https://github.com/django/django/tree/b501b8493f31cf8cba31211d59b3b78642b8cb02)
| 13,918,364,147.5 | 13,904,689,945 | -0.10% | -0.11% to -0.09% |
|
[SymPy](https://github.com/sympy/sympy/tree/85d3998a4517ffbc8a9709b8efa769bb417c174a)
(inconclusive) | 46,173,816,069 | 46,179,681,370 | +0.01% | -0.04% to
+0.07% |
| [OpenAI Python
SDK](https://github.com/openai/openai-python/tree/f6e8480f9a5b2a4d02b17a1da54a1e57964bc312)
(inconclusive) | 16,014,171,701.5 | 16,010,275,990.5 | -0.02% | -0.06%
to +0.02% |
|
[pytest](https://github.com/pytest-dev/pytest/tree/8b005ed7f972987033ec34dc1e68b0635fb8142b)
| 8,810,647,525 | 8,820,278,813.5 | +0.11% | +0.01% to +0.21% |
|
[aiohttp](https://github.com/aio-libs/aiohttp/tree/fe099491d275ef2c21bf683e024e34d51ac05d43)
(inconclusive) | 4,174,366,524 | 4,177,098,277.5 | +0.07% | -0.05% to
+0.18% |
|
[Ansible](https://github.com/ansible/ansible/tree/b4b2b1e82a535d27f902a71fc8396c3af138fca2)
(inconclusive) | 14,452,378,733 | 14,437,861,533 | -0.10% | -0.20% to
0.00% |
|
[botocore](https://github.com/boto/botocore/tree/e250abbe956da791c16086575e6ddb1f2da81a78)
(inconclusive) | 3,026,292,874.5 | 3,029,196,613 | +0.10% | +0.08% to
+0.11% |
|
[Celery](https://github.com/celery/celery/tree/9c2f238334331db43f15956f131235fd3bb70fd1)
| 4,827,798,774.5 | 4,821,536,377.5 | -0.13% | -0.16% to -0.10% |
|
[Dask](https://github.com/dask/dask/tree/249a51a1db4261791b93b4ce04e67341729939c3)
(inconclusive) | 34,971,675,208.5 | 34,966,310,558 | -0.02% | -0.08% to
+0.04% |
|
[NetworkX](https://github.com/networkx/networkx/tree/6855cd586982cc2e4710b8eb87251ccf56674bf1)
(inconclusive) | 15,759,330,379 | 15,755,091,719.5 | -0.03% | -0.06% to
0.00% |
|
[Pydantic](https://github.com/pydantic/pydantic/tree/560f0f96a37d6913afdfddb2de22030ef08e68c3)
(inconclusive) | 13,067,367,266.5 | 13,066,164,729 | -0.01% | -0.08% to
+0.06% |
|
[scikit-learn](https://github.com/scikit-learn/scikit-learn/tree/ee56c8b5d809dc7b970a140ed501269b63c69cf8)
(inconclusive) | 66,903,831,941.5 | 66,912,575,359.5 | +0.01% | -0.09%
to +0.12% |
|
[Scrapy](https://github.com/scrapy/scrapy/tree/e63a574c767d7a9438c21db158f605f1c44c6e6a)
(inconclusive) | 8,973,193,530 | 8,979,773,814 | +0.07% | -0.04% to
+0.18% |
|
[Transformers](https://github.com/huggingface/transformers/tree/3a134bc37f7c22c801b618e289b0255425f22647)
| 102,122,268,229 | 102,017,337,166.5 | -0.10% | -0.11% to -0.10% |
2026-11-20 19:43:11 -05:00
astral-automations-bot[bot]andBrent Westbrook a7ba68b491 Bump version to 0.17.6 (#30578)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-11-19 10:32:47 -05:00
Lérè a6d1e6c421 [ty] Compute import edits for package directory renames (#30083)
## Summary

Towards refining our [recent support for the LSP's file rename
refactor](https://github.com/astral-sh/ty/issues/1560), this updates the
`will_rename.rs` helper module to compute import and reference edits for
same-parent renames of (1) regular packages and (2) namespace packages
supplied by one directory. For example, renaming `pkg/old/` to
`pkg/new/` updates references such as `pkg.old.helpers` to
`pkg.new.helpers`.

/xref https://github.com/astral-sh/ty/issues/4945

## Approach

Map each import name that resolves to the renamed directory to its new
package name. The existing import and reference passes use those
mappings for resolved descendants. When a file and a folder in the same
batch would acquire the same import name, skip the conflicting edits.

## Test Plan

See included tests.
2026-11-16 21:47:19 -08:00
Lérè f87d46534f [ty] Expose module locations for filesystem renames (#30082)
## Summary

This PR provides a new method that uses our module resolver to answer
the question of which directories contribute to a single importable
Python package. This is used in [upcoming support of package directory
renames](https://github.com/astral-sh/ty/issues/4945) to validate that
the rename is supported (when a single directory provides the entire
package; renames for split namespace packages are not supported).

## Notes to reviewers

`Module::package_directories` returns the local directories supplying a
resolved package in the requested resolution mode. It follows the
resolver's search order, returning the selected directory for a regular
package or all contributing directories for a namespace package. It
returns `None` for single-file modules, vendored packages, or when the
requested mode selects a different module.

See included tests.
2026-11-16 21:47:19 -08:00
Brent Westbrook 244668339a Adopt new APIs from Rust 1.98 (#30419)
Summary
--

- The first commit uses [strip_circumfix] to remove paired delimiters in
one call.
- The second commit uses [map_or_default] to combine many `map` and
`unwrap_or_default` calls.
- The third commit uses [bool::ok_or] to turn boolean checks into
`Result<(), E>` values.
- The fourth commit uses [str::substr_range] to get the byte range of a
TODO directive directly from the comment.

The last commit is slightly more involved than the others, as Codex
found a panic in the old code if
a `HACK` TODO comment used the Kelvin sign as its `K` and added a test
showing that `substr_range`
helped to fix it. That seems absurdly niche, but the new code is simpler
anyway.

There's also a new [format_into] API for formatting integers into a
`NumBuffer` and bypassing some
`Display` overhead. We could use this in the `UP031` fix, but it makes
the code a bit more
complicated and seemed worth trying and benchmarking separately to see
if it's worth the trouble.

[strip_circumfix]:
https://doc.rust-lang.org/stable/std/primitive.str.html#method.strip_circumfix
[map_or_default]:
https://doc.rust-lang.org/stable/std/option/enum.Option.html#method.map_or_default
[bool::ok_or]:
https://doc.rust-lang.org/stable/std/primitive.bool.html#method.ok_or
[str::substr_range]:
https://doc.rust-lang.org/stable/std/primitive.str.html#method.substr_range
[format_into]:
https://doc.rust-lang.org/stable/core/primitive.usize.html#method.format_into
2026-11-16 10:04:15 -05:00
0ebb77d35c Bump version to 0.17.5 (#30380)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-11-12 17:26:23 +00:00
Lérè 1317821e56 [ty] Compute edits for Python file renames (#28329)
## Summary

This adds an (as of yet unused) IDE operation called
[`will_rename_files`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L140)
that computes edits to update import statements and imported module
references when a Python file is renamed. For example, renaming
`pkg/old.py` to `pkg/new.py` changes `from pkg import old` to `from pkg
import new` and `old.C` to `new.C`.

I have deliberately restricted the scope of renames that we support such
that we do *not* support the following in this delivery:

- Requests that rename a directory
- Requests that change a module parent (e.g., renaming `a.old` to
`b.new` or `new`)
- Requests that rename an `__init__.py` or `__init__.pyi` file
- Requests that change the extension of a module (e.g., from `.py` to
`.pyi`)

Those are all challenging to support, and not uniformly supported by
other language servers, so I think they are reasonable scope cuts. This
initial delivery was also large enough as it is.

All of the edits we compute are best-effort: we do as much as we can
safely but we may decline to rewrite some references or imports that
should in fact be rewritten. That policy is worth debate, but I think
it's the right thing to do in the face of the fact that the [language
server
protocol](https://github.com/microsoft/language-server-protocol/blob/gh-pages/_specifications/lsp/3.17/workspace/willRenameFiles.md)
does not guarantee that `workspace/willRenameFiles` can cancel the
underlying file rename request, so there's no reliable way to outright
reject requests that we can't handle. As a result, the user will be
forced into fixing their code no matter what, so we might as well get
them as far along as possible. This approach is also consistent with
other language servers.

## Approach

`will_rename_files` maps file paths to module names, then calls
[`edits_for_file`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L230)
in parallel to plan edits in two AST passes over each candidate file:

1.
[`ImportStatementVisitor`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L300)
plans alias name and module field rewrites and records bound name
changes.
2.
[`ModuleReferenceVisitor`](https://github.com/astral-sh/ruff/blob/619109d77ff5f2ade5fcec8d4edaa84e363c335c/crates/ty_ide/src/will_rename.rs#L855)
uses reaching definitions and module types to find references to renamed
modules, including references in string annotations.

Thanks to @abcvav for the initial implementation of these ideas in
#25095; we adopt their design of building a single mapping from old
module names to new ones for the whole batch, then using that mapping
and the semantic model to plan import and reference edits as we walk
each file’s syntax tree.

## Test Plan

See included tests.
2026-11-05 14:29:37 -08:00
astral-automations-bot[bot]andBrent Westbrook 05cdc36a45 Bump version to 0.17.4 (#30073)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-11-05 13:22:15 -05:00
Micha Reiser b95fcfbf91 [ty] Stop scanning a package after its first legacy namespace declaration (#29885)
## Summary

Stop scanning a package initializer once ty recognizes a legacy
namespace declaration. The resolver examines only module-level
statements and accepts the existing `pkgutil.extend_path` and
`pkg_resources.declare_namespace` forms.

On the large parser fixture, the declaration check used the following
instruction counts. These cover the top-level scan and pattern matching,
excluding the calls to obtain and load the parsed module.

| Declaration in `__init__.py` | Top-level statements | Visitor (before)
| Iterator (after) | Reduction |
| --- | ---: | ---: | ---: | ---: |
| First statement | 113 | 2,595 | 454 | 2,141 (82.5%) |
| Absent | 112 | 3,189 | 1,290 | 1,899 (59.5%) |

All three paired runs produced the same counts. The full `ty check` used
0.004% fewer instructions with the declaration first.

## Test Plan

The legacy namespace and partial stub package import mdtests passed.
2026-11-02 14:05:12 +00:00
astral-automations-bot[bot]andBrent Westbrook ba65abf8ba Bump version to 0.17.3 (#29745)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-10-26 20:14:27 -04:00
David Peter 005a313334 [ty] Django: synthesize <field>_id attributes for foreign keys (#29664)
## Summary

This PR adds support for the `<field>_id` attributes that Django
generates for foreign keys. Their types follow the related model's
primary key, or the field specified by `to_field`.

Example:

```py
from django.db import models

class Author(models.Model):
    pass

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

def _(book: Book):
    reveal_type(book.author)  # Author
    reveal_type(book.author_id)  # int
```

Towards https://github.com/astral-sh/ty/issues/1018.

## Test Plan

New Markdown tests. I checked against Django runtime behavior.
2026-10-23 16:42:14 +02:00
David Peter 30be8844b9 [ty] Very basic Django support (#29642)
## Summary

This PR adds basic tests for Django support in ty, and adds a first
customization point where we now synthesize `.id` and `.pk` attributes
for primary keys on Django models. Django support currently relies on
`django-types`, a fork of `django-stubs` which requires less
special-casing in type checkers.

Example
```py
from django.db import models

class Book(models.Model):
    isbn = models.CharField(max_length=13, primary_key=True)
    title = models.CharField()
    pages = models.IntegerField(null=True)

def _(book: Book):
    reveal_type(book.isbn)   # str
    reveal_type(book.title)  # str
    reveal_type(book.pages)  # int | None  (because null=True)

    reveal_type(book.pk)     # str  (because `isbn` is the primary key)

    book.id  # error: no automatic `id` with a custom primary key
```

## Test Plan

I wrote new Markdown test and also verified all of our assertions
against Django's runtime behavior.
2026-10-22 20:20:48 +00:00
astral-automations-bot[bot]andBrent Westbrook 30516b42ab Bump version to 0.17.2 (#29637)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-10-22 13:54:24 -04:00
Carl Meyer d2d9e8a54e [ty] Preserve namespace fallback for partial stub packages (#29559)
Partial stub packages could hide runtime submodules when the
corresponding package used `pkgutil.extend_path` or was an implicit
namespace package. Preserve runtime namespace candidates while resolving
descendants so modules missing from partial stubs can fall back to the
implementation.

Track concrete stub packages separately from ordinary packages,
preserving normal namespace shadowing, complete-stub behavior, and
partial subpackages.

Closes https://github.com/astral-sh/ty/issues/4767.
2026-10-20 20:43:32 -07:00
David Peter f916ac2e0e [ty] Avoid inserting inlay hints containing stub-only types (#29477)
## Summary

Do not suggest "baking in" types like `Unknown` that come from
`ty_extensions`, since (1) this is certainly not what you want, and (2)
it wouldn't work at runtime without `if TYPE_CHECKING` or similar. Do
the same for types from typeshed-internal modules.

Addresses
https://github.com/astral-sh/ruff/pull/29437#discussion_r4298527405

## Test plan

New and changed snapshot tests
2026-10-19 23:16:54 +02:00
astral-automations-bot[bot] 4683270c69 Bump version to 0.17.1 (#29420)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
2026-10-15 10:56:41 -04:00
astral-automations-bot[bot]andBrent Westbrook 5b27c1ccfa Bump version to 0.17.0 (#29259)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-10-09 13:45:29 -04:00
astral-automations-bot[bot]andBrent Westbrook 3265ed1f94 Bump version to 0.16.10 (#29055)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <brentrwestbrook@gmail.com>
2026-10-01 13:40:09 -04:00
Charlie Marsh 41d30df6fd Update Rust toolchain to 1.99 and MSRV to 1.97 (#29047)
## Summary

- Update the Rust toolchain to 1.99.0 and the MSRV to 1.97, following
our N-2 support policy.
- Address the new Clippy warnings and preserve our existing assertion
and formatting macro conventions.
- Update Hawk to 0.1.15 and run it with Rust 1.99.0.
2026-10-01 12:20:10 -04:00
Lérè c47570f5aa [ty] Skip descendant searches for leaf modules (#28845)
## Summary

This avoids unnecessary submodule enumeration when recursively
enumerating all modules for auto-import completions. It recovers most of
the performance penalty incurred by its
[predecessor](https://github.com/astral-sh/ruff/pull/28202).

## Approach

I updated `ModuleSearchCursor::list_modules` to use the directory
entries it already reads during name discovery to track whether each
name is supplied by a non-symlink directory specifically. It then
records the corresponding resolved modules in
`ModuleListing::modules_with_possible_children`, which
`resolve::list_all_modules` uses to select modules for recursion.

## Test Plan

This is a behaviour-preserving refactor that relies on existing tests.
2026-09-28 09:00:31 -07:00
Lérè 430b3ea3e0 [ty] Add namespace package support to import completions. (#28202)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

This adds support for suggestions that come from namespace packages to
auto-imports, missing import quick fixes, and import statement
completions. For example, if `acme/reports.py` defines `Report` but
`acme` has no initializer, ty now offers `Report` with `from
acme.reports import Report`, even before `reports.py` has been opened or
imported.

## Approach

Auto-imports use
[all_symbols](https://github.com/astral-sh/ruff/blob/14c830fa85aea966e3c4ea70b6f5ff6f57f6b2c6/crates/ty_ide/src/all_symbols.rs#L17-L35)
to collect symbols from the modules returned by
[all_modules](https://github.com/astral-sh/ruff/blob/14c830fa85aea966e3c4ea70b6f5ff6f57f6b2c6/crates/ty_module_resolver/src/list.rs#L7-L25).
Previously, that traversal started with
[list_modules](https://github.com/astral-sh/ruff/blob/4137cd0d9a4a70299b9008e4ad103a34e7ed6abc/crates/ty_module_resolver/src/list.rs#L29-L34),
which discovers top-level modules, and recursed through
[Module::all_submodules](https://github.com/astral-sh/ruff/blob/4137cd0d9a4a70299b9008e4ad103a34e7ed6abc/crates/ty_module_resolver/src/module.rs#L141-L143).
The latter [intentionally returned no children for namespace
packages](https://github.com/astral-sh/ruff/blob/4137cd0d9a4a70299b9008e4ad103a34e7ed6abc/crates/ty_module_resolver/src/module.rs#L195-L202),
so their descendants were never considered for auto-imports.

`list_modules` and `Module::all_submodules` now use
[resolve::list_root_modules](https://github.com/astral-sh/ruff/blob/9b24ab90d2022cd6086b295e0d9f7d8e70d3a9f8/crates/ty_module_resolver/src/resolve/search.rs#L67-L73)
and
[resolve::list_submodules](https://github.com/astral-sh/ruff/blob/9b24ab90d2022cd6086b295e0d9f7d8e70d3a9f8/crates/ty_module_resolver/src/resolve/search.rs#L77-L96),
respectively. Both queries delegate to `ModuleSearchCursor` to enumerate
across namespace portions using the existing module resolution rules.
[resolve::list_all_modules](https://github.com/astral-sh/ruff/blob/9b24ab90d2022cd6086b295e0d9f7d8e70d3a9f8/crates/ty_module_resolver/src/resolve/search.rs#L43-L63)
recursively combines these listings, also following unresolved names to
discover local stub overrides. Salsa caches both the individual listings
and the complete recursive result.

This also adopts the new symlink enumeration policy described in
https://github.com/astral-sh/ruff/pull/28201.

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

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-09-28 09:00:30 -07:00
Lérè 730e84d9ee [ty] Add namespace-aware module enumeration (#28201)
## Summary

This adds (dormant) support for namespace-aware module enumeration that
reuses ordinary import resolution rules (to help ensure consistency and
correctness). https://github.com/astral-sh/ruff/pull/28202 uses this
capability to support namespace packages in auto-imports, missing-import
fixes, and import statement completions.

## Approach

The first two commits implement new Salsa queries that are necessary for
the new enumeration algorithm:

1. The first commit refactors the `ResolvedModule` enum to collapse the
`LegacyNamespacePackage` and `RegularPackage` variants into a single
`Package` variant. That new variant represents all packages that contain
initializers, deferring classification of that package until resolution
actually needs to make the distinction. Additionally,
`has_legacy_namespace_declaration` now caches the classification. This
makes the later Salsa queries that cache module listings less prone to
invalidation from irrelevant initializer changes.

2. The second commit introduces a `module_search_snapshot` query which
caches the candidates for a module name prefix (e.g., the prefix
"acme.tools" of the names "acme.tools.power" and "acme.tools.manual").
This avoids repeated resolution work for an ancestor (i.e., for
"acme.tools") that would otherwise occur across sibling modules (i.e.,
for "acme.tools.power" and "acme.tools.manual").

3. The last commit introduces `ModuleSearchCursor::list_modules`, which
collects distinct names from eligible directories and resolves each
through the existing resolver. As part of this change, we implement a
symlink policy that is designed to prevent cycles during recursive
enumeration: we allow symlinked search roots, but otherwise do not
discover names from directories whose relative path from a search root
crosses a symlink. This new policy formalizes our method for cycle
prevention; the code that it will replace also prevented cycles, but did
so in a way that does not appear to have been designed intentionally.

## Test Plan

See included tests.
2026-09-28 09:00:30 -07:00
Charlie Marsh 7d73e4b6da [ty] Cache the flattened module list (#28932)
## Summary

Repeated auto-import requests traverse and sort the same module tree. We
now cache the flattened, sorted module list per resolver environment,
and Salsa invalidates it when module listings change. The cache retains
one boxed list per environment.
2026-09-27 17:02:31 +00:00
Micha Reiser 226201fef0 [ty] Refresh Python settings when virtual environments change (#28650)
## Summary

This PR is a first step towards updating the project's uv metadata when
the virtual environment changes. The scope of this PR is to add the
non-uv specific virtual environment file watching. That is, it adds the
necessary file watching handling to update the detected virtual
environment and its Python version when:

* a `pyenv.cfg` changes
* the default `.venv` or the explicitly specified `environment.python`
virtual environment gets created or deleted.


Unfortunately, this does require storing the path to the resolved
virtual environment in `ProgramSettings`. Otherwise, we'd have to
resolve it every time we see a related file watcher event. It's
unfortunate because it doesn't feel like a setting. But there isn't
really any better to carry forward this information.


I recommend reviewing this PR commit by commit.


## Test Plan

Native file-watching regression tests pass.
2026-09-27 18:48:09 +02:00
Lérè 51f3437d03 [ty] Add a helper for configuring extra search paths to the builder for module resolution tests (#28923)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This makes it easier to configure extra search paths for module
resolution test cases.

## Test Plan

This is is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
2026-09-26 14:35:56 -07:00
Lérè 4976e2ef4d [ty] Share module snapshot formatting across resolver tests (#28921)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This moves `ModuleDebugSnapshot` to a central location where it can more
easily be shared across module resolver tests in the future.

## Test Plan

This is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
2026-09-26 13:41:21 -07:00
Lérè 8a38ca2b01 [ty] Rename module search traversal operation to advance (#28912)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
In response to feedback on https://github.com/astral-sh/ruff/pull/28201,
this renames the `enter_package` method from `ModuleSearchCursor` to
`advance`. I've factored it out from
https://github.com/astral-sh/ruff/pull/28201 to reduce noise from
trivial changes.

## Test Plan

This is a refactor that relies on existing test coverage.
<!-- How was it tested? -->
2026-09-25 14:27:48 -07:00
astral-automations-bot[bot]andBrent Westbrook 0be08a206f Bump version to 0.16.9 (#28882)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-09-24 16:21:50 -04:00
Micha Reiser 1771f6146f [ty] Skip legacy namespace parsing for __init__ files without pkg (#28665) 2026-09-17 16:15:39 +02:00
Lérè aeb51db2b8 [ty] Make module resolution reusable across sibling searches within a namespace package (#28199)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

Our approach to supporting auto-imports for namespace packages is to
make our module enumeration code namespace-aware. In order to do that
correctly, we need to refactor module resolution such that it is able to
resolve several children of the same package using ordinary import
resolution rules.

## Background

_What follows discusses context relevant to this particular PR. For more
background on namespace packages more generally, please see [this
document](https://gist.github.com/lerebear/399114b087d03c0860bf2cde0509e519)._

Consider enumerating modules for a namespace package named `acme`, which
is spread across two search roots:

```text
/project/src/                  /venv/site-packages/
└── acme/                      └── acme/
    └── reports.py                 ├── tools.py
                                   └── tools.pyi
```

The modules that are available for the namespace `acme` are
`acme.reports` and `acme.tools`, and the correct outcome of enumeration
of `acme` is to select `/project/src/acme/reports.py` and
`/venv/site-packages/acme/tools.pyi` as the files that provide the
symbols that are to be made available for auto-import for their
respective modules.

We already have a module resolver that implements that algorithm
correctly (and it's a complex algorithm, so we want to reuse it!), but
it is designed for resolution of a single, complete module name (i.e.,
`acme.reports`), rather than enumeration of several modules under a
common prefix (e.g., all modules under `acme`).

For instance, we can ask the current resolver to resolve `acme.reports`,
at which point it will:

1. List each search root looking for the name `acme`, and discover
`/project/src/acme/` and `/venv/site-packages/acme/`.
2. Probe each of those directories for an initializer (to determine
whether it is an ordinary package, or a namespace package). Upon
determining that both directories contribute to the same namespace
package, it will retain both directories for the rest of the search.
3. List each remaining candidate directory looking for the name
`reports`.

If we were to just use that same interface for enumeration, then
resolving `acme.tools` separately would repeat that traversal and
reconstruct the same set of candidate directories in order to look for
the name `tools`.

Instead, we want to establish all of that search state[^1] just once,
and reuse it for both children of `acme`. That way, we achieve our
primary goal of reusing the existing, correct implementation of module
resolution, and we also achieve our secondary goal of reducing
unnecessary work in a performance-sensitive operation.

[^1]: i.e., The directory names and associated listings described in the
numbered list above.

## Approach

This refactors our ordinary module resolution code (`resolve_name`) to
use a `ModuleSearch` abstraction internally. `ModuleSearch` is a cursor
that stores the search state of a module name prefix (e.g., `acme`) for
reuse during enumeration of all module name suffixes (i.e., `reports`
and `tools`). Hence we achieve our goal of reusing our existing module
resolution code for correctness, but making it more efficient for module
enumeration.

`ModuleSearch` works by providing an interface that describes traversal
of the components of the module name:

- `ModuleSearch::enter_package` (e.g.,
`ModuleSearch::enter_package("acme")`) returns search state for
resolving descendants of `acme`.
- `ModuleSearch::resolve_child` (e.g.,
`ModuleSearch::resolve_child("tools")`) selects the module candidates
for `acme.tools` while leaving the `ModuleSearch` object reusable for
another child.

The [next PR in this
stack](https://github.com/astral-sh/ruff/pull/28201) will build on this
foundation to implement namespace-aware module enumeration.

## Test Plan

This is primarily a behaviour-preserving refactor that relies on
existing tests, but it also includes new tests for new functionality
that we will build on in subsequent PRs.
2026-09-16 23:25:21 -07:00
astral-automations-bot[bot]andBrent Westbrook 62914c4b9b Bump version to 0.16.8 (#28648)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-09-16 11:31:02 -04:00
Lérè c2cd236b9c [ty] Improve clarity of some module resolution terminology and docs (#28593)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This makes a few small changes to some names and comments to improve
clarity. It was factored out from
https://github.com/astral-sh/ruff/pull/28199 to improve the
signal-to-noise ratio for that PR (which will receive a proper review).

## Test Plan

This is a refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-14 14:45:19 -07:00
Lérè d84df49686 [ty] Refactor "desperate" import resolution to use candidate operations that will also apply to module enumeration. (#28543)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It refactors
the `desperately_resolve_name` method (used for ordinary module
resolution) to use methods of `NameResolver` that can be shared with
module enumeration.

## Test Plan

This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-11 21:08:05 -07:00
Lérè 53d4331ddf [ty] Extract a method on NameResolver to advance resolution by single module name component. (#28540)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It factors
out a helper method (`NameResolver::advance_candidates`) for a small
part of the ordinary module resolution process such that it can more
easily be reused for module enumeration in the future.

## Test Plan

This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-11 14:54:49 -07:00
Lérè ce794431a4 [ty] Return root discovery to NameResolver, but retain necessary interface changes (#28536)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
https://github.com/astral-sh/ruff/pull/28531 incorrectly went a bit too
far in turning `NameResolver::discover_roots` into a free function. That
isn't actually necessary for the refactor we're aiming for; we just need
to widen its interface to accept new arguments that allows it to apply
to new contexts. This restores the private method but retains the wider
interface.

## Test Plan

This is a behaviour-preserving refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-11 14:20:03 -07:00
Lérè 35a3ed13e1 [ty] Extract module root discovery from NameResolver. (#28531)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This is a small step towards the [larger
refactor](https://github.com/astral-sh/ruff/pull/28199) that will allow
us to share ordinary module resolution rules with the module enumeration
process required to [support namespace packages for auto
imports](https://github.com/astral-sh/ty/issues/2273) (please see that
refactor PR for a detailed description of our motivations). It refactors
the previously associated `NameResolver::discover_roots` method into a
free function, such that it can more easily be reused for both ordinary
module resolution and module enumeration.

## Test Plan

This is a pure refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-11 13:24:51 -07:00
Lérè 6c8eb98a02 [ty] Retain package listings between resolution steps (#28278)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

This retains directory listings between successive steps of module
resolution, using the `ModuleDirectory` abstraction introduced in
[#28418](https://github.com/astral-sh/ruff/pull/28418).

For example, when resolving `acme.tools`:

```text
acme/
├── __init__.py
└── tools.py
```

Resolving `acme` retrieves its directory listing to find `__init__.py`.
Resolving the next component, `tools`, needs that same listing.
Previously, each resolution candidate retained only the directory’s
path, so the next step reconstructed a `ModuleDirectory` and retrieved
the listing again.

Candidates now retain the `ModuleDirectory` itself, preserving both its
path and its listing, so the resolution for `acme` and `acme.tools` can
both reuse the directory listing for `acme/`. Note that directory
listings are already cached with Salsa, but this avoids repeated cache
retrieval and the path construction needed to perform that retrieval.
Resolution rules remain unchanged.

Downstream, retaining these listings will also allow namespace-package
enumeration to discover child names and resolve them using the same
directory information, as part of [namespace-package auto-import
support](https://github.com/astral-sh/ty/issues/2273).

## Test Plan

This is a behaviour-preserving refactor that relies on existing tests.
<!-- How was it tested? -->
2026-09-10 14:26:05 -07:00
Lérè 3770a96ff9 [ty] Refactor module resolution to use a ModuleDirectory abstraction. (#28418)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->

This refactors our module resolution code in order to introduce a
`ModuleDirectory` abstraction. The purpose of that new abstraction is to
make it easier to reuse a single directory listing to resolve _multiple_
modules, as is required for the symbol enumeration that will power
[namespace package import
completions](https://github.com/astral-sh/ty/issues/2273). For more
background on this problem, please see [this
document](https://gist.github.com/lerebear/399114b087d03c0860bf2cde0509e519).

Downstream, this new abstraction allows for the following improvements
that continue building towards symbol enumeration that supports
namespace packages:

1. A [quick performance
optimization](https://github.com/astral-sh/ruff/pull/28419) that
immediately benefits ordinary module resolution, and hence will also
benefit symbol enumeration once it shares ordinary module resolution
code.
2. The [ability to retain directory listings across resolution
steps](https://github.com/astral-sh/ruff/pull/28278), so that we
maintain efficiency while considering all of the directories that might
contribute to a namespace package.

## Motivation

Consider trying to provide the import completion `from acme.reports
import Report` for `x = Re<CURSOR>` given the following namespace
package layout:

```text
/project/src/acme
└── reports.py        # defines `Report`
```
```text
/venv/site-packages/acme/
├── tools.py          # defines `Tool` and `ImplementationDetail`
└── tools.pyi         # exposes only `Tool` to type checkers
```

In order to discover the `Report` symbol, we must enumerate _all_
symbols exposed by the `acme`. That requires us to must first enumerate
all of `acme`'s module names (i.e. `acme.reports` and `acme.tools`), and
then to resolve each of those names to determine which file actually
exposes the relevant symbols (for `acme.tools` there are two choices,
but the correct one for the purposes of import suggestions is
`tools.pyi`).

Enumerating `acme`'s module names requires us to retrieve directory
listings for `/project/src/acme` and `/venv/site-packages/acme/`.
Subsequently, resolving the name `acme.tools` requires consulting _those
same directory listings_ in order to answer the following questions that
determine the outcome of the module resolution process:

1. Does `/project/src/acme` contain an entry named `tools`? (No.)
2. Does `/venv/site-packages/acme/` contain an ordinary package named
`tools`? (No.)
3. Does `/venv/site-packages/acme/` contain only a runtime module
(`tools.py`) or does it also contain a stub (`tools.pyi`)? (Both.)

So it would be useful to be able to reuse the directory listings from
the enumeration process for the module resolution process.

As a first step towards that vision, this introduces a `ModuleDirectory`
struct, which encapsulates the (1) path to a directory that participates
in module resolution, (2) its directory listing as retrieved from the
filesystem, (3) the existing validations for resolving an exact filename
within that directory.

## Approach

I defined a new [`ModuleDirectory`
struct](https://github.com/astral-sh/ruff/blob/304661fb5d0a6539585b9dd75df74231a6dc9bc8/crates/ty_module_resolver/src/path.rs#L331-L338),
and replaced previous calls to
[`ModulePath::to_file`](https://github.com/astral-sh/ruff/blob/77f653825800ddaf3bc221ae6db49a500e1002d5/crates/ty_module_resolver/src/path.rs#L229-L230)
with calls to
[`ModuleDirectory::resolve_file`](https://github.com/astral-sh/ruff/blob/304661fb5d0a6539585b9dd75df74231a6dc9bc8/crates/ty_module_resolver/src/path.rs#L382-L384).
That new method implements the same checks that were previously spread
across several methods (please see inline comments).

`ModuleDirectory` also provides a few more convenience methods that
should be self-explanatory.

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-09-10 12:54:59 -07:00
astral-automations-bot[bot]andBrent Westbrook b5dba861cc Bump version to 0.16.7 (#28496)
Co-authored-by: astral-automations-bot[bot] <305554984+astral-automations-bot[bot]@users.noreply.github.com>
Co-authored-by: Brent Westbrook <36778786+ntBre@users.noreply.github.com>
2026-09-10 13:47:30 -04:00
Lérè 930a6965c4 [ty] Add a shared model for pytest test collection (#27973)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

As previewed in
https://github.com/astral-sh/ruff/pull/27834#discussion_r3833665878,
this introduces a semantic model of the tests that pytest recognizes in
a particular file or for a particular candidate function. This model
will ultimately be shared by several features (e.g.,
https://github.com/astral-sh/ty/issues/4119 and
https://github.com/astral-sh/ty/issues/4041), and it is [immediately
integrated into our semantic model for pytest
fixtures](https://github.com/astral-sh/ruff/pull/27974) (which powers
"Go to definition" and "Find references" in the language server).

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-09-03 21:48:10 -07:00
Brent Westbrook 22f65a2ab5 Bump 0.16.6 (#28280) 2026-09-03 12:36:42 -04:00
Zsolt Dollenstein f4839591d6 [ty] Add a missing-direct-dependency rule (#28001)
This PR replaces #25027. It adds an opt-in check for imports of
installed distributions that the current project does not declare
directly in `pyproject.toml`.

## Overview

The check uses ty's existing uv workspace integration (`TY_UV=1`) to
call `uv workspace metadata --frozen --active`. uv now provides module
ownership without synchronizing the environment, so ty can read the
metadata without installing packages or updating `uv.lock`.

The metadata provides:

1. Each workspace project's runtime and optional dependencies.
2. Dependencies declared in dependency groups.
3. Importable modules and their owning distributions, including source
paths for editable installs.

During import inference, ty maps each resolved import to its
distribution and compares it against the importing project's direct
declarations. If the declaration is missing, ty emits
`missing-direct-dependency`, naming the distribution to add. Each
distribution is reported once per file, at its first unsuppressed
import.

The rule is disabled by default and requires an existing, synchronized
environment. Unavailable or incompatible dependency metadata disables
the check; rejected dependency metadata produces a debug message.

## Nuances

- Editable installs may lack entries in uv's module-owner map. ty uses
their source paths to attribute resolved imports.
- Files identified as package code require runtime or optional
dependencies. Non-package files, such as tests and scripts, can also use
dependency groups, but those groups' transitive dependencies still need
direct declarations.
- For `from package import child`, a resolved child module is checked
against its own distribution rather than the parent's. Imports with
unknown or ambiguous ownership are skipped.
- Ownership metadata is used only when the explicitly selected Python
environment matches uv's environment.
- The current integration covers directory checks. Explicit file
arguments, `--config-file`, and standalone PEP 723 scripts do not use
the workspace's dependency declarations.

The schema and rule documentation are regenerated. Most of the
rule-documentation diff consists of updated source-line links.
2026-08-28 14:01:44 +00:00
Brent Westbrook 9e4938c4a6 Bump 0.16.5 (#28110) 2026-08-27 12:09:07 -04:00
Charlie Marsh 50a3eae8ee Run Hawk in CI (#27372)
## Summary

We now run Hawk 0.1.13 with Rust 1.98.0 in CI, following the pattern
used by uv. The configuration preserves intentional public APIs and
generated interfaces while checking all configured production binaries
and workspace non-production targets with `-D warnings`.

The accompanying cleanup narrows internal visibility, removes unused
benchmark classification state and accessors, and records intentional
public interfaces as audited Hawk expectations. The resulting
configuration reports zero Hawk findings across the configured targets.
2026-08-26 13:51:16 -06:00
Lérè cc932fa706 [ty] Resolve installed core pytest fixture providers (#27770)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This extends the pytest fixture model from
https://github.com/astral-sh/ruff/pull/27540 to resolve fixtures
supplied by pytest's [built-in
plugins](https://docs.pytest.org/en/stable/reference/fixtures.html).
Pytest makes these fixtures available without an import or a local
`conftest.py`, so ty currently cannot connect requests such as
`tmp_path` or `monkeypatch` to their declarations.

ty now reads the statically known `default_plugins` registration from
the installed `_pytest.config`, resolves those plugins from the same
pytest installation, and searches them in pytest's precedence order
after project providers. This preserves local fixture shadowing and also
models the dynamic `LegacyTmpdirPlugin` registration that supplies the
legacy `tmpdir` fixtures. Registries that cannot be determined
statically remain unresolved.

This implementation intentionally supports pytest 8.x and newer; earlier
pytest versions are outside the supported scope.

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-08-25 15:10:27 -07:00
Lérè 39ca6160b4 [ty] Resolve pytest fixtures through conftest (#27540)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
This extends the model originally introduced in
https://github.com/astral-sh/ruff/pull/27443 to support resolving pytest
fixtures defined in a [hierarchy of `conftest.py`
files](https://docs.pytest.org/en/stable/reference/fixtures.html#conftest-py-sharing-fixtures-across-multiple-files).

These changes remain unused until
https://github.com/astral-sh/ruff/pull/27444.

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-08-25 13:49:59 -07:00
Lérè 9459dc024d [ty] Resolve imported pytest fixture exposures (#27539)
<!--
Thank you for contributing to Ruff/ty! To help us out with reviewing,
please consider the following:

- Does this pull request include a summary of the change? (See below.)
- Does this pull request include a descriptive title? (Please prefix
with `[ty]` for ty pull
  requests.)
- Does this pull request include references to any relevant issues?
- Does this PR follow our AI policy
(https://github.com/astral-sh/.github/blob/main/AI_POLICY.md)?
-->

## Summary

<!-- What's the purpose of the change? What does it do, and why? -->
Building on https://github.com/astral-sh/ruff/pull/27443, this extends
the model for recognizing the pytest fixture bound to a test parameter
to support imported fixtures (as opposed to only fixtures defined in
that same module). Specifically, we now attempt to traverse recursively
through the local name bound by an import to find an underlying pytest
fixture.

The entire semantic model in `pytest.rs` remains unused until
https://github.com/astral-sh/ruff/pull/27444.

## Approach

The implementation proceeds in three stages:

1. (4fcaf2af93) Introduces a new interface
for resolving the bindings that supply a module global in a way that
respects control flow and shadowing. This is general infrastructure,
hence its centralization (it will be used again in
[#26677](https://github.com/astral-sh/ruff/pull/26677) towards
[astral-sh/ty#1560](https://github.com/astral-sh/ty/issues/1560) and
[astral-sh/ty#3410](https://github.com/astral-sh/ty/issues/3410)), but
it is immediately necessary here for correct import resolution.
2. (3056c8c6e9f5cbb60d5261aa75ae1538dc1ebb44) Implements a small
refactor to make a loop clearer.
3. (a1f9f6b1c24a81fae821d5557e63b644c5186c0c) Implements the actual
fixture import resolution logic.

## Test Plan

See included tests.
<!-- How was it tested? -->
2026-08-25 12:35:41 -07:00