Skip to content

rustc_trait_selection: fix trait solver hang caused by degenerate obligations#159774

Open
InvalidPathException wants to merge 1 commit into
rust-lang:mainfrom
InvalidPathException:fix-old-solver-hang
Open

rustc_trait_selection: fix trait solver hang caused by degenerate obligations#159774
InvalidPathException wants to merge 1 commit into
rust-lang:mainfrom
InvalidPathException:fix-old-solver-hang

Conversation

@InvalidPathException

@InvalidPathException InvalidPathException commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

Closes #157516 and #159750.

Bisection pointed to #142712 but the problem has always been present. Fulfillment can go on forever if a degenerate obligation causes additional obligations from poly_project_and_unify_term to be copies of the degenerate one.

Current fix is checking if the obligation is degenerate, making the degenerate case stall, waiting for other obligations to constrain its inference variables, so it can actually normalize or error instead of propagating this. error immediately since the code will not compile anyways.

I am not sure if this is ideal, might need to check perf due to the added heavy-ish condition check.

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Jul 23, 2026
@rustbot

rustbot commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator

r? @mu001999

rustbot has assigned @mu001999.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

Why was this reviewer chosen?

The reviewer was selected based on:

  • Owners of files modified in this PR: compiler
  • compiler expanded to 74 candidates
  • Random selection from 20 candidates

@mu001999

Copy link
Copy Markdown
Member

@rustbot reroll

@rustbot rustbot assigned jackh726 and unassigned mu001999 Jul 23, 2026
@mu001999

mu001999 commented Jul 23, 2026

Copy link
Copy Markdown
Member

might need to check perf due to the added heavy-ish condition check.

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jul 23, 2026
@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Jul 23, 2026
…try>

rustc_trait_selection: fix trait solver hang caused by degenerate obligations
@rust-bors

rust-bors Bot commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 41450ef (41450ef5e1890fe9aaccef25127708688bc116af)
Base parent: 165cce8 (165cce8d820b229af8f6a8226cf0b910b57600ff)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown
Collaborator

Finished benchmarking commit (41450ef): comparison URL.

Overall result: ❌ regressions - no action needed

Benchmarking means the PR may be perf-sensitive. Consider adding rollup=never if this change is not fit for rolling up.

@rustbot label: -S-waiting-on-perf -perf-regression

Instruction count

Our most reliable metric. Used to determine the overall result above. However, even this metric can be noisy.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
0.5% [0.4%, 0.5%] 8
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (primary -8.4%, secondary -2.0%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-8.4% [-8.4%, -8.4%] 1
Improvements ✅
(secondary)
-2.0% [-2.0%, -2.0%] 1
All ❌✅ (primary) -8.4% [-8.4%, -8.4%] 1

Cycles

Results (primary 2.0%)

A less reliable metric. May be of interest, but not used to determine the overall result above.

mean range count
Regressions ❌
(primary)
2.0% [2.0%, 2.0%] 1
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 2.0% [2.0%, 2.0%] 1

Binary size

This perf run didn't have relevant results for this metric.

Bootstrap: 485.902s -> 492.139s (1.28%)
Artifact size: 387.66 MiB -> 387.65 MiB (-0.00%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Jul 23, 2026

@jackh726 jackh726 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious if there's any code that we expect to start to compile with this change, as opposed to eventually erroring. If the answer is no, then perhaps we can just error immediately, instead of stalling.

View changes since this review

})
})
} {
stalled_on.clear();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This really could be expressed better. Something like

  ProjectAndUnifyResult::Holds(os) if os.is_empty() =>ProcessResult::Changed(mk_pending(obligation, os)),
  ProjectAndUnifyResult::Holds(os) => {
      let input_projection_term = infcx
          .resolve_vars_if_possible(project_obligation.predicate)
          .map_bound(|p| p.projection_term);
      let all_same_term = os.iter().all(|o| {
          let Some(proj_clause) = o.predicate.as_projection_clause() else { return false };
          infcx.resolve_vars_if_possible(proj_clause).map_bound(|p| p.projection_term) == input
      });
      if all_same_term {
          ...
      } else {
          ProcessResult::Changed(mk_pending(obligation, os))
      }
  }

Comment on lines +954 to +956
// Every nested obligation is a copy of the obligation we are processing,
// registering would make fulfillment process the same obligation forever.
// So, stall until an inference variable in the predicate is constrained.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A concrete example in a comment here would be useful.

This is also slightly stronger than the comment, anyways: every nested obligation has the same projection term.

@jackh726 jackh726 added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 23, 2026
@InvalidPathException

Copy link
Copy Markdown
Contributor Author

I'm curious if there's any code that we expect to start to compile with this change, as opposed to eventually erroring. If the answer is no, then perhaps we can just error immediately, instead of stalling.

I did consider this, there should not be anything that compiles because of this today, the stall path is reachable only when

  1. normalization returned NoProgress (ProjectionCandidateSet::None in project)
  2. equating the rigid alias with the term variable failed generalization

At that point it must error regardless of how it resolves later on (as of today). But stalling gives a (maybe) better message as we allow more info to come in, since this path is relatively rare, it seems at least not problematic to stall.

trait Bound {}
impl Bound for u32 {}

trait Driver {
    type Object<Ctx: Bound>: Bound;
}

fn make<T: Driver, C: Bound>(c: C) -> T::Object<C> {
    todo!()
}

fn any<X>() -> X {
    todo!()
}

fn f<T: Driver>() {
    let mut x = any();          // x: ?x
    x = make::<T, _>(x);        // forces <T as Driver>::Object<?x> == ?x
}

fn main() {}

Stall:

error[E0283]: type annotations needed
  --> demo.rs:17:9
   |
17 |     let mut x = any();
   |         ^^^^^
18 |     x = make::<T, _>(x);
   |                   - type must be known at this point
   |
   = note: the type must implement `Bound`
help: the trait `Bound` is implemented for `u32`
  --> demo.rs:2:1
   |
 2 | impl Bound for u32 {}
   | ^^^^^^^^^^^^^^^^^^
note: required by a bound in `make`
  --> demo.rs:8:23
   |
 8 | fn make<T: Driver, C: Bound>(_c: C) -> T::Object<C> {
   |                       ^^^^^ required by this bound in `make`
help: consider giving `x` an explicit type
   |
17 |     let mut x: u32 = any();
   |              +++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0283`.

Error immediately:

error[E0284]: type annotations needed for `<T as Driver>::Object<_>`
  --> demo.rs:17:9
   |
17 |     let mut x = any();
   |         ^^^^^
18 |     x = make::<T, _>(x);
   |                      - type must be known at this point
   |
   = note: cannot satisfy `<T as Driver>::Object<_>
help: consider giving `x` an explicit type, where the placeholders `_` are specified
   |
17 |     let mut x: <_ as Driver>::Object<_> = any();
   |              ++++++++++++++++++++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 24, 2026
@jackh726

Copy link
Copy Markdown
Member

Given that the new solver is coming soon and completely overhauls normalization, I'm not inclined to potentially introduce more things that could compile, particularly if the reasoning is just better diagnostics.

Even still, the diagnostics in the error immediately case are not really bad. So, let's go that route.

@jackh726 jackh726 added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jul 24, 2026
@jackh726

Copy link
Copy Markdown
Member

Sorry, can you squash? And then r=me

@InvalidPathException

Copy link
Copy Markdown
Contributor Author

r? @jackh726

@rustbot

rustbot commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator

Requested reviewer is already assigned to this pull request.

Please choose another assignee.

@jackh726

Copy link
Copy Markdown
Member

@bors r+

@rust-bors

rust-bors Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor

📌 Commit f2e0edf has been approved by jackh726

It is now in the queue for this repository.

🌲 The tree is currently closed for pull requests below priority 100. This pull request will be tested once the tree is reopened.

Reason for tree closure: spurious failures

@rust-bors rust-bors Bot added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Jul 26, 2026
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 26, 2026
…r-hang, r=jackh726

rustc_trait_selection: fix trait solver hang caused by degenerate obligations

Closes rust-lang#157516 and rust-lang#159750.

Bisection pointed to rust-lang#142712 but the problem has always been present. Fulfillment can go on forever if a degenerate obligation causes additional obligations from `poly_project_and_unify_term` to be copies of the degenerate one.

Current fix is checking if the obligation is degenerate, ~making the degenerate case stall, waiting for other obligations to constrain its inference variables, so it can actually normalize or error instead of propagating this.~ error immediately since the code will not compile anyways.

I am not sure if this is ideal, might need to check perf due to the added heavy-ish condition check.
JonathanBrouwer added a commit to JonathanBrouwer/rust that referenced this pull request Jul 26, 2026
…r-hang, r=jackh726

rustc_trait_selection: fix trait solver hang caused by degenerate obligations

Closes rust-lang#157516 and rust-lang#159750.

Bisection pointed to rust-lang#142712 but the problem has always been present. Fulfillment can go on forever if a degenerate obligation causes additional obligations from `poly_project_and_unify_term` to be copies of the degenerate one.

Current fix is checking if the obligation is degenerate, ~making the degenerate case stall, waiting for other obligations to constrain its inference variables, so it can actually normalize or error instead of propagating this.~ error immediately since the code will not compile anyways.

I am not sure if this is ideal, might need to check perf due to the added heavy-ish condition check.
rust-bors Bot pushed a commit that referenced this pull request Jul 26, 2026
…uwer

Rollup of 24 pull requests

Successful merges:

 - #159638 (bootstrap: Split the `Step` trait into multiple traits)
 - #159774 (rustc_trait_selection: fix trait solver hang caused by degenerate obligations)
 - #159837 (line-tables-only test: check that the line number matches the function name)
 - #159946 (Update Enzyme submodule to imporve llvm-cov)
 - #159617 (Fix up `#[linkage]` target checking)
 - #159733 (std: Switch implementations of `thread_local!` for WASI)
 - #159783 (Check unsafe impls on safe EIIs)
 - #159810 (Add tuple never coercion collection regression test)
 - #159821 (Update expect message using the recommended style in binary_heap module)
 - #159826 (Remove redundant `#[rustc_paren_sugar]` feature gate)
 - #159846 (Implement `str::copy_from_str`)
 - #159849 (rustc_parse: Stop returning `Option` from statement parsing)
 - #159853 (Updated expect messages for `CString` struct and method documentation)
 - #159875 (More cleanup in `rustc_attr_parsing`)
 - #159882 (Update expect messages in library/alloc/boxed.rs and library/alloc/string.rs to follow the style guide)
 - #159891 (Split multiline derives into std/rustc macros)
 - #159893 (Fix `find_attr` hygiene and `rustc_hir` cleanups)
 - #159895 (rustc-dev-guide subtree update)
 - #159902 (Clarify that the expected runtime symbols signature is for the current target only)
 - #159914 (Fix error in diagnostic on_unmatched_args)
 - #159917 (spare capacity mut constification)
 - #159918 (rename abort_unwind → abort_on_unwind)
 - #159936 (Minor `rustc_ast::ast` doc cleanups)
 - #159945 (Update expect messages in library/core/src/ptr/non_null.rs)
rust-bors Bot pushed a commit that referenced this pull request Jul 26, 2026
…uwer

Rollup of 24 pull requests

Successful merges:

 - #159638 (bootstrap: Split the `Step` trait into multiple traits)
 - #159774 (rustc_trait_selection: fix trait solver hang caused by degenerate obligations)
 - #159837 (line-tables-only test: check that the line number matches the function name)
 - #159946 (Update Enzyme submodule to imporve llvm-cov)
 - #159617 (Fix up `#[linkage]` target checking)
 - #159733 (std: Switch implementations of `thread_local!` for WASI)
 - #159783 (Check unsafe impls on safe EIIs)
 - #159810 (Add tuple never coercion collection regression test)
 - #159821 (Update expect message using the recommended style in binary_heap module)
 - #159826 (Remove redundant `#[rustc_paren_sugar]` feature gate)
 - #159846 (Implement `str::copy_from_str`)
 - #159849 (rustc_parse: Stop returning `Option` from statement parsing)
 - #159853 (Updated expect messages for `CString` struct and method documentation)
 - #159875 (More cleanup in `rustc_attr_parsing`)
 - #159882 (Update expect messages in library/alloc/boxed.rs and library/alloc/string.rs to follow the style guide)
 - #159891 (Split multiline derives into std/rustc macros)
 - #159893 (Fix `find_attr` hygiene and `rustc_hir` cleanups)
 - #159895 (rustc-dev-guide subtree update)
 - #159902 (Clarify that the expected runtime symbols signature is for the current target only)
 - #159914 (Fix error in diagnostic on_unmatched_args)
 - #159917 (spare capacity mut constification)
 - #159918 (rename abort_unwind → abort_on_unwind)
 - #159936 (Minor `rustc_ast::ast` doc cleanups)
 - #159945 (Update expect messages in library/core/src/ptr/non_null.rs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rustc hang in Rust for Linux

5 participants