← Back to Pull requests

[ty] Reuse the builder state when extending wide intersections #30769

Merged
charliermarsh merged 10 files (820 lines) on Dec 04, 2026 22:42 UTC
View on GitHub
charliermarsh charliermarsh commented on Nov 22, 2026 21:09 UTC
Author

Summary

Each failed isinstance check can rule out another class. For example, if A, B, and C are unrelated subclasses of Base, ty can narrow x like this.

def dispatch(x: Base):
    if isinstance(x, A):
        return
    if isinstance(x, B):
        return
    if isinstance(x, C):
        return
    reveal_type(x)  # Base & ~A & ~B & ~C

To rule out C, ty first rebuilds Base & ~A & ~B and checks whether excluding A already rules out B. 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 x is a union, several branches can have the same exclusions. For example, A & ~C & ~D and B & ~C & ~D both need to know whether ~C makes ~D redundant. 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. Expanding Self & ~A & ~B to Base & ~A & ~B means we have to check A and B against Base again. We can reuse the comparison between A and B. 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 expanding Self reduced 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 isinstance example from astral-sh/ty#5227 with x: object against 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 |

Diff: 820 lines (+682 / -138) across 10 files Reviewer: carljm Review duration: 17372m
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.56) × (1 − Review Confidence (0.92)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.56 · 820 lines diff across 10 files
0.56
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.92 · 5 substantive comment(s)
0.92
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
91%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
18 items
astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 22, 2026 21:12 UTC
Bot

<!-- 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

astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 22, 2026 21:14 UTC
Bot

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

Memory usage report

Memory usage unchanged ✅

---

Results for ebd5904 · Workflow run

astral-automations-bot[bot] astral-automations-bot[bot] commented on Nov 22, 2026 21:15 UTC
Bot

<!-- 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[bot] codspeed[bot] commented on Nov 22, 2026 21:29 UTC
Bot

<!-- __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.

carljm carljm commented on code on Dec 04, 2026 19:40 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -2260,6 +2280,20 @@ fn simplify_intersection_pair<'db>(
         };
     }
 
+    // Neither exclusion can subsume the other if neither class inherits from the
+    // other. Check this before interning a pair for every two classes in a chain.
+    // Unrelated classes can still overlap through multiple inheritance.
+    if matches!(polarity, IntersectionPolarity::Negative)
+        && let (Type::NominalInstance(left), Type::NominalInstance(right)) = (first, second)
+        // Looking up the unspecialized MRO of a generic class can force a type
+        // parameter default that is still being inferred.
+        && !left.is_definition_generic(db)
+        && !right.is_definition_generic(db)
+        && left.has_unrelated_class(db, right)

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>

carljm carljm commented on code on Dec 04, 2026 19:40 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -2333,26 +2367,126 @@ fn simplify_intersection_pair_impl<'db>(
     IntersectionSimplification::Unchanged
 }
 
+/// The state after applying an ordered sequence of exclusions. Keep this separate
+/// from the finished type: `build` can collapse an enum complement or simplify a
+/// constrained type variable, which would change how we handle the next exclusion.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, salsa::SalsaValue, get_size2::GetSize)]
+struct ReplayedIntersection<'db> {
+    // Reuse the interned storage for the two ordered sets.
+    state: IntersectionType<'db>,
+    // Every insertion appended its input without changing any earlier element.
+    only_appended: bool,
+}
+
+impl<'db> ReplayedIntersection<'db> {
+    fn into_builder(self, db: &'db dyn Db) -> InnerIntersectionBuilder<'db> {
+        InnerIntersectionBuilder {
+            positive: self.state.positive(db).clone(),
+            negative: self.state.negative(db).clone(),
+        }
+    }
+}
+
+/// Start from the caller's positives and apply the exclusions in order. Salsa
+/// tracks the comparisons so an edit can change which elements survive.
+#[salsa::tracked(returns(copy), cycle_result=|_, _, _, _| None, heap_size=ruff_memory_usage::heap_size)]
+fn replay_exclusions<'db>(
+    db: &'db dyn Db,
+    program: crate::Program<'db>,
+    input: IntersectionType<'db>,
+) -> Option<ReplayedIntersection<'db>> {
+    let positive = input.positive(db);
+    let negative = input.negative(db);
+    // Alias expansion and distribution depend on the surrounding builder.
+    if negative.iter().any(|ty| {
+        ty.is_alias_like()
+            || matches!(
+                ty,
+                Type::Union(_) | Type::Intersection(_) | Type::EnumComplement(_)
+            )
+    }) {
+        return None;
+    }
+
+    let (mut builder, mut only_appended, prefix_len) = if let Some(prefix) = input.shared_prefix(db)
+    {
+        let result = replay_exclusions(db, program, prefix)?;
+        (
+            result.into_builder(db),
+            result.only_appended,
+            prefix.negative(db).len(),
+        )
+    } else {
+        (
+            InnerIntersectionBuilder {
+                positive: positive.clone(),
+                negative: NegativeIntersectionElements::default(),
+            },
+            true,
+            0,
+        )
+    };
+
+    // Branches of a union can share the comparisons between exclusions. If every
+    // exclusion simply appended in isolation, none simplifies an earlier one.
+    // We can skip those comparisons until a positive changes what we inserted.
+    let independent = only_appended && !positive.is_empty() && {
+        let exclusions = IntersectionType::new(db, FxOrderSet::default(), negative.clone());
+        replay_exclusions(db, program, exclusions)?.only_appended
+    };
+    let env = ProgramEnvironment::from_program(program);
+    for ty in negative.iter().skip(prefix_len) {
+        let comparison = if independent && only_appended {
+            ExclusionComparison::SetMembership
+        } else {
+            ExclusionComparison::Pairwise
+        };
+        let effect = builder.add_negative_impl(db, &env, *ty, comparison);
+        only_appended &= effect == ExclusionEffect::Appended;
+    }
+
+    Some(ReplayedIntersection {
+        state: IntersectionType::new(db, builder.positive, builder.negative),

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.

carljm carljm commented on code on Dec 04, 2026 19:40 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -2721,7 +2855,7 @@ impl<'db> InnerIntersectionBuilder<'db> {
         }
     }
 
-    /// Whether all the distinct built-in literals in `exclusions` would survive insertion.
+    /// Whether we can copy the literal exclusions without checking each one against the positives.

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.

carljm carljm commented on code on Dec 04, 2026 19:40 UTC
Code Review
crates/ty_python_semantic/resources/mdtest/generics/pep695/variables.md:1
@@ -1659,6 +1673,64 @@ class Child[T = Child.Item](Parent[T]): ...
 reveal_type(Child[int]())  # revealed: Child[int]
 ```
 
+### Recursive alias through a subclass
+
+Looking up `Leaf.Default` can require the ancestors of `Base`, whose own default is `Leaf.Default`.
+Inference still converges when `Tree` refers to itself through `Child`.
+
+```py
+from typing import TypeAlias
+
+class Base[T = Leaf.Default]:
+    Values: TypeAlias = "Base[int] | int"
+    type Tree = Leaf.Default | list[Child.Tree]
+    Default: TypeAlias = "Values | Child[str]"
+
+class Child[T = Base.Default](Base[T]): ...
+class Leaf(Child): ...
+```
+
+### Exhaustive narrowing of an inherited default

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.

carljm carljm commented on code on Dec 04, 2026 20:56 UTC
Code Review
crates/ty_python_semantic/resources/mdtest/generics/pep695/variables.md:1
@@ -1643,6 +1643,20 @@ reveal_type(Box())  # revealed: Box[Unknown]
 reveal_type(NestedBox())  # revealed: NestedBox[Unknown]
 ```
 
+### A default that excludes a specialization of its own class
+
+`Box[int]` already specifies its type argument, so we can compare the two exclusions without
+resolving the default for `Box` again.
+
+```py
+from ty_extensions import Not
+
+class Box[T = Not[Box[int] | int]]: ...

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.)

carljm carljm commented on code on Dec 04, 2026 21:17 UTC
Code Review
crates/ty_python_semantic/src/types/class/static_literal.rs:1
@@ -950,7 +950,7 @@ impl<'db> StaticClassLiteral<'db> {
 
         #[salsa::tracked(
             returns(as_ref),
-            cycle_initial=|db, id, _, input| mro_ancestors_cycle_initial(db, id, input),
+            cycle_initial=|db, _, _, class| Err(Box::new(StaticMroError::cycle(db, class))),

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.

carljm carljm commented on code on Dec 04, 2026 21:31 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic.rs:1
@@ -1190,6 +1190,30 @@ pub(crate) fn walk_intersection_type<'db, V: visitor::TypeVisitor<'db> + ?Sized>
 
 #[salsa::tracked]
 impl<'db> IntersectionType<'db> {
+    /// Reuse all but the last chunk of an intersection built by successive exclusions.
+    /// Splitting a flat set would copy and intern prefixes that may never be used again.

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.

carljm carljm commented on code on Dec 04, 2026 21:31 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -3615,6 +3759,28 @@ mod tests {
             (Multiple(prefix), Shared(chunks)) if Arc::ptr_eq(prefix, &chunks[0])
         ));
 
+        // Only reuse prefixes that already share their storage. A flat set can have
+        // any length, even when the next exclusion starts a new chunk.
+        assert_eq!(full.shared_prefix(&db), Some(intern(68)));
+        let flat = intern(71);
+        assert_eq!(flat.shared_prefix(&db), None);
+        let extended = IntersectionBuilder::new(&db, &env)
+            .add_positive(Type::Intersection(flat))
+            .add_negative(Type::int_literal(71))
+            .build()
+            .as_intersection()
+            .unwrap();
+        assert_eq!(extended.shared_prefix(&db), Some(flat));

Do these three assertions need to be full assertions rather than debug assertions?

carljm carljm commented on code on Dec 04, 2026 21:33 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -2055,7 +2055,20 @@ impl<'db> IntersectionBuilder<'db> {
                     self.add_positive_impl::<L>(*pos, seen_aliases)?;
                 }
                 let negatives = other.negative(db);
-                if !self.try_add_literal_exclusions(negatives) {
+                if self.try_add_literal_exclusions(negatives) {
+                    return ControlFlow::Continue(());
+                }
+                if negatives.len() >= 16
+                    && let [inner] = &mut self.intersections[..]
+                    && inner.negative.is_empty()
+                    && !inner.contains_never()
+                    // Reuse inputs we already have. Interning every combination of the
+                    // caller's positives and these exclusions can retain many one-off inputs.
+                    && inner.positive.iter().eq(other.positive(db))
+                    && let Some(result) = replay_exclusions(db, self.env.program(db), other)

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.

carljm carljm approved these changes on Dec 04, 2026 21:38 UTC
Approved Reviewer

Thanks!

charliermarsh charliermarsh commented on code on Dec 04, 2026 21:56 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -3615,6 +3759,28 @@ mod tests {
             (Multiple(prefix), Shared(chunks)) if Arc::ptr_eq(prefix, &chunks[0])
         ));
 
+        // Only reuse prefixes that already share their storage. A flat set can have
+        // any length, even when the next exclusion starts a new chunk.
+        assert_eq!(full.shared_prefix(&db), Some(intern(68)));
+        let flat = intern(71);
+        assert_eq!(flat.shared_prefix(&db), None);
+        let extended = IntersectionBuilder::new(&db, &env)
+            .add_positive(Type::Intersection(flat))
+            .add_negative(Type::int_literal(71))
+            .build()
+            .as_intersection()
+            .unwrap();
+        assert_eq!(extended.shared_prefix(&db), Some(flat));

This is test code, I think the full assertions is right, no?

carljm carljm commented on code on Dec 04, 2026 22:31 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -3615,6 +3759,28 @@ mod tests {
             (Multiple(prefix), Shared(chunks)) if Arc::ptr_eq(prefix, &chunks[0])
         ));
 
+        // Only reuse prefixes that already share their storage. A flat set can have
+        // any length, even when the next exclusion starts a new chunk.
+        assert_eq!(full.shared_prefix(&db), Some(intern(68)));
+        let flat = intern(71);
+        assert_eq!(flat.shared_prefix(&db), None);
+        let extended = IntersectionBuilder::new(&db, &env)
+            .add_positive(Type::Intersection(flat))
+            .add_negative(Type::int_literal(71))
+            .build()
+            .as_intersection()
+            .unwrap();
+        assert_eq!(extended.shared_prefix(&db), Some(flat));

Oh sorry, I totally missed that this was in a test! Ignore.

charliermarsh charliermarsh commented on code on Dec 04, 2026 22:34 UTC
Code Review
crates/ty_python_semantic/src/types/set_theoretic/builder.rs:1
@@ -2055,7 +2055,20 @@ impl<'db> IntersectionBuilder<'db> {
                     self.add_positive_impl::<L>(*pos, seen_aliases)?;
                 }
                 let negatives = other.negative(db);
-                if !self.try_add_literal_exclusions(negatives) {
+                if self.try_add_literal_exclusions(negatives) {
+                    return ControlFlow::Continue(());
+                }
+                if negatives.len() >= 16
+                    && let [inner] = &mut self.intersections[..]
+                    && inner.negative.is_empty()
+                    && !inner.contains_never()
+                    // Reuse inputs we already have. Interning every combination of the
+                    // caller's positives and these exclusions can retain many one-off inputs.
+                    && inner.positive.iter().eq(other.positive(db))
+                    && let Some(result) = replay_exclusions(db, self.env.program(db), other)

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.

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