Skip to content

Require coherence of supertrait associated item bounds for dyn-compability - #158915

Open
theemathas wants to merge 2 commits into
rust-lang:mainfrom
theemathas:coherent-dyn-compat
Open

theemathas wants to merge 2 commits into
rust-lang:mainfrom
theemathas:coherent-dyn-compat

Conversation

@theemathas

@theemathas theemathas commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

View all comments

This PR is an alternative to #157710. However, unlike that PR, this PR does not address #150936.

Fixes #154662

In a dyn type, if multiple bounds are specified via supertraits for the same associated item, then we previously accepted them if the relevant trait's generics are different, even if the bounds conflict.

This was unsound, since those generics could end up being instantiated with identical concrete types, causing the dyn type to have two different "values" for the same bound.

Thus, if a trait has multiple supertrait bounds for the same associated item, we check whether those bounds are coherent, similarly to how we check for overlap between impls (i.e., we check if the generics could be instantiated to be the same while the "values" of the bounds are different). If the bounds are incoherent, then we consider the trait to be dyn-incompatible.

r? @fmease

@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. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver) labels Jul 7, 2026
@theemathas

Copy link
Copy Markdown
Contributor Author

I'm unsure of what to do with the now-failing tests.

I'm also rather unsure of my code in general. Please be careful with the review to make sure I didn't do anything stupid. Thank you.

@theemathas theemathas added needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. needs-crater This change needs a crater run to check for possible breakage in the ecosystem. labels Jul 7, 2026
@theemathas
theemathas force-pushed the coherent-dyn-compat branch from 4d67fa1 to 256670e Compare July 7, 2026 15:07
@theemathas

Copy link
Copy Markdown
Contributor Author

r? types

@rustbot rustbot added the T-types Relevant to the types team, which will review and decide on the PR/issue. label Jul 21, 2026
@rustbot rustbot assigned lcnr and unassigned fmease Jul 21, 2026
@lcnr

lcnr commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

after that, we should do a crater run 😁

@lcnr

lcnr commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

@rustbot author

@rustbot rustbot 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 29, 2026
@rustbot

rustbot commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

Reminder, once the PR becomes ready for a review, use @rustbot ready.

@rust-bors

This comment has been minimized.

@theemathas
theemathas force-pushed the coherent-dyn-compat branch from 256670e to 4adf718 Compare August 16, 2026 09:25
@rustbot

This comment has been minimized.

@theemathas
theemathas force-pushed the coherent-dyn-compat branch from 4adf718 to 97592bc Compare August 16, 2026 16:10
@theemathas

theemathas commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor Author

I decided to ask an LLM for assistance with understanding how the trait solver API works, and with double-checking my code for any glaring issues. I still wrote all code manually. In particular, the LLM did the following:

  • Explained the difference between InferCtxt and ObligationCtxt. (The documentation was unfortunately not very helpful to me here. I previously didn't realize that my previous InferCtxt usage generated nested obligations that weren't automatically solved for.)
  • Explained the bug in my initial implementation attempt (which incorrectly called fork_with_typing_mode in an attempt to "invert the polarity" between the two ObligationCtxts).
  • Pointed out the existence of plug_infer_with_placeholders, which I verified to have the behavior that I needed.
  • Pointed out that I needed to call resolve_regions. (I think that this is a rather unfortunate footgun that doesn't seem to be properly documented.)
  • Pointed out a potential problem due to me not instantiating the param_env. I don't understand what this problem is, so I'm deferring to you on what to do here. See the comment below.

I claim full responsibility of all code in this PR.

Comment on lines +1074 to +1082
// Now that we've constrained the two projections to be on the same thing,
// we check whether the two terms are necessarily equal to each other.
// If they are, then the two projections are coherent.
plug_infer_with_placeholders(&infcx, ty::UniverseIndex::ROOT, (proj_1, proj_2));
let ocx = ObligationCtxt::new(&infcx);
ocx.eq(&ObligationCause::dummy(), param_env, proj_1.term, proj_2.term).is_ok()
&& ocx.evaluate_obligations_error_on_ambiguity().no_errors()
&& ocx.resolve_regions(CRATE_DEF_ID, param_env, []).is_empty()
}

@theemathas theemathas Aug 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The LLM, in reviewing my code, told me that I have to instantiate the param_env with trait_args here. However, I should not do this instantiation in the can_equate_generics computation. Is the LLM right here? I don't understand at all what this does.

View changes since the review

@theemathas theemathas Aug 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This test is currently the only pre-existing test that this PR breaks. What should be done about this test?

View changes since the review

@theemathas

Copy link
Copy Markdown
Contributor Author

Is this PR ready for a crater run?

@rustbot ready

@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 Aug 16, 2026
@theemathas
theemathas force-pushed the coherent-dyn-compat branch from 97592bc to 8546c21 Compare August 18, 2026 13:09
@theemathas

Copy link
Copy Markdown
Contributor Author

I just realized that the current implementation has a weird consequence: It is possible for a dyn-compatible trait to be a subtrait of a dyn-incompatible trait. For example:

trait Super<T> {
    type Assoc;
}
trait Sub<T, U>: Super<T, Assoc = i32> + Super<U, Assoc = i64> {}
trait Sub2: Sub<i32, i64> {}

In the above code, dyn Sub2 is legal, but dyn Sub<i32, i64> is not. Is this a problem? Does this cause problems with vtable generation?

@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Sep 14, 2026
Require coherence of supertrait associated item bounds for dyn-compability
@rust-bors

rust-bors Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 0335fc7 (0335fc7ee9e33d92e03d99f3e2fb0fe6119f3cc0)
Base parent: ed77b7b (ed77b7b8699e342c2dc842c83cb5fe4025252ee8)

@theemathas

Copy link
Copy Markdown
Contributor Author

@craterbot check

@craterbot

Copy link
Copy Markdown
Collaborator

👌 Experiment pr-158915-1 created and queued.
🤖 Automatically detected try build 0335fc7
🔍 You can check out the queue and this experiment's details.

ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot craterbot added S-waiting-on-crater Status: Waiting on a crater run to be completed. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Sep 14, 2026
@craterbot

Copy link
Copy Markdown
Collaborator

🚧 Experiment pr-158915-1 is now running

ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

@craterbot

Copy link
Copy Markdown
Collaborator

🎉 Experiment pr-158915-1 is completed!
📊 1 regressed and 0 fixed (1116832 total)
📊 5994 spurious results on the retry-regressed-list.txt, consider a retry1 if this is a significant amount.
📰 Open the summary report.

⚠️ If you notice any spurious failure please add them to the denylist!
ℹ️ Crater is a tool to run experiments across parts of the Rust ecosystem. Learn more

Footnotes

  1. re-run the experiment with crates=https://crater-reports.s3.amazonaws.com/pr-158915-1/retry-regressed-list.txt ↩

@craterbot craterbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-crater Status: Waiting on a crater run to be completed. labels Sep 23, 2026
@rust-bors

This comment has been minimized.

@theemathas

Copy link
Copy Markdown
Contributor Author

Crater is clean.

@rustbot

This comment has been minimized.

@rustbot

This comment has been minimized.

@theemathas

theemathas commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Squashed into 2 commits, and rebased. Ready for review, and hopefully ready for FCP.

@rustbot

This comment has been minimized.

…ics.

See rust-lang#154662

These tests will be fixed in a subsequent commit.
…ility

Fixes rust-lang#154662

In a `dyn` type, if multiple bounds are specified via supertraits for
the same associated item, then we previously accepted them if
the relevant trait's generics are different,
even if the bounds conflict.

This was unsound, since those generics could end up being instantiated
with identical concrete types, causing the `dyn` type to have
two different "values" for the same bound.

Thus, if a trait has multiple supertrait bounds for the same
associated item, we check whether those bounds are coherent,
similarly to how we check for overlap between impls (i.e., we check
if the generics could be instantiated to be the same while the "values"
of the bounds are different). If the bounds are incoherent, then we
consider the trait to be dyn-incompatible.
@rustbot

rustbot commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

This PR was rebased onto a different main commit. Here's a range-diff highlighting what actually changed.

Rebasing is a normal part of keeping PRs up to date, so no action is needed—this note is just to help reviewers.

@theemathas

Copy link
Copy Markdown
Contributor Author

I moved the new tests into its own directory.

I had an LLM look at this PR again. It came up with 4 new test cases (normalize-blanket, normalize-blanket-pointee-sized, depends-on-assoc-ty-bound, depends-on-lifetime-bound), which I edited then added to this PR.

The LLM also noted that my initial idea of switching typing modes between the two stages was already correct. So I did that, which caused normalize-blanket-pointee-sized to start compiling. I don't understand why typing mode would affect this, although it's more a case of "I didn't understand why it previously failed".

@lcnr lcnr left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

sgtm. Can you try to write a Types FCP proposal for this

View changes since this review

// even though a supertrait is dyn-incompatible.
// This can occur when the subtrait instantiates generics to be
// concrete enough that we can prove that the associated type bounds
// do not conflict.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think that's novel. Can we get bugs from doing trait upcasting or what not?

Comment on lines +2 to +3
// Make sure that the dyn-compatibility check for conflicting bounds
// only use bounds from supertraits, and not from type parameters.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what exactly does that mean?


// Determining that `Sub` is dyn-compatible requires normalizing `<Self as Constant>::Out`.
// This depends on impl blocks elsewhere. Make sure we can do this.
// Due to the `PointeeSized`, this normalization doesn't need any trait bounds on `Self`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

instead use #[rustc_no_implicit_default_bounds]


/// Computes [`DynCompatibilityViolation::IncoherentSupertraitAssocs`]
#[instrument(level = "debug", skip(tcx))]
fn incoherent_supertrait_assocs(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

instead of assocs, I'd prefer assoc_items as naming

})
}

#[instrument(level = "debug", skip(tcx), ret)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

function comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

also worth mentioning that this is similar to the explicit negative coherence checking, i.e.

fn impl_intersection_has_negative_obligation(

// as they're projecting different things.
let can_equate_generics =
proj_1.projection_term.args.iter().zip_eq(proj_2.projection_term.args).all(
|(arg_1, arg_2)| ocx.eq(&ObligationCause::dummy(), param_env, arg_1, arg_2).is_ok(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

we should equate them in an empty env here

Comment on lines +1169 to +1170
// FIXME: This doesn't instantiate generic params with placeholders in any bounds
// that may be helpful in proving that the two terms are equal with each other.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

see what we do for explicit negative coherence

// FIXME(with_negative_coherence): the infcx has constraints from equating
// the impl headers. We should use these constraints as assumptions, not as
// requirements, when proving the negated where clauses below.
drop(equate_obligations);
drop(infcx.take_registered_region_obligations());
drop(infcx.take_registered_region_assumptions());
drop(infcx.take_and_reset_region_constraints());
plug_infer_with_placeholders(
infcx,
root_universe,
(impl1_header.impl_args, impl2_header.impl_args),
);
// Right above we plug inference variables with placeholders,
// this gets us new impl1_header_args with the inference variables actually resolved
// to those placeholders.
let impl1_header_args = infcx.deeply_resolve_ignoring_regions(impl1_header.impl_args);
// So there are no infer variables left now, except regions which aren't resolved by
// `deeply_resolve_ignoring_regions`.
assert!(!impl1_header_args.has_non_region_infer());
let param_env = ty::EarlyBinder::bind(tcx, tcx.param_env(impl1_def_id))
.instantiate(tcx, impl1_header_args)
.skip_norm_wip();

should do the same here

Comment on lines +1172 to +1174
// For this second step, we use typecheck mode, as we're distinguishing
// "maybe they're the same" vs "they're definitely the same".
let infcx = infcx.fork_with_typing_mode(TypingMode::non_body_analysis());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

also see

// N.B. We don't need to use intercrate mode here because we're trying to prove
// the *existence* of a negative goal, not the non-existence of a positive goal.
// Without this, we over-eagerly register coherence ambiguity candidates when
// impl candidates do exist.
// FIXME(#132279): `TypingMode::non_body_analysis` is a bit questionable here as it
// would cause us to reveal opaque types to leak their auto traits.
let ref infcx = root_infcx.fork_with_typing_mode(TypingMode::non_body_analysis());

@lcnr

lcnr commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

@rustbot author

@rustbot rustbot 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 Nov 24, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-crater This change needs a crater run to check for possible breakage in the ecosystem. needs-fcp This change is insta-stable, or significant enough to need a team FCP to proceed. S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. T-types Relevant to the types team, which will review and decide on the PR/issue. WG-trait-system-refactor The Rustc Trait System Refactor Initiative (-Znext-solver)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Conflicting supertrait associated type in dyn causes unsoundness and ICE

7 participants