ty rejected `partial(decorator, option=value)` when the decorator
accepted and returned `Callable[P, str]`. It reported that `P.args` was
incompatible with itself. With this change, binding the option leaves
the decorator free to capture the decorated function’s signature.
The solver tracked `P.args` and `P.kwargs` separately and could overlook
the dependency on `P` when removing the decorator’s local type variables
from a constraint. Record that dependency explicitly. For a specialized
return-type alias, visit the arguments that affect the alias’s value so
the solver can substitute the caller’s parameter list there too.
Fixes astral-sh/ty#4973.
## Test plan
Bisected the reported example to #29543 and checked the fix against the
same example. ty now infers `(name: str) -> str` for the decorated
function. I also compared the semantic mdtests under eight alternate
constraint orderings with the base revision. Each ordering produced the
same failing assertions and diagnostics on both revisions.
## Ecosystem report
At `a3e66405a2b5c4b9062803edbed4ddd45ab2c074`, all seven diagnostic
changes were expected. Five Normal and Uniform property assertions and
two Binomial property assertions now infer the one-dimensional arrays
specified by scipy-stubs, with the correct dtypes. The ecosystem
comparison is clear for review. [Full
report](https://github.com/astral-sh/ruff/pull/30150#issuecomment-6702172316)
The gradual range `T <: Any` does not imply the static range `T <: int`,
as `Any` permits materializations that `int` does not satisfy. We
currently assume this implication in the sequent map, as our
transitivity checks use assignability instead of subtyping. However,
this permits unsound simplifications which can lead to incorrect
inference results.
This PR makes a rather large change to how we represent the individual
constraints in a constraint set.
Before, we had a single `Constraint` struct, and assumed that every
individual constraint was a single _range constraint_, which provided a
lower and upper bound for a typevar. Several open workstreams want to
add new kinds of individual constraint. (@ibraheemdev is adding a new
constraint that checks certain gradual bounds; @dcreager is adding a new
constraint that models existentials moar better; @dhruvmanila might need
a new constraint for `ParamSpec`s.)
So, in anticipation of that work, we go ahead and break `Constraint`
apart into an enum, that we can add new variants to in the future. While
we're here, we also move it into a separate submodule to tame the
runaway growth of `constraints.rs`.
We are not adding a single-variant enum. Instead, we have added separate
variants for the different kinds of range constraint that can appear.
Most important, we've broken it apart into separate variants for
only-lower-bound, only-upper-bound, and equivalence bound. That lets us
treat equivalences as a first-class concept, since those are important
to track e.g. for handling the declared constraints of a constrained
typevar. And it gives us an efficiency game in some places, where we had
O(L) lower bounds and O(U) upper bounds, and were having to calculate
O(L×U) different derived sequents from all combinations of those bounds.
We also add separate variants for a "typevar constraint", where one
typevar is being compared directly to another. (So, `T ≤ U`, but not `T
≤ list[U]`.) Those were special-cased in a couple of places, and most
importantly, had an internal representation in `ConstraintSetBuilder`
that was hard to make deterministic. The new representation makes it
easier to identify those special cases, and comes with a deterministic
ordering for free (at least for typevar _range_ constraints).
Given those preliminaries, we also update `SequentMap` so that we
calculate derived sequents globally, outside of any particular
`ConstraintSetBuilder`, and salsa-cache them. That gives us a
performance for certain ecosystem projects, which repeatedly make
comparisons involving complex protocols and `TypedDict` aliases. (Those
are expensive to analyze, and this lets us do that once globally and
share the results across all constraint set solves that use them.)
## Summary
When matching a class object against a protocol, we previously treated
any `property` descriptor as an unconditional match for a protocol
property. This reduced compatibility to a name-only check even though
accessing an instance property on the class exposes the descriptor, not
the value returned by its getter:
```py
class HasValue(Protocol):
@property
def value(self) -> str: ...
class Value:
@property
def value(self) -> str: ...
target: HasValue = Value # error
```
This removes the stale shortcut so the class attribute and protocol
member are compared using the normal type relation.
That shortcut also interfered with generic inference for unions, like in
NumPy's `_DTypeLike[T]`, where it allowed a scalar class such as
`np.int64` to match `_SupportsDType[dtype[T]]` without constraining `T`,
overriding the useful `type[T]` match and producing `Unknown`. With
normal property compatibility, the class-object branch binds `T`, so
explicit dtypes remain specialized through downstream calls:
```py
values = np.array([0, 1, 2], dtype=np.int64)
reveal_type(values) # ndarray[..., dtype[signedinteger[_64Bit]]]
reveal_type(np.interp(values, values, values)) # ndarray[..., dtype[float64]]
```
Closes https://github.com/astral-sh/ty/issues/3199.
## Summary
This PR adds the possibility to write mdtests that specify external
dependencies in a `project` section of TOML blocks. For example, here is
a test that makes sure that we understand Pydantic's dataclass-transform
setup:
````markdown
```toml
[environment]
python-version = "3.12"
python-platform = "linux"
[project]
dependencies = ["pydantic==2.12.2"]
```
```py
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
user = User(id=1, name="Alice")
reveal_type(user.id) # revealed: int
reveal_type(user.name) # revealed: str
# error: [missing-argument] "No argument provided for required parameter
`name`"
invalid_user = User(id=2)
```
````
## How?
Using the `python-version` and the `dependencies` fields from the
Markdown section, we generate a `pyproject.toml` file, write it to a
temporary directory, and use `uv sync` to install the dependencies into
a virtual environment. We then copy the Python source files from that
venv's `site-packages` folder to a corresponding directory structure in
the in-memory filesystem. Finally, we configure the search paths
accordingly, and run the mdtest as usual.
I fully understand that there are valid concerns here:
* Doesn't this require network access? (yes, it does)
* Is this fast enough? (`uv` caching makes this almost unnoticeable,
actually)
* Is this deterministic? ~~(probably not, package resolution can depend
on the platform you're on)~~ (yes, hopefully)
For this reason, this first version is opt-in, locally. ~~We don't even
run these tests in CI (even though they worked fine in a previous
iteration of this PR).~~ You need to set `MDTEST_EXTERNAL=1`, or use the
new `-e/--enable-external` command line option of the `mdtest.py`
runner. For example:
```bash
# Skip mdtests with external dependencies (default):
uv run crates/ty_python_semantic/mdtest.py
# Run all mdtests, including those with external dependencies:
uv run crates/ty_python_semantic/mdtest.py -e
# Only run the `pydantic` tests. Use `-e` to make sure it is not skipped:
uv run crates/ty_python_semantic/mdtest.py -e pydantic
```
## Why?
I believe that this can be a useful addition to our testing strategy,
which lies somewhere between ecosystem tests and normal mdtests.
Ecosystem tests cover much more code, but they have the disadvantage
that we only see second- or third-order effects via diagnostic diffs. If
we unexpectedly gain or lose type coverage somewhere, we might not even
notice (assuming the gradual guarantee holds, and ecosystem code is
mostly correct). Another disadvantage of ecosystem checks is that they
only test checked-in code that is usually correct. However, we also want
to test what happens on wrong code, like the code that is momentarily
written in an editor, before fixing it. On the other end of the spectrum
we have normal mdtests, which have the disadvantage that they do not
reflect the reality of complex real-world code. We experience this
whenever we're surprised by an ecosystem report on a PR.
That said, these tests should not be seen as a replacement for either of
these things. For example, we should still strive to write detailed
self-contained mdtests for user-reported issues. But we might use this
new layer for regression tests, or simply as a debugging tool. It can
also serve as a tool to document our support for popular third-party
libraries.
## Test Plan
* I've been locally using this for a couple of weeks now.
* `uv run crates/ty_python_semantic/mdtest.py -e`