Repository navigation
Conversation
|
This closes #17047 and replace it. |
|
052ce63 has introduced a tiny performance regression which I'm still investigating. In the meantime I'm adding other changes to make naming and classes more clear. In order to perform tests without chunk churning, I've added 6ab4716 too, which I'll send a separate PR as well FYI @chrisvest |
5dbe529 to
191f507
Compare
191f507 to
3fa39c5
Compare
|
I see that the current model on this pr would enable a minalloc style local release path which would benefit to prevent chunk churning and the artificial floor of 8M per size class cache which is applied to 4.2. |
Thanks for reaching out. I'm currently away on vacation and will take a look once I'm back. |
cb32c81 to
0b2707e
Compare
|
@laosijikaichele you can ignore the big amount of changes I have here, please: in the final version I plan to split into separate files the allocator key components too 🙏 In any case this grant me a very very good performance for the event loop case, and the platform one, fixing some of the shortcomings of #17166 |
|
Just for myself: the epoch based mechanism on top of new striped model was impl at 191f507
In the new notification based model, instead, chunks will be allocated to serve the incoming requests and accomodate for the live required buffers, but, once released, will be made available or, if fully released, recycled in the shared parking lot, to serve future demand. |
82bd38c to
b41f062
Compare
|
@chrisvest @laosijikaichele I'm not fully convinced by fa21d4b (a large-buffer magazine per event-loop heap), and I'd like your opinion.
The Java mimalloc port also has one heap per event loop, but cuts large blocks (≤ 2 MiB) from the same 4 MiB segments as the small pages, so a rare large buffer needs no dedicated memory; the price is a floor of one segment per heap. Giving memory back as uniform 4 MiB segments also suits glibc better than our mix of 128 KiB - 8 MiB chunks, which glibc keeps in its arenas after they are freed. Options: keep it per heap, or go back to stripes plus the decay fix. |
@franz1981 Given that large-buffer allocation is likely not the common use case, I'd prefer the per stripe design. |
|
@laosijikaichele agreed, thanks. d33cd10 takes the buffers above the size classes from the stripes again. To keep their idle chunks aging when only event loops use them, an event loop's decay now also decays every stripe in use whose last decay is at least an interval old, when its lock is free: a stripe still decays at most once per interval, and nothing is added to the allocation or release paths. |
A heap's SizeClassChunkRecycler kept up to recycledChunkBytes of chunk buffers for as long as the heap lived, however long nobody took them. Every 10,000 allocations of the heap it now looks at the clock once, and when 10 s passed since its last decay it frees half, rounded up once over all its pools, of the buffers that sat unused through the whole interval, oldest first; otherwise it waits for the next count. The count is carried by the heap's purge ticks, which add the allocations they counted, so there is no cost per allocation and one clock read per count. A per-pool low-water mark finds the cold buffers, and nothing is allocated on the way (measured: 0 bytes over 1M ticks and repeated decays; one decay freeing 128 buffers of 128 KiB takes about 25 us, unpinned CPU, rough). Tests pin the halving, the oldest-first order with free lists kept paired, the low-water mark, both gates and the restart of the count, the single rounding, and the heap's own ticks driving it.
The wholly free chunks a stripe keeps for buffers above the size classes, up to chunkReuseQueueBytes, were never given back while the stripe lived, and those allocations counted toward nothing. The decay's gate moves into a per-heap IdleDecay, fed by the size-class purge ticks as before and by the large-buffer magazine's slow path, which counts one: a slow path is at least one allocation and may be exactly one, so counting more could age the stripe faster than its allocations do, and no fast path counts anything. When it fires it ages the recycler as before and, on a stripe, frees half, rounded up, of the chunks that stayed wholly free through the whole interval, oldest first. Each chunk is stamped with the decay count when it is filed wholly free, which is exact where a low-water mark would not be, since chunks leave that list by fit. Tests pin the halving, a chunk idle for part of an interval surviving it, the active chunk never counting as idle, one count per slow path and none on the fast path, and a slow path driving a decay end to end.
idleChunksAreEvictedAfterRelease sized its burst from chunkReuseQueueCapacity, twice the processors: on a 4-core CI runner the burst fit in the heap's chunk recycler, which usedMemory() counts, so nothing was freed and the test failed. The burst is now twice the recycler's budget, and the settled memory is bounded by that budget. The seeded trace's recorded memory keeps three idle large-buffer chunks, which one processor does not allow: it now assumes at least three. The buffer tests pass with -XX:ActiveProcessorCount 1, 2, 4 and 64.
…classes An event loop took its buffers above the size classes from a stripe, under the stripe's lock, although it has a heap of its own for everything else. The stripe's idle decay then only counted those allocations' slow paths, so the wholly free chunks a burst left there were never given back (32 MiB kept for four minutes of steady traffic in a burst-then-quiet test), while the event loop's own heap, busy with small allocations, aged only its recycler. A thread-local heap now creates a BuddyMagazine on its first such buffer, touched only by its owner thread: the owner puts released blocks straight back, any other thread leaves a note, as on a stripe whose lock is busy. Since every other thread's release is a note there, the heap's size-class slow path applies the magazine's notes too, so its idle bound holds without waiting for a large allocation. The heap's IdleDecay ages the magazine with the recycler, fed by all of the thread's allocations, and applies the notes first. The magazine is freed with the heap, and its buffers report thread-local chunks to JFR. Stripes keep theirs for the threads without a heap. Each event loop can now keep up to chunkReuseQueueBytes of idle large chunks plus its active one, where the stripes' bound was shared.
After a burst, every size class a heap ever used kept its current chunk and the one chunk of its retention floor for good, whether or not it still allocated: in a mixed test, after 120 s of steady 1-16 KiB traffic, 147 MiB of 390 MiB held sat in the size classes that traffic never used, on every heap. And once the recycler and the idle large-buffer chunks were empty, the decay no longer looked at the clock at all. At each decay a size class that made no allocation since the previous one, read from the counters its allocations already keep, gives up its current chunk and every wholly free chunk it keeps, the floor included, to the heap's recycler, which gives them back from the next decay on, by halves, like any buffer offered to it. While the recycler has no room they stay with the class, so memory only goes back by halves. The floor stays for a class in use; chunks with buffers out stay. Every count of 10,000 allocations now looks at the clock, as the rule says.
Each heap kept the chunk its large-buffer magazine allocates from for good, since only chunks filed on its queues age; in a mixed test that was one 8 MiB chunk per heap, 192 MiB of 390 MiB held after 120 s of traffic that allocated no large buffer. At a decay, after applying the notes, a wholly free active chunk is filed like any other chunk while the idle chunks have room for it: it is idle from that decay on and given back once it stays so through the whole next interval, while the next allocation polls it back on its slow path. A chunk with a buffer out stays active, and so does one the idle bound has no room for, rather than being freed before any interval.
…et Recycler MpscIntQueue is a public interface, and this PR added two abstract methods to it, capacity() and resetAndFill(int, int), with revapi told to ignore the break. Code implementing the interface outside Netty would no longer compile. Both are now default methods that throw UnsupportedOperationException, overridden by the queue create() returns, and the revapi ignores are gone. The Recycler constructor with an exclusiveGet flag had no documentation and silently ignored the flag for a guarded pool. It now says what it is for, a pool whose get() only one thread at a time calls, and rejects the flag without unguarded.
Low-memory mode pools the size classes up to 16896 only, pools no buffer above them and has no thread-local heaps. Several tests this PR added assumed otherwise: they failed there, one leaked the buffer it allocated before its assumption skipped it, and a JFR test waited forever for an event low-memory mode never fires, hanging the test JVM. They are skipped in low-memory mode now, the skipped test releases its buffer first, and the JFR test's waits are bounded. What still fails in low-memory mode fails on 4.2 as well (shouldReuseChunks, adaptiveJfrBufferAllocationThreadLocal).
A review of the whole change found comments that no longer matched the code or cited internal benchmarks, and two corner cases: - The idle bound is per heap, and a stripe holds a large-buffer magazine too. A decay frees half of what stayed idle a whole interval, never more, and the IdleDecay documentation now states what a heap can keep idle at most (about 84 MiB per heap with the defaults), which it did not before. - Benchmark names and an unsourced JIT claim are dropped from comments. - The recycler's room check adds in long, so a budget close to Integer.MAX_VALUE cannot overflow it, and evicting an idle size class's chunks no longer assumes a recycler exists. - The JFR chunk events describe what they now mean: memory taken from, and given back to, the memory the allocator is built on. - The stripes' buffer-object pool uses MpscArrayQueue, whose index fields native images need registered, as the other JCTools queues' are. - The seeded trace test documents what it pins instead of how it got there, and is skipped if it ever runs longer than a decay interval.
…vent loops age them This reverts the magazine for buffers above the size classes that every thread-local heap had (fa21d4b). With the size classes going up to 132 KiB such buffers are the exception, and one magazine per event loop made their memory grow with the number of event loops that ever allocate one, each keeping a chunk of at least 2 MiB while it uses them, instead of with how many are live; on the stripes the event loops share chunks, and the number of stripes only grows under lock contention. What the per-heap magazine gave for free was the decay: an event loop counts its allocations on its own heap, so a stripe that only event loops use for large buffers never counted enough to decay its idle chunks. A thread-local heap's decay now also decays every stripe in use whose last decay is at least an interval old, when its lock is free: a stripe still decays at most once per interval, by the same rule, and nothing is added to any allocation or release path.
A stripe that event loops use for buffers above the size classes only counted those allocations' slow paths toward its decay, one each: after a burst the chunk it allocates from serves them all, so the count never got anywhere and the stripe's idle large chunks were never given back. The previous commit had event loops' decays sweep the stripes instead, which puts one heap's upkeep on another heap's thread. The large-buffer magazine now counts every allocation, on the fast path as on the slow one, with its block size in units of the smallest size class: a large buffer paces the stripe's clock reads like the small buffers its bytes would make. It runs under the stripe lock that path already holds. The count only decides how often the clock is read: a stripe still decays at most once per interval, freeing half of what stayed idle through it. The sweep is removed.
…classes An event loop took its buffers above the size classes from a stripe. Each of those allocations counts toward that stripe's decay (546e922), which ages a stripe only while some thread allocates large buffers on it: the chunks an event loop's burst left on a stripe no thread allocates large buffers on again stay there, since only a heap's own allocations may age it. In a burst-then-quiet test (8 event loops and 16 other threads, a 1 GiB burst of all sizes, released, then light traffic of small buffers) the allocator still held 187 MiB after two minutes, 148 MiB of it such chunks; with this change it holds 49 MiB. A thread-local heap now creates a BuddyMagazine on its first such buffer, touched only by its owner thread: the owner puts released blocks straight back, any other thread leaves a note, as on a stripe whose lock is busy. Since every other thread's release is a note there, the heap's size-class slow path applies the magazine's notes too, and the heap's IdleDecay applies them before it ages the magazine with the recycler, fed by all of the thread's allocations, each large one by its block size. The magazine is freed with the heap, and its chunks are reported to JFR as thread-local. Stripes keep theirs for the threads without a heap. Costs: each event loop that allocates large buffers keeps its own chunk and up to chunkReuseQueueBytes of idle ones, where event loops shared the stripes'; they age with the loop's own allocations. The chunks other threads' releases empty come under that bound when the owner applies the notes, on its next slow path or decay. Per buffer: an allocation above the size classes looks for a thread-local heap first, as the size classes do; a large release on a stripe reads the magazine's owner; the size-class slow path, once per chunk's worth of allocations, reads the large magazine's notes. This undoes d33cd10.
d6e63da to
0b05f0f
Compare
…hunk objects Recycler: the exclusive-get pool honours io.netty.recycler.blocking, and both new constructors carry the unguarded disclaimer. BuddyTree becomes a top-level class and takes its minimum block size from the allocator: the smallest power of two above the largest size class (132 KiB), so 256 KiB. Nothing below that is ever claimed, so the trees lose three unused levels and the buddy free lists shrink to match. The allocator's javadoc names the generational hypothesis; the chunk events' descriptions say when they fire; @VisibleForTesting replaces the comments (buffer now declares the provided org.jetbrains:annotations dependency that common already uses). A SizeClassedChunk object is made for one magazine and stays with it, serving one buffer at a time. When every segment is back, the owner side retires the chunk: the buffer goes to the heap's recycler (or back to the chunk allocator), and the object waits on its cache's spare list. The next chunk the magazine needs takes a spare object, or makes one, and a recycled buffer, or allocates one; takeBuffer sets only what belongs to the buffer. The two free lists are built once, when the object is, and are never refilled or reset: when a buffer is given up every offset is on one of them, and the next buffer is handed out from them as they are. A chunk rebuilt from a recycled buffer therefore allocates nothing. A thread releasing a segment of the previous buffer that is still between its offer and its read of the state is counted by the queue before the chunk can read as wholly free; its value lands in the slot it claimed, and the owner's poll waits for it there. The reset that could have overwritten such a slot is gone, and with it the PR's additions to MpscIntQueue: it and its test are upstream's again. The recycler pools buffers only. IntStack is built from a capacity, a count and an IntUnaryOperator, and loses refill. A size class that stayed idle through a decay interval lets go of its spare objects together with its chunks, as does a dying cache; chunks of a dead cache are never reused. Tests: the JIT regression test for the old BuddyTree constructor loop goes with the loop; the seeded trace compares the stripe with the thread-local heap and checks a documented bound instead of a golden table; threads started by tests hand their failures back through CompletableFutures; the recycler test deals in buffers; the cache test expects a given-up chunk on the spare list and mocks retire.
A thread-local chunk object that takes a new buffer drains its external free list into its local stack first, so the segments other threads gave back to the previous buffer are handed out by pop again, as from a new chunk. The drain stops at a slot a releaser claimed but has not written yet, which stays queued for a later poll: nothing waits. IntStack is the drain's IntConsumer. retire asserts the chunk is still AVAILABLE (never after its cache died), and the releaser's comment on a non-AVAILABLE state names the spare list.
idleChunksAreEvictedAfterRelease fills its chunks with 16 KiB buffers instead of 256-byte ones, and chunksAreReusedAcrossSizeClasses frees 4 chunks instead of 64: the same chunks past the recycler budget, and the same reuse, with far fewer buffers alive at once. Each tracked buffer keeps its stack traces, and two of these bursts running concurrently filled a 4 GB test heap.
|
@chrisvest 6f52f79 addresses your review (plus reusing size-classed chunk objects), and 570b197 starts a reused thread-local chunk from its stack. e47ed40 is tests only: two recycler tests held ~260k leak-tracked buffers each and ran the leak-detection legs out of heap, so they now overflow the recycler with bigger buffers. The musl-verify failures are unrelated (two netty-codec-native-quic versions on the classpath), as on other 4.2 PRs. |
| * is the smallest block the buddy path is ever asked for, since every request up to that class is a segment. | ||
| */ | ||
| static final int BUDDY_MIN_BLOCK_SIZE = | ||
| MathUtil.safeFindNextPositivePowerOfTwo(SIZE_CLASSES[SIZE_CLASSES_COUNT - 1] + 1); |
There was a problem hiding this comment.
Consider moving this below the POOLED_SIZE_CLASSES_COUNT definition, and making use of it so we automatically take IS_LOW_MEM into account.
| this.chunkController = strategy.createController(allocator); | ||
| this.chunkCache = strategy.createChunkCache(chunkRecycler, sizeClassIndex, stripeLock); | ||
| this.purgeTickThreshold = (int) Math.min(Integer.MAX_VALUE, | ||
| CHUNK_PURGE_INTERVAL * (strategy.chunkSize / strategy.segmentSize)); |
There was a problem hiding this comment.
Use checked multiplication, to prevent overflow. Or clamp CHUNK_PURGE_INTERVAL.
| Object chunkA = anyChunkOf(bufs.get(0)); | ||
| Object chunkB = anyChunkOf(bufs.get(perChunk)); | ||
| Object chunkC = anyChunkOf(bufs.get(2 * perChunk)); | ||
| assumeTrue(chunkA != chunkB && chunkB != chunkC, "one chunk per " + perChunk + " buffers"); |
There was a problem hiding this comment.
Did you mean assertTrue? You'll need to release all the bufs if you mean to assume and this assumption doesn't hold.
| BuddyHeld b = new BuddyHeld(); | ||
| b.held.add(allocator.heapBuffer(BUDDY_NOTE_SIZE, BUDDY_NOTE_SIZE)); | ||
| b.perChunk = (int) (allocator.usedHeapMemory() / BUDDY_NOTE_SIZE); | ||
| assumeTrue(b.perChunk >= 2, "a buddy chunk holds " + b.perChunk + " buffers"); |
There was a problem hiding this comment.
Assume or assert? You'll need to release the b.held buffers if this is an assumption and it doesn't hold.
…urge interval, and assert test preconditions Motivation: Review: the buddy tree's minimum block ignored low-memory mode, the purge tick threshold could overflow for a very large purge interval, and two tests assumed what they should assert, leaking their buffers when the assumption failed. Modifications: - BUDDY_MIN_BLOCK_SIZE is the next power of two above the largest pooled size class. - CHUNK_PURGE_INTERVAL is clamped to Integer.MAX_VALUE. - The two tests fail, after releasing what they hold, when a chunk does not hold the buffers they expect. Result: Review comments addressed.
|
@chrisvest Addressed in 85ba70d. |
🚨 All tests passed but jobs failed 🚨Failed Jobs without Test Failures❌ Verify native library loading on musl / musl-verify-alpine-aarch64-gcompat 🏷️ Commit: 85ba70d Rerun ControlsClick the checkbox to trigger a rerun:
Learn more about TestLens at testlens.app/docs. |
|
Checking, so far i've run the ecommerce workload using the @laosijikaichele benchmark in JMH which have no timing (sleeps basically), never run this one in this form! |
|
@laosijikaichele Accordly to Claude both my PR, the page store branch and mimalloc fail badly with this test I'm checking what the test actually....test. And why we get better latencies compared to 4.2 with much worse used memory; my educated guess is that we churn way more in 4.2...let's see |
|
@chrisvest Reproduced: 11.5 → 27.7 MB at 128 live, same live bytes. Two causes, from heap dumps:
With both changed as an experiment, memory at 128 live is 11.4 MB on plain threads (4.2: 11.5) and 17.6 MB on event-loop threads (4.2: 19.3); at 1024 live it stays 4–6 MB above 4.2, which is wholly-free buddy chunks kept for reuse. In exchange the PR makes no one-shot allocations, where 4.2 allocates up to ~1,200 unpooled 64 KiB chunks per 2 min at 1024 live. I think these applies to mimalloc too @laosijikaichele |
|
Do the other benchmarks still look reasonable with those changes? |
|
@chrisvest Which ones do you mean: the other profiles in netty-allocator-profiles through the simulator, or the throughput/latency runs (lao's harness, the #17485 cells)? The two changes in my last comment are experiments to isolate the causes, not a proposal yet; the six classes in particular came from the #17485 latency results, so dropping them is not on the table yet. |
|
@franz1981 Ok. I was thinking of Lao's harness. |
|
@chrisvest @laosijikaichele findings so far. The regression is the stripe expansion rule: the PR doubles the number of stripes on the first scan that finds every Your simulator, 4 threads at 1 alloc/ms, head 85ba70d (one scan length for all size classes): 4.2, same run: each size class has its own magazine array with its own lock, starting at one magazine. Why 4.2 ends up with far fewer chunks: (1) a doubling costs 4.2 one magazine and one chunk of one class, while the In short: a few collisions in the first milliseconds double the stripes three times, and from then on every thread Tried: one scan length per size class. It fixes the simulator, but lao's harness on E_COMMERCE (32 platform The model: a stripe is one lock plus one magazine per size class. Thread t starts its scan for class c at stripe The per-class lengths recover the e-commerce footprint in your simulator but regress latency in lao's case for two
|


Motivation:
Existing performance tests shows adaptive striping model and sharing across size classes to under-perform compared to other alternatives.
In addition, the existing striped model is too eager to both allocate and throw away existing slots under contention instead lazily allocate and eventually reuse them, keeping them both stable and more cache-friendly for existing threads.
The existing shared size-class chunk cache degrade severely under heavy contention - and its algorithm is not really made to be effective under concurrent usage.
The chunk cache is not able to purge idle chunks if a specific size class end up allocating from the same magazine's current chunk, causing memory waste.
Modification:
Result:
Fixes #17028
Current state (head 1f303f3; replaces the earlier update notes)
Design. Heaps: one per stripe (one lock each) and one per event loop (thread-local, no lock), each with size-class magazines (now up to 132 KiB) and a recycler for the chunk buffers they give up. Buffers from 132 KiB to 1 MiB (buddy blocks) come from a large-buffer magazine of the same heap, so an event loop takes them from its own heap without a lock; they are the exception now. Releases from other threads leave a note that the owner applies on its slow paths.
Idle memory is bounded and given back. Every 10,000 allocations of a heap (size classes counted on their purge ticks, large buffers by their block size) the clock is read once; after 10 s a decay frees half, rounded up, of what stayed unused a whole interval: recycled buffers, idle large-buffer chunks, the large-buffer chunk in use once wholly free, and the chunks of a size class that allocated nothing (via the recycler). An event loop's large chunks so age with its own traffic, like its size classes. Nothing on the allocation or release fast paths. A heap that stops allocating keeps its memory until it is freed. At most, with the defaults, about 84 MiB per heap (32 MiB recycled, 32 MiB of idle large chunks, the chunk each size class and the large-buffer magazine allocate from), for every event loop that allocates and every stripe in use; on an event loop, chunks emptied by other threads' releases come under that bound when it applies their notes, on its next slow path or decay.
User-visible changes
io.netty.allocator.chunkPurgeIntervalchunkPurgePollsThreadLocal(still read, warns); default 4recycledChunkBytes/chunkReuseQueueByteschunkReuseQueueCapacity,magazineBufferQueueCapacitychunkPurgePollsShared,chunkPurgeThreshold,threadLocalChunkCacheMaxBytes/MinBytesusedMemory(), JFRAllocateChunk/FreeChunkusedMemory()io.netty.recycler.ratioMpscIntQueue.capacity()/resetAndFill()(default methods),Recycler(int, boolean, boolean)Results vs 4.2 (901d1c5; Ryzen 9 7950X, one NUMA node, 2300 MHz, JDK 21)
Verified:
commonandbufferon JDK 11 (revapi, checkstyle) and with 1/2/4 processors; in low-memory mode only the two tests that already fail on 4.2 fail.