[ty] Reuse the builder state when extending wide intersections #30769
<!-- generated-comment typing-conformance -->
<!-- report-run:47439410527:1 -->
Typing conformance results
No changes detected ✅
<details>
<summary>Current numbers</summary>
<br>
The percentage of diagnostics emitted that were expected errors held steady at <b>98.60%</b>. The percentage of expected errors that received a diagnostic held steady at <b>98.86%</b>. The number of fully passing files held steady at <b>137/146</b>.
</details>
---
Results for ebd5904 · Workflow run
<!-- generated-comment memory -->
<!-- report-run:47439410466:1 -->
Memory usage report
Memory usage unchanged ✅
---
Results for ebd5904 · Workflow run
<!-- generated-comment ty-ecosystem -->
<!-- report-run:47439410440:1 -->
ecosystem-analyzer results
No diagnostic changes detected ✅
Large timing changes:
| Project | Old Time | New Time | Change |
|---------|---------:|---------:|-------:|
| python-sop | 0.08s | 0.04s | -53% |
Full report with detailed diff · Timing results
---
Results for ebd5904 · Workflow run
<!-- __CODSPEED_PERFORMANCE_REPORT_COMMENT__ -->
Merging this PR will improve performance by 17.71%
<details>
<summary><b>1 warning</b></summary>
:warning: 5 benchmarks with a significant change ran on different hardware
> Their base and head results were measured on machines with a different CPU, core count or memory, so the changes might not come from the code. Run base and head on the same runner type.
> Learn more about Macro Runners
> See affected benchmarks
</details>
⚡ 7 improved benchmarks ✅ 458 untouched benchmarks 🆕 8 new benchmarks ⏩ 16 skipped benchmarks[^skipped]
Performance Changes
| | Mode | Benchmark | BASE | HEAD | Efficiency |
| --- | ---- | --------- | ------ | ------ | ---------- |
| ⚡ | CPU Simulation | [` ty_micro[large_isinstance_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_large_isinstance_narrowing%3A%3Aty_micro%255Blarge_isinstance_narrowing%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 151.9 ms | 109 ms | +39.3% |
| ⚡ | Memory | [ ty_micro[large_isinstance_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_large_isinstance_narrowing%3A%3Aty_micro%255Blarge_isinstance_narrowing%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 5.9 MB | 4.6 MB | +28.56% |
| ⚡ | CPU Simulation | [ ty_micro[large_union_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_large_union_narrowing%3A%3Aty_micro%255Blarge_union_narrowing%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 177.2 ms | 148.6 ms | +19.19% |
| ⚡ | CPU Simulation | [ ty_micro[enum_or_pattern_exhaustiveness_400] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_enum_or_pattern_exhaustiveness%3A%3Aty_micro%255Benum_or_pattern_exhaustiveness_400%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 191.9 ms | 161.1 ms | +19.09% |
| ⚡ | CPU Simulation | [ ty_micro[many_enum_members_2] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_many_enum_members_2%3A%3Aty_micro%255Bmany_enum_members_2%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 122.4 ms | 109.9 ms | +11.41% |
| ⚡ | CPU Simulation | [ ty_micro[enum_or_pattern_exhaustiveness_200] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_enum_or_pattern_exhaustiveness%3A%3Aty_micro%255Benum_or_pattern_exhaustiveness_200%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 130 ms | 122.3 ms | +6.25% |
| ⚡ | Memory | [ ty_micro[large_union_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_large_union_narrowing%3A%3Aty_micro%255Blarge_union_narrowing%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | 5.6 MB | 5.4 MB | +4.03% |
| 🆕 | CPU Simulation | [ ty_micro[isinstance_self_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_isinstance_self_narrowing%3A%3Aty_micro%255Bisinstance_self_narrowing%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 320.8 ms | N/A |
| 🆕 | CPU Simulation | [ ty_micro[replacing_class_exclusions] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_replacing_class_exclusions%3A%3Aty_micro%255Breplacing_class_exclusions%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 3.2 s | N/A |
| 🆕 | CPU Simulation | [ ty_micro[class_pattern_fallthrough] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_class_pattern_fallthrough%3A%3Aty_micro%255Bclass_pattern_fallthrough%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 146.5 ms | N/A |
| 🆕 | CPU Simulation | [ ty_micro[generic_class_pattern_fallthrough] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_generic_class_pattern_fallthrough%3A%3Aty_micro%255Bgeneric_class_pattern_fallthrough%255D&runnerMode=Simulation&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 193.2 ms | N/A |
| 🆕 | Memory | [ ty_micro[class_pattern_fallthrough] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_class_pattern_fallthrough%3A%3Aty_micro%255Bclass_pattern_fallthrough%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 4.9 MB | N/A |
| 🆕 | Memory | [ ty_micro[isinstance_self_narrowing] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_isinstance_self_narrowing%3A%3Aty_micro%255Bisinstance_self_narrowing%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 6.7 MB | N/A |
| 🆕 | Memory | [ ty_micro[generic_class_pattern_fallthrough] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_generic_class_pattern_fallthrough%3A%3Aty_micro%255Bgeneric_class_pattern_fallthrough%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 5.5 MB | N/A |
| 🆕 | Memory | [ ty_micro[replacing_class_exclusions] ](https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?uri=crates%2Fruff_benchmark%2Fbenches%2Fty.rs%3A%3Amicro%3A%3Abenchmark_replacing_class_exclusions%3A%3Aty_micro%255Breplacing_class_exclusions%255D&runnerMode=Memory&utm_source=github&utm_medium=comment-v2&utm_content=benchmark) | N/A | 7.5 MB | N/A |
[!TIP]
Curious why performance improved? Comment @codspeedbot explain why performance improved` on this PR, or directly use the CodSpeed MCP with your agent.
---
<sub>Comparing <code>charlie/resume-intersections</code> (ebd5904) with <code>main</code> (7ba8028)</sub>
<a href="https://app.codspeed.io/astral-sh/ruff/branches/charlie%2Fresume-intersections?utm_source=github&utm_medium=comment-v2&utm_content=button">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codspeed.io/pr-report/open-in-codspeed-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codspeed.io/pr-report/open-in-codspeed-light.svg">
<img alt="Open in CodSpeed" src="https://codspeed.io/pr-report/open-in-codspeed-light.svg" width="169" height="32">
</picture>
</a>
[^skipped]: 16 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.
Codex finding for potential followup:
<details>
I found a case where we save a lot of memory here but get slower. If we dispatch on self, expand_intersection_typevars_and_newtypes replaces Self with its bound and adds the exclusions one at a time. So we still visit every pair at every step, and now we walk both MROs each time, outside the cached pair comparison. Inheriting from list[int] makes this particularly noticeable.
I reproduced it by checking the output of this generator with a Python 3.13 target.
# /// script
# dependencies = []
# ///
print("class Base(list[int]):")
print(" def dispatch(self) -> int:")
for i in range(200):
print(f" if isinstance(self, C{i}): return {i}")
print(" return -1")
for i in range(200):
print(f"class C{i}(Base): ...")
Could we reuse the comparisons between exclusions when expanding the bound? I think this could also be a follow-up. We can keep it pretty narrow. Alongside try_add_literal_exclusions, if we have a single nominal positive, no existing negatives, and at least 16 nominal exclusions, we could do the following.
1. Call replay_exclusions with just the exclusions and check only_appended.
2. Check that simplify_intersection_pair returns Unchanged for each exclusion paired with the expanded positive (Mixed).
3. If both checks pass, just do inner.negative = exclusions.clone(). Otherwise fall back to adding them individually.
That lets us share the chunks without interning a new input for each possible bound.
In an experiment on this example, median CPU time was 18.8s on the parent, 22.3s here, and 7.5s with the above change. Retained Salsa memory went from 111 MiB to 8.4 MiB to 7.2 MiB respectively. The timings are from three interleaved runs per version on Linux, with one worker and an unoptimized dev build. Memory was measured separately. I'd be inclined to add a microbenchmark for this case.
</details>
If only_appended is true, can we just use input here? That should also save hashing the whole intersection again.
Otherwise, could we shrink the sets before interning them, as we do in InnerIntersectionBuilder::build? If a later exclusion subsumes most of a wide prefix, we can end up keeping a large allocation for very few elements. Once the interned state shares the Arc, the shrink in build can't reclaim that space.
Could we also copy the exclusions directly for the common enum case, e.g. Color & ~Color.RED & ~Color.BLUE? known_class() returns None for enum literals, so we still rebuild the set here and can end up throwing it away in favor of exclusions.clone(). We've already checked that all the exclusions come from the same enum. If its instance is the sole positive, checking the first member's enum class against that positive should suffice.
Could we mirror this one in the legacy variables mdtests too? I tried it with T = TypeVar("T", default="Child.Other"), U = TypeVar("U", default="Root"), Root(Generic[T]) and Child(Root[U]). We get the same revealed type and recognize that the narrowing is exhaustive there too.
Not necessarily any action needed, but just noting that this PR seems to add a bunch of tests with negated typevar defaults, which seems unlikely to be a case that ever occurs in any real-world code today. How do these tests map to / originate from a real-world concern that is core to this PR? Or do they not really relate, but Codex just happened to notice a regression from this PR's main change, fix it, and then add a regression test? Is there a way we could test the same thing with a less contrived example? (If not, I'm fine adding these too.)
Nice! This is independently a cool improvement, that we can avoid creating a new specialization just as a cycle initial that we then will almost certainly throw away.
Can we make this comment more clearly explain the contract of just this method? Right now it's kind of explaining the caller's related logic, more than what this method actually does.
Do these three assertions need to be full assertions rather than debug assertions?
Could we avoid most of the replay machinery by initializing an empty builder directly from the existing IntersectionType? In the example from the PR description, by the time we have Base & ~A & ~B, we've already simplified those three against each other. I'd expect adding ~C to only require comparisons involving C. Even when we expand Self, we need to check the exclusions against the new bound, but can we reuse what we know about the exclusions relative to each other?
I had Codex try copying both sets into an empty builder regardless of size and all 882 mdtests passed. I see a couple of caveats.
Structural substitution can intern an intersection without simplifying the substituted elements. Could we handle those cases separately and make it an invariant that ordinary intersections have already been simplified?
Even for builder-produced intersections, simplification isn't quite idempotent today. Codex found this example (adding 13 unrelated exclusions gives the same result above the threshold here).
from typing import Any, reveal_type
from ty_extensions import Intersection, Not
class Child(list[Any]): ...
def f(x: Intersection[Not[bool], Not[list[Any]], Not[Child], Not[int]]):
reveal_type(x) # ~Child & ~list[Any] & ~int
if isinstance(x, Child):
reveal_type(x) # Child & ~list[Any] today, Never with copying
Removing ~bool swaps ~Child ahead of ~list[Any]. We use different redundancy checks in the two directions, so replay drops ~Child. Here copying actually seems preferable to me. We should probably address the order dependence separately.
Thanks!
This is test code, I think the full assertions is right, no?
Oh sorry, I totally missed that this was in a test! Ignore.
This is a really interesting idea. I will probably merge this to unblock while I explore in https://github.com/astral-sh/ruff/pull/31515.
carljm
charliermarsh
Summary
Each failed
isinstancecheck can rule out another class. For example, ifA,B, andCare unrelated subclasses ofBase, ty can narrowxlike this.To rule out
C, ty first rebuildsBase & ~A & ~Band checks whether excludingAalready rules outB. We repeat that check for every subsequent branch.We already handle built-in literal exclusions together (#30736 and #30767). We can do the same for members of one enum when their literal flags match. Enum complements list members in declaration order, so ruling them out in reverse order would otherwise give us a new set of prefixes at every step.
For other intersections with at least 16 exclusions, we cache the builder’s ordered positive and negative elements. Successive exclusions can share chunks of storage. When we start with the same positives and no exclusions, we can resume from the last shared chunk boundary, even if the builder removed or replaced an element. For a flat set, we cache the result of applying the whole set. Splitting it would copy and retain prefixes we might never reuse.
If
xis a union, several branches can have the same exclusions. For example,A & ~C & ~DandB & ~C & ~Dboth need to know whether~Cmakes~Dredundant. The builder records whether each insertion simply appended its input. If all the exclusions append when tried on their own, we can share those comparisons across branches. We still check each exclusion against the positives, and resume pairwise comparisons as soon as a branch changes what gets inserted.The same comparisons come up when we narrow
self. ExpandingSelf & ~A & ~BtoBase & ~A & ~Bmeans we have to checkAandBagainstBaseagain. We can reuse the comparison betweenAandB. If neither exclusion simplifies against the bound, we can also keep the original storage.Closes astral-sh/ty#5227.
Test plan
On the 200-subclass example that dispatches on
self, reusing the comparisons when expandingSelfreduced median CPU time from 10.6 s to 3.4 s relative to the earlier version of this PR. I ran each version three times with one worker in the mdtest harness targeting Python 3.13.I ran the
isinstanceexample from astral-sh/ty#5227 withx: objectagainst main at e88203b8bd.| Classes | Query metadata on main | This PR | Total Salsa on main | This PR |
| ---: | ---: | ---: | ---: | ---: |
| 250 | 25.5 MiB | 0.9 MiB | 41.2 MiB | 5.7 MiB |
| 500 | 191.2 MiB | 2.7 MiB | 241.5 MiB | 8.5 MiB |
| 1,000 | 1,476.6 MiB | 9.1 MiB | 1,663.4 MiB | 17.1 MiB |