180 points · by muglug · 2y ago · 122 comments
In v1 you put in 128 containers is with each 1024 boxes.
Then v2 is taking out the first box out of each container, tossing the container and putting the box at the space where the container was, packing them.
The fact that capacity doubles when you remove the as u8 is... normal. You reuse the space, so you can fix 2u8 in the space of 1u16.
The problem here is more that this the optimization causes a Vec<T> -> Vec<Y> where sizeof(T) > sizeof(Y) to have much more capacity than expected.
Which IS a valid bug report. Bug again, not a memory leak.
Memory leak: classical C style, fully lost in memgrind (runtime bug) Space leak: Some memory structure requires significantly more memory than it should. E.g. keeping a (lazy) ref to a large blob, around that keeps it in memory.
The effect is largely the same, but the latter is almost harder to spot, since the tooling cannot be as general as memgrind.
Honestly, if I had 300k Vecs, I would call `shrink_to_fit` even without that optimization.
1: Since the edge list calculation logic is run for one node at a time in sequence, the fact that it temporarily uses 132kb of memory would normally not be a problem at all. However, the new collect() optimization meant that that internal storage was being preserved in the final vec which got inserted into the list of edge lists, thus keeping around that 132kb of obsolete memory forever. Multiply that by 300k nodes and suddenly you’ve leaked the computer’s entire RAM.
It is indeed a bit surprising, but seems entirely reasonable for the platform to do imo. It's efficient, in both memory (allocation) and CPU. If you want a specifically-sized container, you have to make sure that happens, otherwise you're letting things be optimized in language-general ways. That will frequently be wrong in edge cases, and may change at any time.
But it's 200x.
Right?
fn dbg_vec<T>(v: &Vec<T>) {
println!(
"vec data ptr={:?} len={} cap={}",
v.as_ptr(),
v.len(),
v.capacity()
);
}
fn main() {
{
let v1 = (0u16..128).map(|i| [i; 1024]).collect::<Vec<_>>();
dbg_vec(&v1);
let v2 = v1.into_iter().map(|x| x[0] as u8).collect::<Vec<_>>();
dbg_vec(&v2);
}
{
let v1 = (0u16..128).map(|i| [i; 1024]).collect::<Vec<_>>();
dbg_vec(&v1);
let v2 = v1.into_iter().map(|x| x[0]).collect::<Vec<_>>();
dbg_vec(&v2);
}
}
# cargo +nightly clean
Removed 11 files, 7.3MiB total
# cargo +nightly run --release
Compiling vec-debug v0.1.0 (/home/neo/vec-debug)
Finished release [optimized] target(s) in 0.17s
Running `target/release/vec-debug`
vec data ptr=0x7f47ee162010 len=128 cap=128
vec data ptr=0x7f47ee121010 len=128 cap=262144
vec data ptr=0x55c6514f3ba0 len=128 cap=128
vec data ptr=0x55c6514f3ba0 len=128 cap=131072
What happens is that the original's vectors assigned space gets reused. That's it.It LOOKS like there is more because the capacity inflates. But capacity is written in terms of sizeof(T), not bits
(0u16..128).map(|i| [i; 1024]).collect::<Vec<_>>()
the capacity (and length) is 128 times an array of 1024 of a u16. We then re-use the same underlying array which has a CAPACITY of 128 times (1024 * 16) and put in a u8 (the cast). So each item went from 1024 * 16 to 8.So previously we had 128 * 1024 * 16 = 2,097,152 bits.
How many times can we put 8 bits in a capacity of 2,097,152 bits?
262,144
How many times can we put 16 bits in a capacity of 2,097,152 bits?
131,072
However, the semantic distinction between "this uses much more memory than expected" and "this is a memory leak" is a little subtle, and it seems pretty rude to call it clickbait.
> the memory waste from excess capacity should always be at most 2x, but I was seeing over 200x.
So the 200x analysis is his problem?
Someone already filed this as a bug: https://github.com/rust-lang/rust/issues/120091
The issue is more about reusing memory that has been allocated when you "convert" (in Rust term: into_iter()) a Vec to another Vec. More surprisingly, the reuse still happens even when the new Vec has a different type than the original Vec's type. You should read the whole post—it's more interesting than I (and you) thought.
In the Haskell world, "space leak" is used to refer to a lazy computation that overallocates because of laziness (classic example being the difference between foldl and foldr or maybe that's foldl' and foldr'--I forget some details/cannot be bothered to think about folds right now).
I've personally stolen the terminology for a computation that temporarily holds on to a bunch of unneeded memory.
Whether you call that a leak or not, Rust is known for its predictability. Allocating 200x the memory which a programmer would expect if he doesn't know the implementation details is bad.
Coming from my java days, they called this a memory leak there too.
It’s definitely a more inappropriate term in rust, where memory leak has a definite meaning already.
It's something you should expect to be able to try to do. The underlying allocator may reject the request depending on context (maybe it is works for large sizes only, for example). This is provided by Rust's Allocator trait realloc_in_place() API, which returns CannotReallocInPlace if it isn't possible.
For Vec::collect, in the event that the storage cannot be reused smaller in place, I think it would be reasonable to free it and allocate an appropriately sized buffer instead.
This optimisation crosses the line into "too clever by half". Once a Rust programmers groks how Vec's work their mental model of how capacity is allocated simple, so simple they hardly need thing about it's implications as they write code. This optimisation breaks that simple model badly, and you would have to be really focused to realise it's about to bite you as the code streams off your finger tips. Consequently this "optimisation" is almost certainly going to cause a lot of code to using far more memory than expected.
You get the same results with filter():
let mut v = vec![1,2,3];
v.push(4);
println!("len {} cap {}", v.len(), v.capacity());
let v = v.into_iter().map(|x| x+1).filter(|_x| false).collect::<Vec<_>>();
println!("len {} cap {}", v.len(), v.capacity());
len 4 cap 6
len 0 cap 6
Despite being in some sense "correct", I'd consider that result a bug. One fix would be to examine the result, and if it breaks the programmers expectations badly (by say using more than twice the memory needed) it does a shink_to_fit() for you. Since the programmer is probably expecting a new vector to be generated it isn't a surprising outcome.That being said, it’s also not an unreasonable expectation on the user’s behalf that the size and capacity don’t get crazy different in code as innocuous and idiomatic as this.
I wonder how the open bug will end up training itself.
But I think the real thing for me is that this violates the principle of least surprise. If I wanted the type of memory reuse / lazy transformation behavior this optimization introduces, I would be looking at working with an iterator with a bunch of functinoal transforms. And if I'm calling .collect() it's because I want to convert the iterator into a data structure optimized for reads.
But I can also see how others would land on the other end, and hence the challenges for the library authors.
If you want specific memory behavior, you really do have to use a method that intends to do that. Like `shrink_to_fit()` (mentioned in the article).
I.e., the docs could call out that there aren't such implied behaviors, and that in some circumstances, it might reuse the allocation, but that that's not guaranteed. (And ideally, offer me info on what to do if I do want certain guarantees about the allocation of the Vec.)
Warding off what I think is a reasonable, but wrong, assumption, is well within the scope of the docs.
This touched upon a pet peeve of mine for its resemblance with all the talk about undefined behaviour in C and C++. Programmers’ expectations are not codified and do not need to be respected: international standards do.
That's pretty negative attitude - my immediate gut response was "and neither do yours". But Rust isn't an ISO standard and is still in development. Even if we do think in those terms, people developing a standard have IMHO an obligation to the people who will be using the standard.
My guess is that all or almost-all non-trivial C++ projects trigger IFNDR and thus have no actual meaning per the ISO standard language. They do work, more or less, but that's just convention and can be taken away at any time or for any reason. Header files, use of concepts, unfortunate algorithmic goofs, careless naming, there are a billion† ways to trigger IFNDR in C++ and by definition that's fatal to your correctness.
† A billion is likely an overestimate, but WG21 has no formal inventory of IFNDR in the sprawling ISO document so, who knows.
What if...stick with me...the standards sought to codify and respect programmers' expectations?
https://en.wikipedia.org/wiki/Principle_of_least_astonishmen...
https://github.com/rust-lang/rust/blob/25f8d01fd8bda339612d0...
It's not supposed to waste more space than a regular `collect()` or `push()` would when growing the capacity exponentially.
-----
Nice post. I love calling attention to this. Just a few months ago, I ran into the ~same~ similar problem, although it wasn't caused by `collect()`. It was caused by "normal" `Vec` usage:
https://github.com/BurntSushi/aho-corasick/commit/474393be8d...
The issue appeared when building large Aho-Corasick automatons. Otherwise, it usually doesn't matter too much because the absolute memory sizes are pretty small. But if your automaton uses 1GB of memory, then because of the excess capacity in a bunch of little `Vec` values, that usage could easily balloon to 2GB. And even at that size, _it was hard to notice that it was more than it should have been_! It is easy to just think that's normal memory usage. Especially when it's coming from the automaton representation that you know is less memory efficient. (What I'm talking about here is something I called a "non-contiguous NFA." The aho-corasick crate also has a "contiguous NFA" and a DFA. The "contiguous NFA" uses one contiguous `Vec` allocation with a bunch of bit-packing tricks.)
But then someone actually reported an issue on the `ahocorasick_rs`[2] Python project (bindings to the `aho-corasick` crate) that the `pyahocorasick`[3] Python package (with a bespoke C implementation of Aho-Corasick) was using _substantially_ less memory. The contiguous NFA was still doing better, but the _peak_ memory usage of `ahocorasick_rs` was much much bigger than `pyahocorasick`. That prompted me to investigate and figure out what the heck was going wrong. (And this is one reason why benchmarks comparing tools or libraries are actually useful beyond just advertisements or flexing. They alert you to what is possible, and thus possibly push you to find bugs in your current implementation that might be otherwise easy to miss. In other words, benchmark comparisons can turn unknown unknowns into known unknowns.)
So since this prompted me to look very carefully at memory usage, I noticed that the memory usage reported by `AhoCorasick::memory_usage`[4] was substantially smaller than peak RSS memory usage in a simple reproduction program of the original issue reported to `ahocorasick_rs`. I eventually figured out that was because of the excess capacity used by a zillion tiny `Vec`s in the non-contiguous representation. I fixed _most_ of that by calling `shrink_to_fit()`. But as the commit linked above notes, it wasn't really feasible to call `shrink_to_fit()` on all `Vec`s because that ended up with a non-trivial impact on construction time. And on top of all of that, memory usage was still worse than `pyahocorasick`.
But why was I using a bunch of little `Vec`s in the first place? It's because this is the "non-contiguous" NFA. This is the thing that gets built from a list of patterns by first building a trie then filling in the failure transitions. That trie construction really demands random access mutation, which puts a constraint on your data structure choices. Plus, I had designed the contiguous NFA as a release valve of sorts that lifts this constraint. So I reasoned, "sure, the non-contiguous NFA isn't designed to be fast. It just needs to get us started." But still, `pyahocorasick` only has one Aho-Corasick implementation (the `aho-corasick` crate has 3). So it must be doing something differently.
It turns out that `pyahocorasick` uses linked lists! THE HORROR! But actually, they are a really good solution to this problem. As a Rust programmer, I reach for `Vec` first. But a C programmer reaches for linked lists first. And it turns out that linked lists are a much better fit here.
And so, I switched to linked lists[5]. (But using indices instead of pointers. Because of course. This is Rust. :-)) And now `ahocorasick_rs` uses less memory than `pyahocorasick`!
[1]: https://old.reddit.com/r/rust/comments/199jycb/identifying_r...
[2]: https://pypi.org/project/ahocorasick-rs/
[3]: https://pypi.org/project/pyahocorasick/
[4]: https://docs.rs/aho-corasick/latest/aho_corasick/struct.AhoC...
[5]: https://github.com/BurntSushi/aho-corasick/commit/31bb1fc30d...
If it wasn't caused by `collect()`, then I suppose it's a related problem, but not the same problem. Your problem was caused by, as your commit message says, "ignorance [original: ignorant] of the broader effects of this strategy [double-when-full] in aggregate"
The OP's problem, otoh, is more about reusing memory that has been allocated when you "convert" (in Rust term: into_iter()) a Vec to another Vec. What's more, the reuse also happens even when the new Vec has a different type from the original Vec's type. This behavior is more surprising than the double-when-full strategy, which is more widely known by programmers (even if sometimes they "forget" about the implications).
My phrasing is a reflection of what I think is a more universal lesson to draw from the blog, and one that is not provoked merely by how `collect()` works, but rather, the nature of growth amortization itself.
> This behavior is more surprising than the double-when-full strategy
I agree.
I updated my comment to use "similar" instead of "same."
That is, the vec could expand to areas much larger than the actual used size, but this would have no effect on process RSS until those pages get dirtied with actual data.
When you do the madvise, based on the contact of the API, the kernel has to do a TLB shoot down which is really expensive. And not just “expensive for my process” but expensive in terms of a significant slowdown for entire machine. Honestly you could probably DDOS a machine if you could reliably trigger that shootdown.
As such you want to be very very careful where you place that data structure.
For what it’s worth your memory allocator (or at least a good one like mimalloc or the non-gperftools newer tcmalloc) will do exactly as you mentioned where it will free memory back to the OS using advanced heuristics tested out at scale.
As for why a shoot down is needed, it’s so that a racing allocation call in another process doesn’t get that virtual address but be running on a core where the TLB points elsewhere (the core that did the allocation may not even be the one where it’s used).
I'd certainly want intelligence (either by the user or by the framework) in how frequently you release pages back to the OS.
But the DONTNEED is really not the core of the value. It's being able to create vectors that don't fragment as badly.
And yes, you're right a decent allocator could help with this, and what I'm describing is really just a kind of specialized allocator.
1. "Do you know if there are any config knobs in the aho-corasick crate that will speed up construction?"
2. "I have my own implementation of Aho-Corasick and construction isn't as fast as I hoped. What kinds of tricks can I employ to make my own implementation faster?"
I'd be happy to try and answer either of these, but I think it would be better to ask with a concrete example on the issue tracker Discussions: https://github.com/BurntSushi/aho-corasick/discussions
All of the tricks I know about (and I judged to be worth doing) are in the aho-corasick crate. There's really just no getting around the fact that you need to first build a trie (which requires visiting every byte in every pattern) and then do a breadth-first search across the entire trie to setup failure transitions. Making construction substantially faster probably requires some kind of innovation in those two parts at a fundamental level.
You can also cheat at this. That is, by designing your Aho-Corasick automaton to be zero-copy deserializable. The DFAs in regex-automata support this. I waver on whether to do this for aho-corasick, because it acts like a straight-jacket for evolving the internals of the library.
Note that the conversion from a non-contiguous NFA to a contiguous NFA is, relatively speaking, pretty cheap. The only real reason to not use a contiguous NFA is that it can't represent as many patterns as a non-contiguous NFA. (Because of the compression tricks it uses.)
The interesting bits start here: https://github.com/BurntSushi/aho-corasick/blob/f227162f7c56...
<Vec<_>>()
perhaps to become another ¯\_(ツ)_/¯
?"Identifying Rust's collect:<Vec<_>>() memory leak footgun"
but the actual title of the blog post is:
"Identifying Rust's collect::<Vec<_>>() memory leak footgun"
That extra colon matters to Rust's syntax.
Sidenote, `<Vec<_>>` is missing the best part - the fish head, to become `::<Vec<_>>`, aka `::<>` - the Turbo Fish :D
I admit to using this syntax more than necessary just so i can write a turbofish :D
edit: Wait no, `<>` is the head - isn't it. hah. So i guess it's missing the fins? /shrug