Repository navigation
feat: pre-allocate packet send buffer to MTU size to avoid realloc - #3702
larseggert wants to merge 6 commits into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #3702 +/- ##
=======================================
Coverage 96.75% 96.75%
=======================================
Files 118 118
Lines 39784 39786 +2
Branches 39784 39786 +2
=======================================
+ Hits 38492 38495 +3
+ Misses 1267 1266 -1
Partials 25 25
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
Merging this PR will regress 2 benchmarks
|
| Mode | Benchmark | BASE |
HEAD |
Efficiency | |
|---|---|---|---|---|---|
| ❌ | Memory | simulated/1000-streams/each-1000-bytes |
401.5 KB | 422.2 KB | -4.91% |
| ❌ | Memory | simulated/1-streams/each-1000-bytes |
24.7 KB | 25.9 KB | -4.41% |
| ⚡ | Memory | simulated/10-streams/each-1048576-bytes |
11.4 MB | 9.2 MB | +24.71% |
| ⚡ | Memory | simulated/1-streams/each-4194304-bytes |
5.2 MB | 4.4 MB | +19.21% |
| ⚡ | Simulation | simulated/pacing-false/same-seed |
144.2 ms | 136.8 ms | +5.4% |
| ⚡ | Simulation | simulated/1-streams/each-4194304-bytes |
176.9 ms | 168.5 ms | +4.98% |
| ⚡ | Simulation | simulated/pacing-true/same-seed |
143.6 ms | 137.4 ms | +4.52% |
| ⚡ | Simulation | simulated/pacing-true/varying-seeds |
143.6 ms | 137.4 ms | +4.51% |
Tip
Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.
Comparing larseggert:opp-send-buffer-alloc (fcc27fd) with main (de70e15)
6aabe09 to
e54e6f3
Compare
We tried this before but Claude insists this is a good idea...
e54e6f3 to
2c14e2e
Compare
There was a problem hiding this comment.
Pull request overview
This PR reduces allocations during packet construction by pre-allocating the per-batch datagram payload buffer to the current path PLPMTU, avoiding an initial growth/realloc when building the first packet on a path.
Changes:
- Allocate
send_bufferwith capacitypath.borrow().plpmtu()instead of starting from an emptyVec. - Add rationale in-code to avoid scaling the allocation by
max_datagrams(which can be large with GSO).
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
Which benchmark shows the reliable signal that this is an improvement?
I don't think this is a regression we are willing to accept? |
mxinden
left a comment
There was a problem hiding this comment.
Firefox mostly sends ACKs and small requests past the handshake. Is this a good idea?
|
The regression is from before the latest changes, which should fix it. If not, obviously we can't accept. I see no downside in using a 1500 byte buffer here? |
There was a problem hiding this comment.
Correct and low-risk change. The pre-allocation is ~1.2KB (initial PLPMTU of 1280 minus IP/UDP headers), which avoids 2–3 reallocations when the first datagram approaches MTU size.
Re @mxinden's concern about Firefox mostly sending small ACKs past the handshake: even in that case, ~1.2KB of unused capacity per batch is negligible, and Vec's growth strategy would allocate similar amounts after the first push anyway. The optimization is most impactful during the handshake and bulk data transfer where packets routinely fill the MTU.
1112c32 to
3540ce1
Compare
There was a problem hiding this comment.
Clean, low-risk change. Two improvements here:
-
Borrow consolidation: Collapsing three separate
path.borrow()calls into one scope removes redundantRefCellborrow/unborrow cycles. The explicitdrop(path_ref)is necessary sincepathis re-borrowed (both shared and mutably) inside the loop — worth keeping in mind if this block is ever refactored. -
Pre-allocation:
Vec::with_capacity(mtu)avoids 2–3 reallocations during the first packet encode. For multi-datagram GSO batches theVecwill still grow beyondmtu, but the common single-datagram path gets a single right-sized allocation.
Re @mxinden's concern about Firefox's typical small-ACK pattern: even there, Vec::new() allocates nothing up front but then hits the allocator on the first extend during encoding. The difference is one ~1.2 KB allocation vs. a few smaller grow-and-copy cycles — net effect is neutral to slightly positive regardless of packet size, and clearly wins during handshake and bulk transfer.
There was a problem hiding this comment.
Clean, correct change. Two things happening here:
-
Borrow consolidation: The three separate
path.borrow()calls collapse into one scope with an explicitdropbefore the loop — necessary sincepathis re-borrowed both shared (lines 2629, 2668) and mutably deeper in the call chain. Eliminates redundantRefCelloverhead. -
Pre-allocation:
Vec::with_capacity(mtu)right-sizes the first datagram's allocation (~1.2 KB at initial PLPMTU). For GSO batches theVecwill still grow, but the common single-datagram path avoids 2–3 grow-and-copy cycles. Thedebug_assertat line 2668 already guards againstmtuchanging mid-batch, so using the cached value is safe.
Re @mxinden's concern about small ACKs: Vec::new() allocates nothing up front but then hits the allocator on the first extend during encoding anyway, so the net overhead for small packets is one right-sized allocation vs. a few smaller grow-and-copy rounds — neutral to slightly positive.
No issues found. The previous inline suggestion (consolidating borrows) has been implemented in this revision.
|
Some historical context on this:
The long-lived send buffer in #2747 is in my eyes the best next step. |
There was a problem hiding this comment.
Clean, correct change. Two wins in six lines:
-
Borrow consolidation — three
path.borrow()calls collapse into one scope. The explicitdrop(path_ref)is necessary sincepathis re-borrowed both shared and mutably inside the loop. Eliminates redundantRefCelloverhead. -
Pre-allocation —
Vec::with_capacity(mtu)right-sizes the buffer for the first datagram (~1.2 KB at initial PLPMTU of 1280). For multi-datagram GSO batches theVecwill still grow, but the common single-datagram path avoids grow-and-copy cycles entirely. The existingdebug_assert_eq!at line 2681 already validates that the cachedmtustays consistent within a batch, so using the pre-loop value is safe.
Re @mxinden's question: even for small ACK-only packets, Vec::new() would hit the allocator on the first extend anyway — the difference is one right-sized allocation vs. a few smaller grow-copy rounds, which is neutral to slightly positive regardless of packet size.
|
@mxinden this really looks performance positive? |
|
Where do I find the https://github.com/mozilla/neqo/blob/main/neqo-bin/benches/main.rs benchmark results? I can't find them in #3702 (comment). This is counterintuitive to me as:
|
See #3804 - we haven't been generating them. (That PR was exactly motivated by me also wanting to compare profiles apples to apples...)
Well, only by 1500 bytes. I still don't see how that matters.
Correct. But IIRC |
There was a problem hiding this comment.
Behavior-neutral change: hoists the three path.borrow() calls into one borrow and pre-sizes send_buffer to one PLPMTU. Correctness looks fine — the borrow is dropped before the loop re-borrows path (including borrow_mut() in datagram_batch), and the existing debug_assert_eq!(mtu, path.borrow().plpmtu()) guards the hoisted mtu. My earlier suggestion to consolidate the borrows has been applied.
Architectural note, extending @mxinden's point rather than repeating it: the effect here is bounded on both ends. For a GSO batch the buffer still grows by doubling from mtu, i.e. ~log2(max_datagrams) reallocs (each copying up to tens of KiB, so the copied bytes saved are less lopsided than the realloc count suggests); for ACK-only output — Firefox's common case — it trades ~7 small allocations for one 1500-byte one that is immediately handed to the socket. Both directions are plausibly in the noise, which is consistent with the CodSpeed deltas being carried by the microbenchmarks rather than by anything obviously allocation-bound. Now that #3804 has landed, neqo-bin/benches/main.rs numbers would settle the question, and the earlier +55.9% upload regression should be confirmed gone on the current head.
Given that the long-lived reused send buffer (#2747) subsumes this entirely — amortized zero allocations and no over-allocation, making the constant-vs-batch sizing tradeoff moot — the main question for this PR is whether it's worth landing as a stopgap versus going straight there. If it does land, a short comment recording why mtu (and not the batch bound) was chosen would save the next person from re-deriving this thread.
| let mtu = path_ref.plpmtu(); | ||
| let address_family_max_mtu = path_ref.pmtud().address_family_max_mtu(); | ||
| drop(path_ref); | ||
| let mut send_buffer = Vec::with_capacity(mtu); |
There was a problem hiding this comment.
[!NOTE]
The rationale comment from the earlier revision got dropped; mtu as a capacity isn't self-explanatory. Also worth noting that this doesn't cover the largest datagram the loop can build: when pmtud().needs_probe(), the first datagram is built up to probe_size(), which is by construction larger than plpmtu().
Minimal fix — restore the rationale:
| let mut send_buffer = Vec::with_capacity(mtu); | |
| // Pre-allocate one MTU to avoid reallocating while the first datagram | |
| // of the batch is built. | |
| let mut send_buffer = Vec::with_capacity(mtu); |
Alternative — size for the whole batch, which is exactly the bound the loop enforces below via address_family_max_mtu - send_buffer.len() < mtu, so no realloc at all (at the cost of up to a 64 KiB allocation for an ACK-only output):
| let mut send_buffer = Vec::with_capacity(mtu); | |
| let mut send_buffer = | |
| Vec::with_capacity((mtu * max_datagrams.get()).min(address_family_max_mtu)); |
Performance profiles for profiler.firefox.comBenchmarks (14)
|
Failed Interop TestsQUIC Interop Runner, client vs. server, differences relative to
All resultsSucceeded Interop TestsQUIC Interop Runner, client vs. server neqo-pr as client
neqo-pr as server
Unsupported Interop TestsQUIC Interop Runner, client vs. server neqo-pr as client
neqo-pr as server
|
Client/server transfer resultsPerformance differences relative to 30f8b8d. Transfer of 33554432 bytes over loopback, min. 100 runs. All unit-less numbers are in milliseconds.
Table above only shows statistically significant changes. See all results below. All resultsTransfer of 33554432 bytes over loopback, min. 100 runs. All unit-less numbers are in milliseconds.
Download data for |
Benchmark resultsSignificant performance differences relative to 30f8b8d. streams-flow-controlled/walltime/1-streams/each-4194304-bytes: 💚 Performance has improved by -4.0976%. time: [25.118 ms 25.152 ms 25.187 ms]
thrpt: [158.81 MiB/s 159.03 MiB/s 159.25 MiB/s]
change:
time: [-4.2726% -4.0976% -3.9223] (p = 0.00 < 0.05)
thrpt: [+4.0824% +4.2727% +4.4633]
Performance has improved.streams-flow-controlled/walltime/10-streams/each-1048576-bytes: 💚 Performance has improved by -5.4737%. time: [68.405 ms 68.490 ms 68.578 ms]
thrpt: [145.82 MiB/s 146.01 MiB/s 146.19 MiB/s]
change:
time: [-5.6248% -5.4737% -5.3220] (p = 0.00 < 0.05)
thrpt: [+5.6212% +5.7907% +5.9600]
Performance has improved.
Found 2 outliers among 100 measurements (2.00%)
2 (2.00%) high mildAll resultsstreams/walltime/1-streams/each-1000-bytes: Change within noise threshold. time: [541.82 µs 543.52 µs 545.55 µs]
thrpt: [1.7481 MiB/s 1.7546 MiB/s 1.7601 MiB/s]
change:
time: [-1.7219% -1.2153% -0.7040] (p = 0.00 < 0.05)
thrpt: [+0.7090% +1.2302% +1.7521]
Change within noise threshold.
Found 10 outliers among 100 measurements (10.00%)
10 (10.00%) high severestreams/walltime/1000-streams/each-1-bytes: Change within noise threshold. time: [10.545 ms 10.560 ms 10.575 ms]
thrpt: [92.348 KiB/s 92.482 KiB/s 92.609 KiB/s]
change:
time: [-1.2873% -1.1002% -0.9003] (p = 0.00 < 0.05)
thrpt: [+0.9085% +1.1125% +1.3041]
Change within noise threshold.streams/walltime/1000-streams/each-1000-bytes: No change in performance detected. time: [31.127 ms 31.163 ms 31.198 ms]
thrpt: [30.568 MiB/s 30.603 MiB/s 30.638 MiB/s]
change:
time: [-0.1743% -0.0229% +0.1321] (p = 0.77 > 0.05)
thrpt: [-0.1319% +0.0229% +0.1746]
No change in performance detected.streams-flow-controlled/walltime/1-streams/each-4194304-bytes: 💚 Performance has improved by -4.0976%. time: [25.118 ms 25.152 ms 25.187 ms]
thrpt: [158.81 MiB/s 159.03 MiB/s 159.25 MiB/s]
change:
time: [-4.2726% -4.0976% -3.9223] (p = 0.00 < 0.05)
thrpt: [+4.0824% +4.2727% +4.4633]
Performance has improved.streams-flow-controlled/walltime/10-streams/each-1048576-bytes: 💚 Performance has improved by -5.4737%. time: [68.405 ms 68.490 ms 68.578 ms]
thrpt: [145.82 MiB/s 146.01 MiB/s 146.19 MiB/s]
change:
time: [-5.6248% -5.4737% -5.3220] (p = 0.00 < 0.05)
thrpt: [+5.6212% +5.7907% +5.9600]
Performance has improved.
Found 2 outliers among 100 measurements (2.00%)
2 (2.00%) high mildtransfer/walltime/pacing-false/varying-seeds: Change within noise threshold. time: [17.504 ms 17.516 ms 17.528 ms]
thrpt: [228.21 MiB/s 228.36 MiB/s 228.52 MiB/s]
change:
time: [-2.7255% -2.6410% -2.5548] (p = 0.00 < 0.05)
thrpt: [+2.6217% +2.7127% +2.8018]
Change within noise threshold.
Found 2 outliers among 100 measurements (2.00%)
2 (2.00%) high mildtransfer/walltime/pacing-true/varying-seeds: Change within noise threshold. time: [17.710 ms 17.720 ms 17.731 ms]
thrpt: [225.60 MiB/s 225.73 MiB/s 225.86 MiB/s]
change:
time: [-2.0017% -1.9228% -1.8436] (p = 0.00 < 0.05)
thrpt: [+1.8782% +1.9605% +2.0426]
Change within noise threshold.
Found 1 outliers among 100 measurements (1.00%)
1 (1.00%) high mildtransfer/walltime/pacing-false/same-seed: Change within noise threshold. time: [17.299 ms 17.311 ms 17.323 ms]
thrpt: [230.91 MiB/s 231.07 MiB/s 231.23 MiB/s]
change:
time: [-2.5059% -2.4215% -2.3274] (p = 0.00 < 0.05)
thrpt: [+2.3828% +2.4816% +2.5703]
Change within noise threshold.
Found 4 outliers among 100 measurements (4.00%)
4 (4.00%) high mildtransfer/walltime/pacing-true/same-seed: Change within noise threshold. time: [17.704 ms 17.714 ms 17.725 ms]
thrpt: [225.67 MiB/s 225.81 MiB/s 225.94 MiB/s]
change:
time: [-2.0284% -1.9449% -1.8634] (p = 0.00 < 0.05)
thrpt: [+1.8988% +1.9835% +2.0704]
Change within noise threshold.
Found 2 outliers among 100 measurements (2.00%)
1 (1.00%) low mild
1 (1.00%) high mildDownload data for |
|
Closing in favor of #3948 |
We tried this before but Claude insists this is a good idea...