Repository navigation
Description
Related: #3687, #3058, #4184
See also: #4346, #4352
A QUIC server can make each process_output() call on a neqo client take CPU time proportional to the number of client streams whose sending half it keeps from finishing. The cause is in SendStreams::write_frames() (neqo-transport/src/send_stream.rs): it visits every open send stream once per transmission priority, so five times for every 1-RTT packet the client tries to build, even when no stream has anything to send. The server only has to grant 1 byte of initial_max_stream_data_bidi_remote, never send MAX_STREAM_DATA, and keep sending small packets. It cannot open the streams itself, so this only matters when the client application has already opened thousands of streams on one connection. The result is a slowdown of the thread running neqo for as long as the connection lasts, and nothing more.
A send stream stays in SendStreams::map until its FIN or reset is acknowledged. On each of the five calls from Connection::write_appdata_frames(), has_data_at() is re-evaluated for every entry, and nothing remembers that an idle stream had nothing to send. A client stream that has used its single byte of credit sends STREAM_DATA_BLOCKED and then sits in State::Send indefinitely. The attached reproducer is an integration test using the transport Connection with default parameters, in a release build. With 20,000 such streams it measures about 0.9 ms of client time per 32-byte server packet, compared with 0.2 ms when the sending halves are allowed to finish. With 2,000 streams the figures are 54 µs and 11 µs. No STREAM, STREAM_DATA_BLOCKED or RESET_STREAM frames are sent during the timed calls.
Through Http3Client this walk is one of several per-packet costs that grow with the stream count, and not the largest. At 20,000 requests it adds about 0.75 ms per packet, and only when the application still holds unsent request bodies. In the GET case, Http3Connection::send_non_control_streams() accounts for most of the cost.
This is the same pattern that e1e66e7 removed from maybe_emit_writable_events() for MAX_DATA, but in a different loop that is still present on main. The per-packet walk goes back to bba17eb (2019) and is in every release since v0.1.0. It became five walks with the 2021 priority changes (38d3059, d5cc502).
Details
SendStreams::write_frames() asks every send stream of the connection whether it has a frame to send,
and Connection::write_appdata_frames() calls it five times, once per TransmissionPriority, for each
1-RTT packet that process_output() tries to build. With N streams whose sending half is still open, one
process_output() call evaluates SendStream::has_data_at() 5·N times, also when no stream has anything
to send and the call produces a bare ACK or nothing. How long a sending half stays open is up to the peer:
a stream that has used up its stream credit cannot be finished before MAX_STREAM_DATA arrives.
Measured with a Connection client with default parameters that writes an eight-byte message on each of N
bidirectional streams and closes a stream once the whole message was accepted. The server never reads or
answers, and then sends packets of 32 to 43 bytes, each with one byte on a unidirectional stream of its
own. The two columns differ only in the server's initial_max_stream_data_bidi_remote. The time is what
process_input() plus process_output() take for one such packet (release build, best of three runs of
2,000 packets):
| streams | 1 MiB of stream credit: sending halves finished and removed | 1 byte of stream credit: sending halves open |
|---|---|---|
| 2,000 | 10.6 µs | 54.4 µs |
| 20,000 | 208 µs | 901 µs |
During the timed calls the client's counters for STREAM, STREAM_DATA_BLOCKED and RESET_STREAM frames do
not move: no stream has anything to send. A temporary counter in has_data_at() shows 10,000 and 100,000
calls on the client per timed packet in the right column and none in the left. With the loop below
replaced by an iteration over only the streams that may have a frame, the right column equals the left
(10.6 and 204 µs). Without any streams the same packet costs 1.7 µs.
The loop (neqo-transport/src/send_stream.rs:2241, in SendStreams::write_frames()):
for stream in self.map.values_mut() {
if stream.is_fair() || !stream.has_data_at(priority) {
continue;
}
trace!(" {stream}");
if !stream.write_frames(priority, builder, tokens, stats) {
break;
}
}self.map holds every send stream from its creation until remove_ended() (send_stream.rs:2171) finds
it in DataRecvd or ResetRecvd (is_ended(), :1440), that is, until the peer has acknowledged its
FIN or its reset. has_data_at() (:777) looks at the stream state, at the flow-control state for a
STREAM_DATA_BLOCKED frame that is due, and at the send buffer for unsent or lost bytes. For an idle stream
the answer is false at every priority, and nothing remembers that. When there are fair (WebTransport)
streams, all in one send group and without a send order, a second loop walks map once more (:2284).
write_appdata_frames() makes the call for Critical, Important, High and Normal, and Low
(neqo-transport/src/connection/mod.rs:2416, :2428, :2449, :2483). It runs from
Connection::write_frames() (:2623) each time output_dgram_on_path() sets up a short-header packet on
the primary path (:2882); if no frame was written the packet is abandoned afterwards (:2884), so a
process_output() call that returns only a timer pays for the five walks too. They are skipped while the
send profile is ACK-only, that is, while the congestion window is used up or pacing holds the next packet
back (:2609).
The neighbours of this loop already avoid a walk when nothing has changed: remove_ended() returns at once
unless has_ended is set (:2172), and maybe_emit_writable_events() returns at once unless a stream can
be waiting for connection credit (:2426, added in e1e66e7, "so a peer cannot make each MAX_DATA frame
cost O(streams)"). 281135a added has_data_at() to make each visit in write_frames() cheaper; the
visits themselves remained. The walk over every stream for each packet goes back to bba17eb
("Implement stream send and receive", 2019-03-01), the first commit that sent stream data, and is in every
release since v0.1.0; 38d3059 and d5cc502 (2021-02-11, stream priorities) turned one walk per packet
into four and then five.
How the right column comes about: the server advertises initial_max_stream_data_bidi_remote = 1.
SendStream::send() accepts only what flow control allows (avail(), :1409, used in send_internal(),
:1471), so stream_send() takes one byte of the eight, and the application, which still holds seven,
cannot close the stream. The client sends that byte and one STREAM_DATA_BLOCKED frame per stream; after
that the stream is in State::Send with nothing to send, and it stays in map because the server never
sends MAX_STREAM_DATA. In the left column the message fits, its FIN is acknowledged and the send stream is
removed. The receiving halves are open in both columns; they have a per-packet walk of their own
(RecvStreams::write_frames(), neqo-transport/src/recv_stream.rs:65), which is why the left column
grows with the stream count as well. That is a different loop and not the subject here.
Impact
A server can make every process_output() call of a client cost CPU time in proportion to the number of
streams whose sending half it keeps from finishing: about 35 ns per stream with 20,000 streams, 22 ns with
2,000. It chooses both transport parameters involved (initial_max_streams_bidi and
initial_max_stream_data_bidi_remote) and then only has to send packets; an application calls
process_output() after every datagram or batch of datagrams it has fed in. What the server cannot do
itself is open the streams: it needs an application that opens many streams on one connection. Neqo sets
no limit of its own on that besides the peer's stream limit; Http3Client::fetch() goes straight to
Connection::stream_create() (neqo-http3/src/connection.rs:936). An Http3Client gets into the same
state: with a server that grants one byte of stream credit and does not read, 20,000 GET requests are
accepted, each request stream sends STREAM_DATA_BLOCKED and none can finish its sending half.
Through Http3Client, this walk is one of several per-packet costs that grow with the stream count, and
not the largest. With 20,000 requests whose sending halves are finished, a small server packet already
costs the client 0.42 ms. When the application still holds unsent request bodies (a POST body larger than
the stream credit), this walk adds about 0.75 ms, for 1.2 ms in total. In the GET case above a packet
costs 6.8 to 7.6 ms, almost all of it per-call work in neqo-http3 for requests that wait for credit
(Http3Connection::send_non_control_streams(), neqo-http3/src/connection.rs:419); without this walk it
is still 6.4 ms.
For an application on the transport Connection, with 20,000 such streams a 32-byte packet costs the
client 0.9 ms instead of 0.2 ms, so about 1,100 of
them per second, less than 50 kB/s, keep the thread that runs neqo busy; with 2,000 streams it takes about
18,000 packets per second. The effect is a slowdown of that thread for as long as the connection is open,
and nothing else.
Suggested fix
The attached patch changes only neqo-transport/src/send_stream.rs and no signatures. It lets
SendStreams keep track of the streams that may have a frame to send, in a new
pending: BTreeSet<usize> of map indices, and has write_frames() iterate that set instead of map:
in the unfair loop (moved to write_unfair_frames(), still in creation order) and in both fair
(WebTransport) paths, where the fair_rr_next cursor walks the set in the same circular order. A stream
leaves the set once the new SendStream::has_data() (has_data_at() for any priority) is false.
A stream enters the set on insert() if it already has something to send, and after get_mut() has
handed it out: get_mut() remembers its index in last_mut, and the next get_mut(), write_frames()
or remove_ended() checks has_data() for it once. lost(), reset_lost() and blocked_lost() now go
through get_mut() for the same reason, and IntoIterator for &mut SendStreams marks every stream as
pending. remove_ended() re-maps the indices that extract_if shifts. Adding the stream in get_mut()
unconditionally would be simpler but too coarse: Http3Client offers the buffered data of every request
that waits for credit to the transport again on each call (send_non_control_streams()), which would
put all of them back into the set and make Http3Client::process_output() with 20,000 credit-blocked
requests about twice as slow; with the deferred check only streams that really got a frame queued become
pending. The patch adds three unit tests; with it applied the reproducer's OBSERVED and CONTROL times are
equal.
Two things to weigh before merging:
- With several send groups or sendOrder buckets, a call that finds no fair stream with data at that
priority (fair_has_data_at()) now skips the group passes and only advancesper_group_next, so a
bucket's round-robin cursor that points past its end after a removal is wrapped to 0 at the next pass
with data rather than at the next call. - In the
send_streamscriterion bench idle streams get faster (20 streams, 1 active: 177 ns to about
100 ns), butwrite_frames()is 12-28 % slower when every fair stream is active (20 fair streams:
0.84 to 1.08 µs).
The patch removes this walk only. For the per-packet cost to stop growing with the stream count,
RecvStreams::write_frames() (neqo-transport/src/recv_stream.rs:65) and, for HTTP/3,
Http3Connection::send_non_control_streams() (neqo-http3/src/connection.rs:419) need the same
treatment.
Proposed patches
patches/1.patch
# neqo-transport/src/send_stream.rs
# SendStreams tracks the streams that may have a frame to send, so write_frames stops walking every open send
# stream for every packet
#
# SendStreams::write_frames re-derived 'which streams have a frame due' by calling has_data_at() on every open
# send stream, five times per packet, so a peer that keeps sending halves open (no stream credit) sets the
# per-packet cost. The patch keeps that knowledge in SendStreams, the owner of the map: a BTreeSet of map
# indices ('pending') that write_frames iterates instead of the map, for the unfair loop and for both fair
# (WebTransport) paths; a stream is dropped once it has nothing left at any priority, and remove_ended
# re-maps the indices it shifts. It starts from the scanner's hint but does not add a stream in get_mut
# unconditionally: measured here, that makes Http3Client::process_output with 20,000 credit-blocked requests
# about twice as slow (5.3 ms to 10.7-12 ms), because HTTP/3 re-offers blocked data on every call. Instead
# get_mut remembers the stream it handed out and the next get_mut/write_frames/remove_ended checks the new
# has_data() once, so only streams that really got a frame queued (send, close, reset, lost frame,
# STREAM_DATA_BLOCKED) become pending; the same case now takes 4.3-4.7 ms, and no signature or caller
# changes. Checked: cargo +nightly fmt, clippy -D warnings (also benches), the whole test suite (1960 pass,
# three new unit tests), and a throw-away randomized comparison against the old write_frames (20,000 seeds,
# 1.5 M packets; unfair, single-group, multi-group and sendOrder mixes) that produced byte-identical
# packets, tokens and group cursors. Behaviour change to know about: with several send groups or sendOrder
# buckets, a call that finds no fair stream with data now skips the group passes, so a bucket's round-robin
# cursor that points past its end after a removal is wrapped to 0 at the next pass with data rather than at
# the next call. The existing send_streams criterion bench improves for idle streams (20 streams, 1 active:
# 177 ns to about 100 ns) and gets 12-28 % slower where every stream is active (20 fair streams: 0.84 to
# 1.08 us), which is the
# reviewer: good — Fixes the root cause (write_frames visits only streams that may have a frame) inside
# send_stream.rs with no signature changes; full test suite, clippy -D warnings and nightly fmt pass, and
# both their reproducer and my HTTP/3 test drop to the control figure. Before merging, check the
# send_streams benchmark: the author reports 12-28% slower write_frames when every fair stream is active.
# our check: FIXED · confidence medium
#
diff --git a/neqo-transport/src/send_stream.rs b/neqo-transport/src/send_stream.rs
index 6c9e3490..f15c2c70 100644
--- a/neqo-transport/src/send_stream.rs
+++ b/neqo-transport/src/send_stream.rs
@@ -9,7 +9,7 @@
use std::{
cell::RefCell,
cmp::{Ordering, max, min},
- collections::{BTreeMap, VecDeque, btree_map::Entry},
+ collections::{BTreeMap, BTreeSet, VecDeque, btree_map::Entry},
fmt::{self, Display, Formatter},
mem,
num::NonZeroUsize,
@@ -807,6 +807,22 @@ impl SendStream {
self.has_next_bytes(retransmission)
}
+ /// Returns `true` if [`Self::has_data_at`] is `true` for any priority.
+ ///
+ /// Any change to `has_data_at` must also be reflected here.
+ fn has_data(&mut self) -> bool {
+ match &self.state {
+ State::ResetSent { priority, .. } => return priority.is_some(),
+ State::ResetSentReliable {
+ priority: Some(_), ..
+ } => return true,
+ State::Ready { fc, .. } | State::Send { fc, .. } if fc.is_blocked() => return true,
+ _ => {}
+ }
+ // What is due for retransmission is also due at the stream's own priority.
+ self.has_next_bytes(false)
+ }
+
/// Return `false` if the builder is full and the caller should stop iterating.
///
/// Any new frame type added here must also be reflected in `has_data_at`.
@@ -1927,6 +1943,16 @@ pub struct SendStreams {
fair_rr_next: usize,
max_low_watermark: Option<NonZeroUsize>, // Upper bound of the streams' low watermarks.
+
+ /// Indices into `map` of the streams that might have a frame to send, which spares
+ /// `write_frames` a walk of every open stream for every packet. A stream is added
+ /// when it has a frame to send after it was inserted or modified or lost a frame,
+ /// and removed once `write_frames` finds that it has nothing left at any priority.
+ pending: BTreeSet<usize>,
+ /// Index into `map` of the stream that `get_mut` handed out last. What the caller
+ /// does with that stream is only known afterwards, so `update_pending` checks it
+ /// before `pending` is used and before the next stream is handed out.
+ last_mut: Option<usize>,
}
impl SendStreams {
@@ -1945,7 +1971,22 @@ impl SendStreams {
reason = "OK here."
)]
pub fn get_mut(&mut self, id: StreamId) -> Res<&mut SendStream> {
- self.map.get_mut(&id).ok_or(Error::InvalidStreamId)
+ self.update_pending();
+ let (index, _, stream) = self.map.get_full_mut(&id).ok_or(Error::InvalidStreamId)?;
+ // The caller might queue data, or close or reset the stream.
+ self.last_mut = Some(index);
+ Ok(stream)
+ }
+
+ /// Add the stream that `get_mut` handed out last to `pending` if it now has a frame
+ /// to send.
+ fn update_pending(&mut self) {
+ if let Some(index) = self.last_mut.take()
+ && let Some((_, stream)) = self.map.get_index_mut(index)
+ && stream.has_data()
+ {
+ self.pending.insert(index);
+ }
}
#[must_use]
@@ -1953,8 +1994,12 @@ impl SendStreams {
self.map.contains_key(&id)
}
- pub fn insert(&mut self, id: StreamId, stream: SendStream) {
- self.map.insert(id, stream);
+ pub fn insert(&mut self, id: StreamId, mut stream: SendStream) {
+ let pending = stream.has_data();
+ let (index, _) = self.map.insert_full(id, stream);
+ if pending {
+ self.pending.insert(index);
+ }
}
/// Insert `stream_id` into group `gid`'s queue for `sendorder`, creating the group
@@ -2141,25 +2186,27 @@ impl SendStreams {
}
pub fn lost(&mut self, token: &RecoveryToken) {
- if let Some(ss) = self.map.get_mut(&token.id) {
+ if let Ok(ss) = self.get_mut(token.id) {
ss.mark_as_lost(token.offset, expect_usize(token.length), token.fin);
}
}
pub fn reset_lost(&mut self, stream_id: StreamId) {
- if let Some(ss) = self.map.get_mut(&stream_id) {
+ if let Ok(ss) = self.get_mut(stream_id) {
ss.reset_lost();
}
}
pub fn blocked_lost(&mut self, stream_id: StreamId, limit: u64) {
- if let Some(ss) = self.map.get_mut(&stream_id) {
+ if let Ok(ss) = self.get_mut(stream_id) {
ss.blocked_lost(limit);
}
}
pub fn clear(&mut self) {
self.map.clear();
+ self.pending.clear();
+ self.last_mut = None;
self.has_ended = false;
self.per_group.clear();
self.per_group_next = 0;
@@ -2173,6 +2220,12 @@ impl SendStreams {
return false;
}
self.has_ended = false;
+ self.update_pending();
+ // `extract_if` shifts `map` indices, so carry `pending` over by stream ID.
+ let pending = mem::take(&mut self.pending)
+ .into_iter()
+ .filter_map(|index| self.map.get_index(index).map(|(&id, _)| id))
+ .collect::<SmallVec<[_; 8]>>();
let mut removed = false;
for (stream_id, stream) in self.map.extract_if(.., |_, s| s.is_ended()) {
removed = true;
@@ -2183,6 +2236,10 @@ impl SendStreams {
}
}
}
+ self.pending = pending
+ .iter()
+ .filter_map(|id| self.map.get_index_of(id))
+ .collect();
// Clean up now-empty groups.
self.per_group.retain(|_, grp| !grp.is_empty());
if self.per_group_next >= self.per_group.len() {
@@ -2197,6 +2254,52 @@ impl SendStreams {
removed
}
+ /// Write frames for the streams without fairness, in `map` order.
+ ///
+ /// Only the streams in `pending` can have something to send. Those that turn out to
+ /// have nothing left at any priority, fair or not, are dropped from `pending`.
+ fn write_unfair_frames<B: Buffer>(
+ &mut self,
+ priority: TransmissionPriority,
+ builder: &mut packet::Builder<B>,
+ tokens: &mut recovery::Tokens,
+ stats: &mut FrameStats,
+ ) {
+ trace!("processing streams... unfair:");
+ self.update_pending();
+ let mut drained = SmallVec::<[_; 8]>::new();
+ for &idx in &self.pending {
+ let Some((_, stream)) = self.map.get_index_mut(idx) else {
+ continue;
+ };
+ if !stream.has_data_at(priority) {
+ if !stream.has_data() {
+ drained.push(idx);
+ }
+ continue;
+ }
+ if stream.is_fair() {
+ continue;
+ }
+ trace!(" {stream}");
+ if !stream.write_frames(priority, builder, tokens, stats) {
+ break;
+ }
+ }
+ for idx in drained {
+ self.pending.remove(&idx);
+ }
+ }
+
+ /// Whether a fair stream has something to send at `priority`.
+ fn fair_has_data_at(&mut self, priority: TransmissionPriority) -> bool {
+ let map = &mut self.map;
+ self.pending.iter().any(|&idx| {
+ map.get_index_mut(idx)
+ .is_some_and(|(_, s)| s.is_fair() && s.has_data_at(priority))
+ })
+ }
+
pub fn write_frames<B: Buffer>(
&mut self,
priority: TransmissionPriority,
@@ -2237,16 +2340,7 @@ impl SendStreams {
// First: unfair streams (non-WebTransport H3 streams, by creation order).
// Then: all fair streams via per-group round-robin (includes null sendGroup).
- trace!("processing streams... unfair:");
- for stream in self.map.values_mut() {
- if stream.is_fair() || !stream.has_data_at(priority) {
- continue;
- }
- trace!(" {stream}");
- if !stream.write_frames(priority, builder, tokens, stats) {
- break;
- }
- }
+ self.write_unfair_frames(priority, builder, tokens, stats);
// Send groups: round-robin between all groups, including NULL_GROUP_ID (ungrouped
// fair streams). The null sendGroup is bandwidth-equal to all explicit sendGroups
// (spec: "The user agent considers WebTransportSendGroups as equals when allocating
@@ -2272,6 +2366,7 @@ impl SendStreams {
// Walk `map` by index rather than via the group's `regular` OrderGroup:
// `get_index_mut` is direct Vec access (no per-stream hash lookup), giving
// the same cache-friendly cost as the original `values_mut()` walk.
+ // Only the indices in `pending` are visited, in the same circular order.
// `fair_rr_next` is a round-robin cursor into `map`; when the builder fills
// mid-pass we resume at the stream *after* the one that filled, so later
// fair streams are not starved (WebTransport spec write-chunk 6.3 step 6.1:
@@ -2281,8 +2376,8 @@ impl SendStreams {
self.fair_rr_next = 0;
}
let start = self.fair_rr_next;
- for off in 0..n {
- let idx = (start + off) % n;
+ let (before, from) = (self.pending.range(..start), self.pending.range(start..));
+ for &idx in from.chain(before) {
// `idx < n`, so this always succeeds; `else` is just to avoid a panic.
let Some((_, stream)) = self.map.get_index_mut(idx) else {
continue;
@@ -2301,6 +2396,14 @@ impl SendStreams {
self.per_group_next = 0;
}
let start = self.per_group_next;
+ // The passes below look at every fair stream, which is only worth it when one
+ // of them has something to send at this priority. Otherwise they write nothing
+ // and all that is left to do is the cursor update at the end. (With a full
+ // builder they stop at the first stream, so there is nothing to save.)
+ if !builder.is_full() && !self.fair_has_data_at(priority) {
+ self.per_group_next = (start + 1) % num_groups;
+ return;
+ }
// Split borrows on disjoint fields so we can access both per_group (for
// priority ordering) and map (for the stream itself) in the same loop body
// without an intermediate Vec.
@@ -2445,6 +2548,8 @@ impl<'a> IntoIterator for &'a mut SendStreams {
type IntoIter = indexmap::map::IterMut<'a, StreamId, SendStream>;
fn into_iter(self) -> indexmap::map::IterMut<'a, StreamId, SendStream> {
+ // The caller can modify any of the streams.
+ self.pending = (0..self.map.len()).collect();
self.map.iter_mut()
}
}
@@ -3805,6 +3910,113 @@ mod tests {
);
}
+ /// Three idle streams, which share connection flow control.
+ fn three_streams() -> ([StreamId; 3], SendStreams) {
+ let conn_fc = connection_fc(1 << 20);
+ let conn_events = ConnectionEvents::default();
+ let ids = [0, 4, 8].map(StreamId::from);
+ let mut ss = SendStreams::default();
+ for id in ids {
+ let s = SendStream::new(id, 1 << 20, Rc::clone(&conn_fc), conn_events.clone());
+ ss.insert(id, s);
+ }
+ (ids, ss)
+ }
+
+ /// Write what `ss` has to send at the default priority into a fresh packet.
+ fn write_default_priority(ss: &mut SendStreams) -> recovery::Tokens {
+ let mut tokens = recovery::Tokens::new();
+ let mut builder =
+ packet::Builder::short(Encoder::default(), false, None::<&[u8]>, packet::LIMIT);
+ ss.write_frames(
+ TransmissionPriority::default(),
+ &mut builder,
+ &mut tokens,
+ &mut FrameStats::default(),
+ );
+ tokens
+ }
+
+ /// `write_frames` only looks at the streams that might have something to send: a
+ /// stream is looked at once a modification or the loss of a frame has left it with
+ /// something to send, and is forgotten once it is drained.
+ #[test]
+ fn write_frames_tracks_pending_streams() {
+ let (ids, mut ss) = three_streams();
+
+ // A modification that queues nothing does not make a stream pending.
+ ss.get_mut(ids[0]).unwrap().set_max_stream_data(1 << 21);
+ assert!(write_default_priority(&mut ss).is_empty());
+ assert!(ss.pending.is_empty());
+
+ // Writing to a stream does, until the data is sent.
+ ss.get_mut(ids[1]).unwrap().send(b"hello").unwrap();
+ let tokens = write_default_priority(&mut ss);
+ assert_eq!(tokens.len(), 1);
+ assert_eq!(as_stream_token(&tokens[0]).id, ids[1]);
+ assert!(write_default_priority(&mut ss).is_empty());
+ assert!(ss.pending.is_empty());
+
+ // So does the loss of that data.
+ ss.lost(as_stream_token(&tokens[0]));
+ let tokens = write_default_priority(&mut ss);
+ assert_eq!(tokens.len(), 1);
+ assert_eq!(as_stream_token(&tokens[0]).id, ids[1]);
+
+ // And so does closing or resetting a stream, for each stream that is modified.
+ ss.get_mut(ids[0]).unwrap().close();
+ ss.get_mut(ids[2]).unwrap().reset(0);
+ assert_eq!(write_default_priority(&mut ss).len(), 2);
+ assert!(write_default_priority(&mut ss).is_empty());
+ assert!(ss.pending.is_empty());
+ }
+
+ /// Fair streams are tracked in the same way, in one send group and in several.
+ #[test]
+ fn write_frames_tracks_pending_fair_streams() {
+ let (ids, mut ss) = three_streams();
+ for id in ids {
+ ss.set_fairness(id, true).unwrap();
+ }
+
+ ss.get_mut(ids[2]).unwrap().send(b"hello").unwrap();
+ let tokens = write_default_priority(&mut ss);
+ assert_eq!(tokens.len(), 1);
+ assert_eq!(as_stream_token(&tokens[0]).id, ids[2]);
+ assert!(write_default_priority(&mut ss).is_empty());
+ assert!(ss.pending.is_empty());
+
+ ss.set_sendgroup(ids[0], Some(SendGroupId::new(1))).unwrap();
+ assert!(write_default_priority(&mut ss).is_empty());
+ ss.get_mut(ids[0]).unwrap().send(b"hello").unwrap();
+ ss.get_mut(ids[1]).unwrap().send(b"hello").unwrap();
+ assert_eq!(write_default_priority(&mut ss).len(), 2);
+ assert!(write_default_priority(&mut ss).is_empty());
+ assert!(ss.pending.is_empty());
+ }
+
+ /// Removing ended streams moves the streams after them in `map`, which must not make
+ /// `write_frames` lose track of a stream that has something to send.
+ #[test]
+ fn remove_ended_keeps_pending_streams() {
+ let (ids, mut ss) = three_streams();
+
+ // The first stream ends: its FIN is sent and acknowledged.
+ ss.get_mut(ids[0]).unwrap().close();
+ let tokens = write_default_priority(&mut ss);
+ assert_eq!(tokens.len(), 1);
+ ss.acked(as_stream_token(&tokens[0]));
+
+ // The last stream has data when the first one is removed.
+ ss.get_mut(ids[2]).unwrap().send(b"hello").unwrap();
+ assert!(ss.remove_ended());
+ assert!(!ss.exists(ids[0]));
+
+ let tokens = write_default_priority(&mut ss);
+ assert_eq!(tokens.len(), 1);
+ assert_eq!(as_stream_token(&tokens[0]).id, ids[2]);
+ }
+
#[test]
// Verify lost frames handle fin properly with zero length fin
fn send_stream_get_frame_zerolength_fin() {
@@ -4486,6 +4698,7 @@ mod tests {
"has_data_at({prio:?})",
);
}
+ assert_eq!(s.has_data(), !expected.is_empty(), "has_data()");
}
// An idle stream (no data, no pending frames) reports false at every priority.When fixing this, please carry this line into the commit message:
Discovered by Anthropic's OSS Scanner, as vulnerability ANT-2026-GX6H53N7.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity