rustc_type_ir/search_graph/
mod.rs

1/// The search graph is responsible for caching and cycle detection in the trait
2/// solver. Making sure that caching doesn't result in soundness bugs or unstable
3/// query results is very challenging and makes this one of the most-involved
4/// self-contained components of the compiler.
5///
6/// We added fuzzing support to test its correctness. The fuzzers used to verify
7/// the current implementation can be found in https://github.com/lcnr/search_graph_fuzz.
8///
9/// This is just a quick overview of the general design, please check out the relevant
10/// [rustc-dev-guide chapter](https://rustc-dev-guide.rust-lang.org/solve/caching.html) for
11/// more details. Caching is split between a global cache and the per-cycle `provisional_cache`.
12/// The global cache has to be completely unobservable, while the per-cycle cache may impact
13/// behavior as long as the resulting behavior is still correct.
14use std::cmp::Ordering;
15use std::collections::BTreeSet;
16use std::fmt::Debug;
17use std::hash::Hash;
18use std::marker::PhantomData;
19
20use derive_where::derive_where;
21use rustc_index::{Idx, IndexVec};
22use tracing::debug;
23
24use crate::data_structures::HashMap;
25
26mod global_cache;
27use global_cache::CacheData;
28pub use global_cache::GlobalCache;
29
30/// The search graph does not simply use `Interner` directly
31/// to enable its fuzzing without having to stub the rest of
32/// the interner. We don't make this a super trait of `Interner`
33/// as users of the shared type library shouldn't have to care
34/// about `Input` and `Result` as they are implementation details
35/// of the search graph.
36pub trait Cx: Copy {
37    type Input: Debug + Eq + Hash + Copy;
38    type Result: Debug + Eq + Hash + Copy;
39
40    type DepNodeIndex;
41    type Tracked<T: Debug + Clone>: Debug;
42    fn mk_tracked<T: Debug + Clone>(
43        self,
44        data: T,
45        dep_node_index: Self::DepNodeIndex,
46    ) -> Self::Tracked<T>;
47    fn get_tracked<T: Debug + Clone>(self, tracked: &Self::Tracked<T>) -> T;
48    fn with_cached_task<T>(self, task: impl FnOnce() -> T) -> (T, Self::DepNodeIndex);
49
50    fn with_global_cache<R>(self, f: impl FnOnce(&mut GlobalCache<Self>) -> R) -> R;
51
52    fn evaluation_is_concurrent(&self) -> bool;
53}
54
55pub trait Delegate {
56    type Cx: Cx;
57    /// Whether to use the provisional cache. Set to `false` by a fuzzer when
58    /// validating the search graph.
59    const ENABLE_PROVISIONAL_CACHE: bool;
60    type ValidationScope;
61    /// Returning `Some` disables the global cache for the current goal.
62    ///
63    /// The `ValidationScope` is used when fuzzing the search graph to track
64    /// for which goals the global cache has been disabled. This is necessary
65    /// as we may otherwise ignore the global cache entry for some goal `G`
66    /// only to later use it, failing to detect a cycle goal and potentially
67    /// changing the result.
68    fn enter_validation_scope(
69        cx: Self::Cx,
70        input: <Self::Cx as Cx>::Input,
71    ) -> Option<Self::ValidationScope>;
72
73    const FIXPOINT_STEP_LIMIT: usize;
74
75    type ProofTreeBuilder;
76    fn inspect_is_noop(inspect: &mut Self::ProofTreeBuilder) -> bool;
77
78    const DIVIDE_AVAILABLE_DEPTH_ON_OVERFLOW: usize;
79
80    fn initial_provisional_result(
81        cx: Self::Cx,
82        kind: PathKind,
83        input: <Self::Cx as Cx>::Input,
84    ) -> <Self::Cx as Cx>::Result;
85    fn is_initial_provisional_result(
86        cx: Self::Cx,
87        kind: PathKind,
88        input: <Self::Cx as Cx>::Input,
89        result: <Self::Cx as Cx>::Result,
90    ) -> bool;
91    fn on_stack_overflow(
92        cx: Self::Cx,
93        inspect: &mut Self::ProofTreeBuilder,
94        input: <Self::Cx as Cx>::Input,
95    ) -> <Self::Cx as Cx>::Result;
96    fn on_fixpoint_overflow(
97        cx: Self::Cx,
98        input: <Self::Cx as Cx>::Input,
99    ) -> <Self::Cx as Cx>::Result;
100
101    fn is_ambiguous_result(result: <Self::Cx as Cx>::Result) -> bool;
102    fn propagate_ambiguity(
103        cx: Self::Cx,
104        for_input: <Self::Cx as Cx>::Input,
105        from_result: <Self::Cx as Cx>::Result,
106    ) -> <Self::Cx as Cx>::Result;
107
108    fn step_is_coinductive(cx: Self::Cx, input: <Self::Cx as Cx>::Input) -> bool;
109}
110
111/// In the initial iteration of a cycle, we do not yet have a provisional
112/// result. In the case we return an initial provisional result depending
113/// on the kind of cycle.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum PathKind {
116    Coinductive,
117    Inductive,
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum UsageKind {
122    Single(PathKind),
123    Mixed,
124}
125impl UsageKind {
126    fn merge(self, other: Self) -> Self {
127        match (self, other) {
128            (UsageKind::Mixed, _) | (_, UsageKind::Mixed) => UsageKind::Mixed,
129            (UsageKind::Single(lhs), UsageKind::Single(rhs)) => {
130                if lhs == rhs {
131                    UsageKind::Single(lhs)
132                } else {
133                    UsageKind::Mixed
134                }
135            }
136        }
137    }
138    fn and_merge(&mut self, other: Self) {
139        *self = self.merge(other);
140    }
141}
142
143#[derive(Debug, Clone, Copy)]
144struct AvailableDepth(usize);
145impl AvailableDepth {
146    /// Returns the remaining depth allowed for nested goals.
147    ///
148    /// This is generally simply one less than the current depth.
149    /// However, if we encountered overflow, we significantly reduce
150    /// the remaining depth of all nested goals to prevent hangs
151    /// in case there is exponential blowup.
152    fn allowed_depth_for_nested<D: Delegate>(
153        root_depth: AvailableDepth,
154        stack: &IndexVec<StackDepth, StackEntry<D::Cx>>,
155    ) -> Option<AvailableDepth> {
156        if let Some(last) = stack.raw.last() {
157            if last.available_depth.0 == 0 {
158                return None;
159            }
160
161            Some(if last.encountered_overflow {
162                AvailableDepth(last.available_depth.0 / D::DIVIDE_AVAILABLE_DEPTH_ON_OVERFLOW)
163            } else {
164                AvailableDepth(last.available_depth.0 - 1)
165            })
166        } else {
167            Some(root_depth)
168        }
169    }
170
171    /// Whether we're allowed to use a global cache entry which required
172    /// the given depth.
173    fn cache_entry_is_applicable(self, additional_depth: usize) -> bool {
174        self.0 >= additional_depth
175    }
176}
177
178/// All cycle heads a given goal depends on, ordered by their stack depth.
179///
180/// We therefore pop the cycle heads from highest to lowest.
181#[derive(Clone, Debug, PartialEq, Eq, Default)]
182struct CycleHeads {
183    heads: BTreeSet<StackDepth>,
184}
185
186impl CycleHeads {
187    fn is_empty(&self) -> bool {
188        self.heads.is_empty()
189    }
190
191    fn highest_cycle_head(&self) -> StackDepth {
192        *self.heads.last().unwrap()
193    }
194
195    fn opt_highest_cycle_head(&self) -> Option<StackDepth> {
196        self.heads.last().copied()
197    }
198
199    fn opt_lowest_cycle_head(&self) -> Option<StackDepth> {
200        self.heads.first().copied()
201    }
202
203    fn remove_highest_cycle_head(&mut self) {
204        let last = self.heads.pop_last();
205        debug_assert_ne!(last, None);
206    }
207
208    fn insert(&mut self, head: StackDepth) {
209        self.heads.insert(head);
210    }
211
212    fn merge(&mut self, heads: &CycleHeads) {
213        for &head in heads.heads.iter() {
214            self.insert(head);
215        }
216    }
217
218    /// Update the cycle heads of a goal at depth `this` given the cycle heads
219    /// of a nested goal. This merges the heads after filtering the parent goal
220    /// itself.
221    fn extend_from_child(&mut self, this: StackDepth, child: &CycleHeads) {
222        for &head in child.heads.iter() {
223            match head.cmp(&this) {
224                Ordering::Less => {}
225                Ordering::Equal => continue,
226                Ordering::Greater => unreachable!(),
227            }
228
229            self.insert(head);
230        }
231    }
232}
233
234/// The nested goals of each stack entry and the path from the
235/// stack entry to that nested goal.
236///
237/// We only start tracking nested goals once we've either encountered
238/// overflow or a solver cycle. This is a performance optimization to
239/// avoid tracking nested goals on the happy path.
240///
241/// We use nested goals for two reasons:
242/// - when rebasing provisional cache entries
243/// - when checking whether we have to ignore a global cache entry as reevaluating
244///   it would encounter a cycle or use a provisional cache entry.
245///
246/// We need to disable the global cache if using it would hide a cycle, as
247/// cycles can impact behavior. The cycle ABA may have different final
248/// results from a the cycle BAB depending on the cycle root.
249#[derive_where(Debug, Default; X: Cx)]
250struct NestedGoals<X: Cx> {
251    nested_goals: HashMap<X::Input, UsageKind>,
252}
253impl<X: Cx> NestedGoals<X> {
254    fn is_empty(&self) -> bool {
255        self.nested_goals.is_empty()
256    }
257
258    fn insert(&mut self, input: X::Input, path_from_entry: UsageKind) {
259        self.nested_goals.entry(input).or_insert(path_from_entry).and_merge(path_from_entry);
260    }
261
262    fn merge(&mut self, nested_goals: &NestedGoals<X>) {
263        #[allow(rustc::potential_query_instability)]
264        for (input, path_from_entry) in nested_goals.iter() {
265            self.insert(input, path_from_entry);
266        }
267    }
268
269    /// Adds the nested goals of a nested goal, given that the path `step_kind` from this goal
270    /// to the parent goal.
271    ///
272    /// If the path from this goal to the nested goal is inductive, the paths from this goal
273    /// to all nested goals of that nested goal are also inductive. Otherwise the paths are
274    /// the same as for the child.
275    fn extend_from_child(&mut self, step_kind: PathKind, nested_goals: &NestedGoals<X>) {
276        #[allow(rustc::potential_query_instability)]
277        for (input, path_from_entry) in nested_goals.iter() {
278            let path_from_entry = match step_kind {
279                PathKind::Coinductive => path_from_entry,
280                PathKind::Inductive => UsageKind::Single(PathKind::Inductive),
281            };
282            self.insert(input, path_from_entry);
283        }
284    }
285
286    #[cfg_attr(feature = "nightly", rustc_lint_query_instability)]
287    #[allow(rustc::potential_query_instability)]
288    fn iter(&self) -> impl Iterator<Item = (X::Input, UsageKind)> + '_ {
289        self.nested_goals.iter().map(|(i, p)| (*i, *p))
290    }
291
292    fn get(&self, input: X::Input) -> Option<UsageKind> {
293        self.nested_goals.get(&input).copied()
294    }
295
296    fn contains(&self, input: X::Input) -> bool {
297        self.nested_goals.contains_key(&input)
298    }
299}
300
301rustc_index::newtype_index! {
302    #[orderable]
303    #[gate_rustc_only]
304    pub struct StackDepth {}
305}
306
307/// Stack entries of the evaluation stack. Its fields tend to be lazily
308/// when popping a child goal or completely immutable.
309#[derive_where(Debug; X: Cx)]
310struct StackEntry<X: Cx> {
311    input: X::Input,
312
313    /// The available depth of a given goal, immutable.
314    available_depth: AvailableDepth,
315
316    /// The maximum depth reached by this stack entry, only up-to date
317    /// for the top of the stack and lazily updated for the rest.
318    reached_depth: StackDepth,
319
320    /// All cycle heads this goal depends on. Lazily updated and only
321    /// up-to date for the top of the stack.
322    heads: CycleHeads,
323
324    /// Whether evaluating this goal encountered overflow. Lazily updated.
325    encountered_overflow: bool,
326
327    /// Whether this goal has been used as the root of a cycle. This gets
328    /// eagerly updated when encountering a cycle.
329    has_been_used: Option<UsageKind>,
330
331    /// The nested goals of this goal, see the doc comment of the type.
332    nested_goals: NestedGoals<X>,
333
334    /// Starts out as `None` and gets set when rerunning this
335    /// goal in case we encounter a cycle.
336    provisional_result: Option<X::Result>,
337}
338
339/// A provisional result of an already computed goals which depends on other
340/// goals still on the stack.
341#[derive_where(Debug; X: Cx)]
342struct ProvisionalCacheEntry<X: Cx> {
343    /// Whether evaluating the goal encountered overflow. This is used to
344    /// disable the cache entry except if the last goal on the stack is
345    /// already involved in this cycle.
346    encountered_overflow: bool,
347    /// All cycle heads this cache entry depends on.
348    heads: CycleHeads,
349    /// The path from the highest cycle head to this goal.
350    path_from_head: PathKind,
351    nested_goals: NestedGoals<X>,
352    result: X::Result,
353}
354
355pub struct SearchGraph<D: Delegate<Cx = X>, X: Cx = <D as Delegate>::Cx> {
356    root_depth: AvailableDepth,
357    /// The stack of goals currently being computed.
358    ///
359    /// An element is *deeper* in the stack if its index is *lower*.
360    stack: IndexVec<StackDepth, StackEntry<X>>,
361    /// The provisional cache contains entries for already computed goals which
362    /// still depend on goals higher-up in the stack. We don't move them to the
363    /// global cache and track them locally instead. A provisional cache entry
364    /// is only valid until the result of one of its cycle heads changes.
365    provisional_cache: HashMap<X::Input, Vec<ProvisionalCacheEntry<X>>>,
366
367    _marker: PhantomData<D>,
368}
369
370impl<D: Delegate<Cx = X>, X: Cx> SearchGraph<D> {
371    pub fn new(root_depth: usize) -> SearchGraph<D> {
372        Self {
373            root_depth: AvailableDepth(root_depth),
374            stack: Default::default(),
375            provisional_cache: Default::default(),
376            _marker: PhantomData,
377        }
378    }
379
380    /// Lazily update the stack entry for the parent goal.
381    /// This behavior is shared between actually evaluating goals
382    /// and using existing global cache entries to make sure they
383    /// have the same impact on the remaining evaluation.
384    fn update_parent_goal(
385        cx: X,
386        stack: &mut IndexVec<StackDepth, StackEntry<X>>,
387        reached_depth: StackDepth,
388        heads: &CycleHeads,
389        encountered_overflow: bool,
390        nested_goals: &NestedGoals<X>,
391    ) {
392        if let Some(parent_index) = stack.last_index() {
393            let parent = &mut stack[parent_index];
394            parent.reached_depth = parent.reached_depth.max(reached_depth);
395            parent.encountered_overflow |= encountered_overflow;
396
397            parent.heads.extend_from_child(parent_index, heads);
398            let step_kind = Self::step_kind(cx, parent.input);
399            parent.nested_goals.extend_from_child(step_kind, nested_goals);
400            // Once we've got goals which encountered overflow or a cycle,
401            // we track all goals whose behavior may depend depend on these
402            // goals as this change may cause them to now depend on additional
403            // goals, resulting in new cycles. See the dev-guide for examples.
404            if !nested_goals.is_empty() {
405                parent.nested_goals.insert(parent.input, UsageKind::Single(PathKind::Coinductive))
406            }
407        }
408    }
409
410    pub fn is_empty(&self) -> bool {
411        if self.stack.is_empty() {
412            debug_assert!(self.provisional_cache.is_empty());
413            true
414        } else {
415            false
416        }
417    }
418
419    /// The number of goals currently in the search graph. This should only be
420    /// used for debugging purposes.
421    pub fn debug_current_depth(&self) -> usize {
422        self.stack.len()
423    }
424
425    fn step_kind(cx: X, input: X::Input) -> PathKind {
426        if D::step_is_coinductive(cx, input) { PathKind::Coinductive } else { PathKind::Inductive }
427    }
428
429    /// Whether the path from `head` to the current stack entry is inductive or coinductive.
430    fn stack_path_kind(
431        cx: X,
432        stack: &IndexVec<StackDepth, StackEntry<X>>,
433        head: StackDepth,
434    ) -> PathKind {
435        if stack.raw[head.index()..].iter().all(|entry| D::step_is_coinductive(cx, entry.input)) {
436            PathKind::Coinductive
437        } else {
438            PathKind::Inductive
439        }
440    }
441
442    /// Probably the most involved method of the whole solver.
443    ///
444    /// Given some goal which is proven via the `prove_goal` closure, this
445    /// handles caching, overflow, and coinductive cycles.
446    pub fn with_new_goal(
447        &mut self,
448        cx: X,
449        input: X::Input,
450        inspect: &mut D::ProofTreeBuilder,
451        mut evaluate_goal: impl FnMut(&mut Self, &mut D::ProofTreeBuilder) -> X::Result,
452    ) -> X::Result {
453        let Some(available_depth) =
454            AvailableDepth::allowed_depth_for_nested::<D>(self.root_depth, &self.stack)
455        else {
456            return self.handle_overflow(cx, input, inspect);
457        };
458
459        // We check the provisional cache before checking the global cache. This simplifies
460        // the implementation as we can avoid worrying about cases where both the global and
461        // provisional cache may apply, e.g. consider the following example
462        //
463        // - xxBA overflow
464        // - A
465        //     - BA cycle
466        //     - CB :x:
467        if let Some(result) = self.lookup_provisional_cache(cx, input) {
468            return result;
469        }
470
471        // Lookup the global cache unless we're building proof trees or are currently
472        // fuzzing.
473        let validate_cache = if !D::inspect_is_noop(inspect) {
474            None
475        } else if let Some(scope) = D::enter_validation_scope(cx, input) {
476            // When validating the global cache we need to track the goals for which the
477            // global cache has been disabled as it may otherwise change the result for
478            // cyclic goals. We don't care about goals which are not on the current stack
479            // so it's fine to drop their scope eagerly.
480            self.lookup_global_cache_untracked(cx, input, available_depth)
481                .inspect(|expected| debug!(?expected, "validate cache entry"))
482                .map(|r| (scope, r))
483        } else if let Some(result) = self.lookup_global_cache(cx, input, available_depth) {
484            return result;
485        } else {
486            None
487        };
488
489        // Detect cycles on the stack. We do this after the global cache lookup to
490        // avoid iterating over the stack in case a goal has already been computed.
491        // This may not have an actual performance impact and we could reorder them
492        // as it may reduce the number of `nested_goals` we need to track.
493        if let Some(result) = self.check_cycle_on_stack(cx, input) {
494            debug_assert!(validate_cache.is_none(), "global cache and cycle on stack");
495            return result;
496        }
497
498        // Unfortunate, it looks like we actually have to compute this goalrar.
499        let depth = self.stack.next_index();
500        let entry = StackEntry {
501            input,
502            available_depth,
503            reached_depth: depth,
504            heads: Default::default(),
505            encountered_overflow: false,
506            has_been_used: None,
507            nested_goals: Default::default(),
508            provisional_result: None,
509        };
510        assert_eq!(self.stack.push(entry), depth);
511
512        // This is for global caching, so we properly track query dependencies.
513        // Everything that affects the `result` should be performed within this
514        // `with_cached_task` closure. If computing this goal depends on something
515        // not tracked by the cache key and from outside of this anon task, it
516        // must not be added to the global cache. Notably, this is the case for
517        // trait solver cycles participants.
518        let ((final_entry, result), dep_node) = cx.with_cached_task(|| {
519            self.evaluate_goal_in_task(cx, input, inspect, &mut evaluate_goal)
520        });
521
522        // We've finished computing the goal and have popped it from the stack,
523        // lazily update its parent goal.
524        Self::update_parent_goal(
525            cx,
526            &mut self.stack,
527            final_entry.reached_depth,
528            &final_entry.heads,
529            final_entry.encountered_overflow,
530            &final_entry.nested_goals,
531        );
532
533        // We're now done with this goal. We only add the root of cycles to the global cache.
534        // In case this goal is involved in a larger cycle add it to the provisional cache.
535        if final_entry.heads.is_empty() {
536            if let Some((_scope, expected)) = validate_cache {
537                // Do not try to move a goal into the cache again if we're testing
538                // the global cache.
539                assert_eq!(result, expected, "input={input:?}");
540            } else if D::inspect_is_noop(inspect) {
541                self.insert_global_cache(cx, input, final_entry, result, dep_node)
542            }
543        } else if D::ENABLE_PROVISIONAL_CACHE {
544            debug_assert!(validate_cache.is_none());
545            let entry = self.provisional_cache.entry(input).or_default();
546            let StackEntry { heads, nested_goals, encountered_overflow, .. } = final_entry;
547            let path_from_head = Self::stack_path_kind(cx, &self.stack, heads.highest_cycle_head());
548            entry.push(ProvisionalCacheEntry {
549                encountered_overflow,
550                heads,
551                path_from_head,
552                nested_goals,
553                result,
554            });
555        } else {
556            debug_assert!(validate_cache.is_none());
557        }
558
559        result
560    }
561
562    fn handle_overflow(
563        &mut self,
564        cx: X,
565        input: X::Input,
566        inspect: &mut D::ProofTreeBuilder,
567    ) -> X::Result {
568        if let Some(last) = self.stack.raw.last_mut() {
569            last.encountered_overflow = true;
570            // If computing a goal `B` depends on another goal `A` and
571            // `A` has a nested goal which overflows, then computing `B`
572            // at the same depth, but with `A` already on the stack,
573            // would encounter a solver cycle instead, potentially
574            // changing the result.
575            //
576            // We must therefore not use the global cache entry for `B` in that case.
577            // See tests/ui/traits/next-solver/cycles/hidden-by-overflow.rs
578            last.nested_goals.insert(last.input, UsageKind::Single(PathKind::Coinductive));
579        }
580
581        debug!("encountered stack overflow");
582        D::on_stack_overflow(cx, inspect, input)
583    }
584
585    /// When reevaluating a goal with a changed provisional result, all provisional cache entry
586    /// which depend on this goal get invalidated.
587    fn clear_dependent_provisional_results(&mut self) {
588        let head = self.stack.next_index();
589        #[allow(rustc::potential_query_instability)]
590        self.provisional_cache.retain(|_, entries| {
591            entries.retain(|entry| entry.heads.highest_cycle_head() != head);
592            !entries.is_empty()
593        });
594    }
595
596    /// A necessary optimization to handle complex solver cycles. A provisional cache entry
597    /// relies on a set of cycle heads and the path towards these heads. When popping a cycle
598    /// head from the stack after we've finished computing it, we can't be sure that the
599    /// provisional cache entry is still applicable. We need to keep the cache entries to
600    /// prevent hangs.
601    ///
602    /// What we therefore do is check whether the cycle kind of all cycles the goal of a
603    /// provisional cache entry is involved in would stay the same when computing the
604    /// goal without its cycle head on the stack. For more details, see the relevant
605    /// [rustc-dev-guide chapter](https://rustc-dev-guide.rust-lang.org/solve/caching.html).
606    ///
607    /// This can be thought of rotating the sub-tree of this provisional result and changing
608    /// its entry point while making sure that all paths through this sub-tree stay the same.
609    ///
610    ///
611    /// In case the popped cycle head failed to reach a fixpoint anything which depends on
612    /// its provisional result is invalid. Actually discarding provisional cache entries in
613    /// this case would cause hangs, so we instead change the result of dependant provisional
614    /// cache entries to also be ambiguous. This causes some undesirable ambiguity for nested
615    /// goals whose result doesn't actually depend on this cycle head, but that's acceptable
616    /// to me.
617    fn rebase_provisional_cache_entries(
618        &mut self,
619        cx: X,
620        stack_entry: &StackEntry<X>,
621        mut mutate_result: impl FnMut(X::Input, X::Result) -> X::Result,
622    ) {
623        let head = self.stack.next_index();
624        #[allow(rustc::potential_query_instability)]
625        self.provisional_cache.retain(|&input, entries| {
626            entries.retain_mut(|entry| {
627                let ProvisionalCacheEntry {
628                    encountered_overflow: _,
629                    heads,
630                    path_from_head,
631                    nested_goals,
632                    result,
633                } = entry;
634                if heads.highest_cycle_head() != head {
635                    return true;
636                }
637
638                // We don't try rebasing if the path from the current head
639                // to the cache entry is not coinductive or if the path from
640                // the cache entry to the current head is not coinductive.
641                //
642                // Both of these constraints could be weakened, but by only
643                // accepting coinductive paths we don't have to worry about
644                // changing the cycle kind of the remaining cycles. We can
645                // extend this in the future once there's a known issue
646                // caused by it.
647                if *path_from_head != PathKind::Coinductive
648                    || nested_goals.get(stack_entry.input).unwrap()
649                        != UsageKind::Single(PathKind::Coinductive)
650                {
651                    return false;
652                }
653
654                // Merge the cycle heads of the provisional cache entry and the
655                // popped head. If the popped cycle head was a root, discard all
656                // provisional cache entries which depend on it.
657                heads.remove_highest_cycle_head();
658                heads.merge(&stack_entry.heads);
659                let Some(head) = heads.opt_highest_cycle_head() else {
660                    return false;
661                };
662
663                // As we've made sure that the path from the new highest cycle
664                // head to the uses of the popped cycle head are fully coinductive,
665                // we can be sure that the paths to all nested goals of the popped
666                // cycle head remain the same. We can simply merge them.
667                nested_goals.merge(&stack_entry.nested_goals);
668                // We now care about the path from the next highest cycle head to the
669                // provisional cache entry.
670                *path_from_head = Self::stack_path_kind(cx, &self.stack, head);
671                // Mutate the result of the provisional cache entry in case we did
672                // not reach a fixpoint.
673                *result = mutate_result(input, *result);
674                true
675            });
676            !entries.is_empty()
677        });
678    }
679
680    fn lookup_provisional_cache(&mut self, cx: X, input: X::Input) -> Option<X::Result> {
681        if !D::ENABLE_PROVISIONAL_CACHE {
682            return None;
683        }
684
685        let entries = self.provisional_cache.get(&input)?;
686        for &ProvisionalCacheEntry {
687            encountered_overflow,
688            ref heads,
689            path_from_head,
690            ref nested_goals,
691            result,
692        } in entries
693        {
694            let head = heads.highest_cycle_head();
695            if encountered_overflow {
696                // This check is overly strict and very subtle. We need to make sure that if
697                // a global cache entry depends on some goal without adding it to its
698                // `nested_goals`, that goal must never have an applicable provisional
699                // cache entry to avoid incorrectly applying the cache entry.
700                //
701                // As we'd have to otherwise track literally all nested goals, we only
702                // apply provisional cache entries which encountered overflow once the
703                // current goal is already part of the same cycle. This check could be
704                // improved but seems to be good enough for now.
705                let last = self.stack.raw.last().unwrap();
706                if last.heads.opt_lowest_cycle_head().is_none_or(|lowest| lowest > head) {
707                    continue;
708                }
709            }
710
711            // A provisional cache entry is only valid if the current path from its
712            // highest cycle head to the goal is the same.
713            if path_from_head == Self::stack_path_kind(cx, &self.stack, head) {
714                // While we don't have to track the full depth of the provisional cache entry,
715                // we do have to increment the required depth by one as we'd have already failed
716                // with overflow otherwise
717                let next_index = self.stack.next_index();
718                let last = &mut self.stack.raw.last_mut().unwrap();
719                let path_from_entry = Self::step_kind(cx, last.input);
720                last.nested_goals.insert(input, UsageKind::Single(path_from_entry));
721
722                Self::update_parent_goal(
723                    cx,
724                    &mut self.stack,
725                    next_index,
726                    heads,
727                    false,
728                    nested_goals,
729                );
730                debug_assert!(self.stack[head].has_been_used.is_some());
731                debug!(?head, ?path_from_head, "provisional cache hit");
732                return Some(result);
733            }
734        }
735
736        None
737    }
738
739    /// Even if there is a global cache entry for a given goal, we need to make sure
740    /// evaluating this entry would not have ended up depending on either a goal
741    /// already on the stack or a provisional cache entry.
742    fn candidate_is_applicable(
743        cx: X,
744        stack: &IndexVec<StackDepth, StackEntry<X>>,
745        provisional_cache: &HashMap<X::Input, Vec<ProvisionalCacheEntry<X>>>,
746        nested_goals: &NestedGoals<X>,
747    ) -> bool {
748        // If the global cache entry didn't depend on any nested goals, it always
749        // applies.
750        if nested_goals.is_empty() {
751            return true;
752        }
753
754        // If a nested goal of the global cache entry is on the stack, we would
755        // definitely encounter a cycle.
756        if stack.iter().any(|e| nested_goals.contains(e.input)) {
757            debug!("cache entry not applicable due to stack");
758            return false;
759        }
760
761        // The global cache entry is also invalid if there's a provisional cache entry
762        // would apply for any of its nested goals.
763        #[allow(rustc::potential_query_instability)]
764        for (input, path_from_global_entry) in nested_goals.iter() {
765            let Some(entries) = provisional_cache.get(&input) else {
766                continue;
767            };
768
769            debug!(?input, ?path_from_global_entry, ?entries, "candidate_is_applicable");
770            // A provisional cache entry is applicable if the path to
771            // its highest cycle head is equal to the expected path.
772            for &ProvisionalCacheEntry {
773                encountered_overflow,
774                ref heads,
775                path_from_head,
776                nested_goals: _,
777                result: _,
778            } in entries.iter()
779            {
780                // We don't have to worry about provisional cache entries which encountered
781                // overflow, see the relevant comment in `lookup_provisional_cache`.
782                if encountered_overflow {
783                    continue;
784                }
785
786                // A provisional cache entry only applies if the path from its highest head
787                // matches the path when encountering the goal.
788                let head = heads.highest_cycle_head();
789                let full_path = match Self::stack_path_kind(cx, stack, head) {
790                    PathKind::Coinductive => path_from_global_entry,
791                    PathKind::Inductive => UsageKind::Single(PathKind::Inductive),
792                };
793
794                match (full_path, path_from_head) {
795                    (UsageKind::Mixed, _)
796                    | (UsageKind::Single(PathKind::Coinductive), PathKind::Coinductive)
797                    | (UsageKind::Single(PathKind::Inductive), PathKind::Inductive) => {
798                        debug!(
799                            ?full_path,
800                            ?path_from_head,
801                            "cache entry not applicable due to matching paths"
802                        );
803                        return false;
804                    }
805                    _ => debug!(?full_path, ?path_from_head, "paths don't match"),
806                }
807            }
808        }
809
810        true
811    }
812
813    /// Used when fuzzing the global cache. Accesses the global cache without
814    /// updating the state of the search graph.
815    fn lookup_global_cache_untracked(
816        &self,
817        cx: X,
818        input: X::Input,
819        available_depth: AvailableDepth,
820    ) -> Option<X::Result> {
821        cx.with_global_cache(|cache| {
822            cache
823                .get(cx, input, available_depth, |nested_goals| {
824                    Self::candidate_is_applicable(
825                        cx,
826                        &self.stack,
827                        &self.provisional_cache,
828                        nested_goals,
829                    )
830                })
831                .map(|c| c.result)
832        })
833    }
834
835    /// Try to fetch a previously computed result from the global cache,
836    /// making sure to only do so if it would match the result of reevaluating
837    /// this goal.
838    fn lookup_global_cache(
839        &mut self,
840        cx: X,
841        input: X::Input,
842        available_depth: AvailableDepth,
843    ) -> Option<X::Result> {
844        cx.with_global_cache(|cache| {
845            let CacheData { result, additional_depth, encountered_overflow, nested_goals } = cache
846                .get(cx, input, available_depth, |nested_goals| {
847                    Self::candidate_is_applicable(
848                        cx,
849                        &self.stack,
850                        &self.provisional_cache,
851                        nested_goals,
852                    )
853                })?;
854
855            // Update the reached depth of the current goal to make sure
856            // its state is the same regardless of whether we've used the
857            // global cache or not.
858            let reached_depth = self.stack.next_index().plus(additional_depth);
859            // We don't move cycle participants to the global cache, so the
860            // cycle heads are always empty.
861            let heads = Default::default();
862            Self::update_parent_goal(
863                cx,
864                &mut self.stack,
865                reached_depth,
866                &heads,
867                encountered_overflow,
868                nested_goals,
869            );
870
871            debug!(?additional_depth, "global cache hit");
872            Some(result)
873        })
874    }
875
876    fn check_cycle_on_stack(&mut self, cx: X, input: X::Input) -> Option<X::Result> {
877        let (head, _stack_entry) = self.stack.iter_enumerated().find(|(_, e)| e.input == input)?;
878        debug!("encountered cycle with depth {head:?}");
879        // We have a nested goal which directly relies on a goal deeper in the stack.
880        //
881        // We start by tagging all cycle participants, as that's necessary for caching.
882        //
883        // Finally we can return either the provisional response or the initial response
884        // in case we're in the first fixpoint iteration for this goal.
885        let path_kind = Self::stack_path_kind(cx, &self.stack, head);
886        let usage_kind = UsageKind::Single(path_kind);
887        self.stack[head].has_been_used =
888            Some(self.stack[head].has_been_used.map_or(usage_kind, |prev| prev.merge(usage_kind)));
889
890        // Subtle: when encountering a cyclic goal, we still first checked for overflow,
891        // so we have to update the reached depth.
892        let next_index = self.stack.next_index();
893        let last_index = self.stack.last_index().unwrap();
894        let last = &mut self.stack[last_index];
895        last.reached_depth = last.reached_depth.max(next_index);
896
897        let path_from_entry = Self::step_kind(cx, last.input);
898        last.nested_goals.insert(input, UsageKind::Single(path_from_entry));
899        last.nested_goals.insert(last.input, UsageKind::Single(PathKind::Coinductive));
900        if last_index != head {
901            last.heads.insert(head);
902        }
903
904        // Return the provisional result or, if we're in the first iteration,
905        // start with no constraints.
906        if let Some(result) = self.stack[head].provisional_result {
907            Some(result)
908        } else {
909            Some(D::initial_provisional_result(cx, path_kind, input))
910        }
911    }
912
913    /// Whether we've reached a fixpoint when evaluating a cycle head.
914    fn reached_fixpoint(
915        &mut self,
916        cx: X,
917        stack_entry: &StackEntry<X>,
918        usage_kind: UsageKind,
919        result: X::Result,
920    ) -> bool {
921        if let Some(prev) = stack_entry.provisional_result {
922            prev == result
923        } else if let UsageKind::Single(kind) = usage_kind {
924            D::is_initial_provisional_result(cx, kind, stack_entry.input, result)
925        } else {
926            false
927        }
928    }
929
930    /// When we encounter a coinductive cycle, we have to fetch the
931    /// result of that cycle while we are still computing it. Because
932    /// of this we continuously recompute the cycle until the result
933    /// of the previous iteration is equal to the final result, at which
934    /// point we are done.
935    fn evaluate_goal_in_task(
936        &mut self,
937        cx: X,
938        input: X::Input,
939        inspect: &mut D::ProofTreeBuilder,
940        mut evaluate_goal: impl FnMut(&mut Self, &mut D::ProofTreeBuilder) -> X::Result,
941    ) -> (StackEntry<X>, X::Result) {
942        let mut i = 0;
943        loop {
944            let result = evaluate_goal(self, inspect);
945            let stack_entry = self.stack.pop().unwrap();
946            debug_assert_eq!(stack_entry.input, input);
947
948            // If the current goal is not the root of a cycle, we are done.
949            //
950            // There are no provisional cache entries which depend on this goal.
951            let Some(usage_kind) = stack_entry.has_been_used else {
952                return (stack_entry, result);
953            };
954
955            // If it is a cycle head, we have to keep trying to prove it until
956            // we reach a fixpoint. We need to do so for all cycle heads,
957            // not only for the root.
958            //
959            // See tests/ui/traits/next-solver/cycles/fixpoint-rerun-all-cycle-heads.rs
960            // for an example.
961            //
962            // Check whether we reached a fixpoint, either because the final result
963            // is equal to the provisional result of the previous iteration, or because
964            // this was only the root of either coinductive or inductive cycles, and the
965            // final result is equal to the initial response for that case.
966            if self.reached_fixpoint(cx, &stack_entry, usage_kind, result) {
967                self.rebase_provisional_cache_entries(cx, &stack_entry, |_, result| result);
968                return (stack_entry, result);
969            }
970
971            // If computing this goal results in ambiguity with no constraints,
972            // we do not rerun it. It's incredibly difficult to get a different
973            // response in the next iteration in this case. These changes would
974            // likely either be caused by incompleteness or can change the maybe
975            // cause from ambiguity to overflow. Returning ambiguity always
976            // preserves soundness and completeness even if the goal is be known
977            // to succeed or fail.
978            //
979            // This prevents exponential blowup affecting multiple major crates.
980            // As we only get to this branch if we haven't yet reached a fixpoint,
981            // we also taint all provisional cache entries which depend on the
982            // current goal.
983            if D::is_ambiguous_result(result) {
984                self.rebase_provisional_cache_entries(cx, &stack_entry, |input, _| {
985                    D::propagate_ambiguity(cx, input, result)
986                });
987                return (stack_entry, result);
988            };
989
990            // If we've reached the fixpoint step limit, we bail with overflow and taint all
991            // provisional cache entries which depend on the current goal.
992            i += 1;
993            if i >= D::FIXPOINT_STEP_LIMIT {
994                debug!("canonical cycle overflow");
995                let result = D::on_fixpoint_overflow(cx, input);
996                self.rebase_provisional_cache_entries(cx, &stack_entry, |input, _| {
997                    D::on_fixpoint_overflow(cx, input)
998                });
999                return (stack_entry, result);
1000            }
1001
1002            // Clear all provisional cache entries which depend on a previous provisional
1003            // result of this goal and rerun.
1004            self.clear_dependent_provisional_results();
1005
1006            debug!(?result, "fixpoint changed provisional results");
1007            self.stack.push(StackEntry {
1008                has_been_used: None,
1009                provisional_result: Some(result),
1010                ..stack_entry
1011            });
1012        }
1013    }
1014
1015    /// When encountering a cycle, both inductive and coinductive, we only
1016    /// move the root into the global cache. We also store all other cycle
1017    /// participants involved.
1018    ///
1019    /// We must not use the global cache entry of a root goal if a cycle
1020    /// participant is on the stack. This is necessary to prevent unstable
1021    /// results. See the comment of `StackEntry::nested_goals` for
1022    /// more details.
1023    fn insert_global_cache(
1024        &mut self,
1025        cx: X,
1026        input: X::Input,
1027        final_entry: StackEntry<X>,
1028        result: X::Result,
1029        dep_node: X::DepNodeIndex,
1030    ) {
1031        let additional_depth = final_entry.reached_depth.as_usize() - self.stack.len();
1032        debug!(?final_entry, ?result, "insert global cache");
1033        cx.with_global_cache(|cache| {
1034            cache.insert(
1035                cx,
1036                input,
1037                result,
1038                dep_node,
1039                additional_depth,
1040                final_entry.encountered_overflow,
1041                final_entry.nested_goals,
1042            )
1043        })
1044    }
1045}