Skip to content

Avoid TrustedLen specialization that optimize poorly in collect_remaining_errors - #160073

Open
panstromek wants to merge 1 commit into
rust-lang:mainfrom
panstromek:avoid-trusted-len-thin-vec
Open

Avoid TrustedLen specialization that optimize poorly in collect_remaining_errors#160073
panstromek wants to merge 1 commit into
rust-lang:mainfrom
panstromek:avoid-trusted-len-thin-vec

Conversation

@panstromek

@panstromek panstromek commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor Author

@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 28, 2026
@rust-bors

This comment has been minimized.

rust-bors Bot pushed a commit that referenced this pull request Jul 28, 2026
Avoid TrustedLen specialization that optimize poorly in collect_remaining_errors
@rust-bors

rust-bors Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

☀️ Try build successful (CI)
Build commit: 4bd0be6 (4bd0be6d9bb9580aab29eed8cfcd3ba5e095d874)
Base parent: e19d321 (e19d321c06479c6fd77533582b0d5a86651f1be3)

@rust-timer

This comment has been minimized.

@rust-timer

Copy link
Copy Markdown
Collaborator

Finished benchmarking commit (4bd0be6): comparison URL.

Overall result: ❌✅ regressions and improvements - please read:

Benchmarking means the PR may be perf-sensitive. It's automatically marked not fit for rolling up. Overriding is possible but disadvised: it risks changing compiler perf.

Next, please: If you can, justify the regressions found in this try perf run in writing along with @rustbot label: +perf-regression-triaged. If not, fix the regressions and do another perf run. Neutral or positive results will clear the label automatically.

@bors rollup=never rustc-perf
@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.1% [0.1%, 0.1%] 3
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-0.5% [-2.6%, -0.1%] 19
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (primary -1.1%, secondary -2.9%)

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)
-1.1% [-1.1%, -1.1%] 1
Improvements ✅
(secondary)
-2.9% [-5.7%, -0.8%] 3
All ❌✅ (primary) -1.1% [-1.1%, -1.1%] 1

Cycles

Results (primary -1.5%, secondary -2.4%)

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)
3.3% [3.0%, 3.6%] 2
Improvements ✅
(primary)
-1.5% [-1.5%, -1.5%] 1
Improvements ✅
(secondary)
-4.1% [-6.2%, -2.4%] 7
All ❌✅ (primary) -1.5% [-1.5%, -1.5%] 1

Binary size

Results (secondary -0.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)
- - 0
Improvements ✅
(secondary)
-0.0% [-0.0%, -0.0%] 1
All ❌✅ (primary) - - 0

Bootstrap: 490.165s -> 488.452s (-0.35%)
Artifact size: 388.34 MiB -> 390.43 MiB (0.54%)

@rustbot rustbot added perf-regression Performance regression. and removed S-waiting-on-perf Status: Waiting on a perf run to be completed. labels Jul 28, 2026
@panstromek

Copy link
Copy Markdown
Contributor Author

Yea, the issue is still there even after #160005.

r? @nnethercote

Atm I don't know if we will be able to fix the TrustedLen specialization problem in general some time soon. This workaround is a bit funky, but it works for this case and it doesn't seem like we hit this issue in many other places in the compiler anyway.

@panstromek
panstromek marked this pull request as ready for review July 28, 2026 16:10
@rustbot

rustbot commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Some changes occurred to the core trait solver

cc @rust-lang/initiative-trait-system-refactor

@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 28, 2026
@lqd

lqd commented Jul 28, 2026

Copy link
Copy Markdown
Member

Is this an error codepath? Why are we hitting it that much in the benchmarks?

@Kobzol

Kobzol commented Jul 28, 2026

Copy link
Copy Markdown
Member

Probably because our benchmarks are relatively old crates (anything gets old quickly in Rust unless you regularly update it), and they are generating thousands of warnings, FCWs, etc.

Edit: wait, this looks like an actual trait error codepath? Not sure if that is relevant to what I wrote above; if not, then nevermind.

@lqd

lqd commented Jul 28, 2026

Copy link
Copy Markdown
Member

It seems that way although I haven't checked. But if there's anything in there it looks like a bad time heh. I'm mostly pointing this out so we know what we're optimizing, if it's worth it, and the opposite (the regressions we could sometimes ignore in the other PRs working with ThinVec).

@panstromek

Copy link
Copy Markdown
Contributor Author

I'm not sure, I assumed it's one of those things where we try to solve something multiple ways until it succeeds, so the error happens as a part of normal execution path.

But if the list is always empty, then it'd kinda make sense that an iterator that doesn't look at size_hint and just calls next a single time and return empty vec would maybe optimize better?

@panstromek

Copy link
Copy Markdown
Contributor Author

It is indeed almost always empty, but sometimes not:

$ cat results/eprintln-Id-syn-2.0.101-new-solver-Check-Full | sort | uniq -c | sort -n 
    182 collect_remaining_errors: len=1
1057538 collect_remaining_errors: len=0

@Kobzol

Kobzol commented Jul 28, 2026

Copy link
Copy Markdown
Member

Maybe the size hint is set based on capacity or something? That is weird, I would expect that if the input Vec is empty, then the size hint will also be set to 0.

Anyway, maybe instead of the skip(0) magic, creating an empty vec and then iterating through the input obligations and pushing to the Vec would be easier to understand? With a comment that says that we don't want to allocate the vector there unnecesarily, because it is usually empty.

@the8472

the8472 commented Jul 28, 2026

Copy link
Copy Markdown
Member

But if the list is always empty, then it'd kinda make sense that an iterator that doesn't look at size_hint and just calls next a single time and return empty vec would maybe optimize better?

Maybe. Trustedlen is, well, trusted, so perhaps we can shortcircuit on 0 there too. OTOH that's an extra branch, so it'll need benchmarking.

@panstromek

panstromek commented Jul 28, 2026

Copy link
Copy Markdown
Contributor Author

Maybe the size hint is set based on capacity or something

It should be exactly the length of the iterator (and therefore vec.len()), that's the contract of TrustedLen.

But to clarify what I was talking about, the non-specialized impl first calls next() and early returns Vec::new() for None case, while the specialized impl first calls size_hint, then Vec::with_capacity(..), then SpecExtend::extend, which calls the size_hint() again and then a bunch more setup before it delegates to iter.for_each(). That's a bunch more code to churn through in the empty case (at least by vočko).

They are right next to each other here: https://github.com/rust-lang/rust/blob/main/library/alloc/src/vec/spec_from_iter_nested.rs

But yea, I might actually just add if len == 0 check at the start of collect_remaining_errors and outline the rest, that might be better than doing anything fancy.

@the8472

the8472 commented Jul 28, 2026

Copy link
Copy Markdown
Member

They are right next to each other here:

Heh, yes and no. Those are the FromIterator entrypoints, which then delegates two its another maze of Extend specializations, which bottom out here, also next to each other:

fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
// This is the case for a general iterator.
//
// This function should be the moral equivalent of:
//
// for item in iterator {
// self.push(item);
// }
while let Some(element) = iterator.next() {
let len = self.len();
if len == self.capacity() {
let (lower, _) = iterator.size_hint();
self.reserve(lower.saturating_add(1));
}
unsafe {
ptr::write(self.as_mut_ptr().add(len), element);
// Since next() executes user code which can panic we have to bump the length
// after each step.
// NB can't overflow since we would have had to alloc the address space
self.set_len(len + 1);
}
}
}
// specific extend for `TrustedLen` iterators, called both by the specializations
// and internal places where resolving specialization makes compilation slower
#[cfg(not(no_global_oom_handling))]
fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
let (low, high) = iterator.size_hint();
if let Some(additional) = high {
debug_assert_eq!(
low,
additional,
"TrustedLen iterator's size hint is not exact: {:?}",
(low, high)
);
self.reserve(additional);
unsafe {
let ptr = self.as_mut_ptr();
let mut local_len = SetLenOnDrop::new(&mut self.len);
iterator.for_each(move |element| {
ptr::write(ptr.add(local_len.current_len()), element);
// Since the loop executes user code which can panic we have to update
// the length every step to correctly drop what we've written.
// NB can't overflow since we would have had to alloc the address space
local_len.increment_len(1);
});
}
} else {
// Per TrustedLen contract a `None` upper bound means that the iterator length
// truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
// Since the other branch already panics eagerly (via `reserve()`) we do the same here.
// This avoids additional codegen for a fallback code path which would eventually
// panic anyway.
panic!("capacity overflow");
}
}

@nnethercote nnethercote 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.

I'm fine with the skip(0), it's very simple and works well and the comment explains it.

r=me with the comment changes below.

View changes since this review

Comment thread compiler/rustc_trait_selection/src/solve/fulfill.rs Outdated
@nnethercote

Copy link
Copy Markdown
Contributor

(at least by vočko)

What does this mean? Google didn't give me any answers that seem relevant :)

@panstromek

Copy link
Copy Markdown
Contributor Author

Sorry, it means something like "guess from cursory look." or a "guesstimate." Vočko means something like a squinting eye.

@panstromek
panstromek force-pushed the avoid-trusted-len-thin-vec branch from 53b006c to 51752f0 Compare July 28, 2026 22:59
@panstromek

Copy link
Copy Markdown
Contributor Author

Thanks. I addressed the nits but I don't have r+ rights.

@nnethercote

Copy link
Copy Markdown
Contributor

@bors r+

@rust-bors

rust-bors Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

📌 Commit 51752f0 has been approved by nnethercote

It is now in the queue for this repository.

@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-review Status: Awaiting review from the assignee but also interested parties. labels Jul 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

perf-regression Performance regression. 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. 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.

7 participants