Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! RFC 9002 §7: how much may be in the air at once.//!//! The NewReno controller of Appendix B, which is the one QUIC specifies and//! the one an endpoint is entitled to replace — §7 says so explicitly, and//! the signals QUIC provides are generic enough that CUBIC or BBR reads the//! same inputs. What is not optional is having one at all: an endpoint that//! sends whatever it has whenever it can is the reason the internet needs//! congestion control, and it is also the reason a QUIC implementation with//! no controller has no business on a network it shares.//!//! ## What the controller is counting//!//! Bytes, not packets, and only the bytes of packets that will be//! acknowledged. §7: "packets containing only ACK frames do not count toward//! bytes in flight and are not congestion controlled", because a sender that//! throttled its own acknowledgements would be throttling the feedback the//! controller runs on. Everything else — including PADDING, which is how a//! client's first datagram reaches 1200 octets — counts, since it occupies//! the path exactly as much as data would.//!//! ## One controller, three spaces//!//! §7: "The congestion controller is per path". The three packet number//! spaces are three sets of keys sharing one path, so they share one window;//! loss detection is per space because a packet number means nothing outside//! its own, but the network they all traverse does not know about any of it.//!//! ## Not here//!//! Pacing (§7.7), which spreads a window's worth of packets over a round trip//! instead of sending them back to back. It needs a timer the caller drives//! and belongs above this. And ECN marking: this reads the peer's CE counter//! and reacts to it (§7.1), but nothing here can *set* the codepoint, which//! lives in the IP header that a QUIC library never touches — a caller that//! marks its datagrams will find the reaction already implemented.
const std = @import("std");
const recovery = @import("recovery.zig");
pub const Instant = recovery.Instant;pub const Duration = recovery.Duration;
/// §14.1 of RFC 9000: the smallest maximum datagram size QUIC permits, and/// the value to assume before path MTU discovery has said otherwise.pub const min_datagram_size: usize = 1200;
/// §7.2: "Endpoints SHOULD use an initial congestion window of ten times the/// maximum datagram size, while limiting the window to the larger of 14,720/// bytes or twice the maximum datagram size."////// Ten packets is a starting guess large enough to finish most handshakes in/// one flight and small enough that guessing wrong is not a burst. The 14,720/// ceiling is RFC 6928's ten-segment window adjusted for UDP's smaller/// header, which the RFC notes is where the number comes from.pub fn initialWindow(max_datagram_size: usize) usize { return @min(10 * max_datagram_size, @max(14_720, 2 * max_datagram_size));}
test initialWindow { // Ten 1200-octet datagrams fit under the ceiling; ten 1500-octet ones // do not, and are held to 14,720. try std.testing.expectEqual(@as(usize, 12_000), initialWindow(min_datagram_size)); try std.testing.expectEqual(@as(usize, 14_720), initialWindow(1500));}
/// §7.2: "The minimum congestion window is the smallest value the congestion/// window can attain in response to loss... The RECOMMENDED value is 2 */// max_datagram_size."////// Two rather than one so that a sender in trouble can still put a packet on/// the path while another is outstanding, which is what lets it recover at/// all rather than waiting a round trip per packet.pub fn minimumWindow(max_datagram_size: usize) usize { return 2 * max_datagram_size;}
test minimumWindow { try std.testing.expectEqual(@as(usize, 2400), minimumWindow(min_datagram_size));}
/// §7.3.2: the window is halved on a congestion event. Held as a pair of/// integers because `kLossReductionFactor` is 0.5 and this arithmetic has no/// business being floating point.pub const loss_reduction_numerator: usize = 1;pub const loss_reduction_denominator: usize = 2;
/// §7.6: `kPersistentCongestionThreshold`, 3 probe timeouts. "Larger values/// cause the sender to become less responsive to persistent congestion, which/// can result in aggressive sending into a congested network. Too small a/// value can result in a sender declaring persistent congestion/// unnecessarily."pub const persistent_congestion_threshold: u64 = 3;
/// RFC 6356 §3: what one path's congestion avoidance needs to know about/// the others -- "the congestion window on subflow i is increased by/// min(alpha*bytes_acked*MSS_i/cwnd_total, bytes_acked*MSS_i/cwnd_i)".pub const Coupling = struct { /// "A parameter of the algorithm that describes the aggressiveness of /// the multipath flow", computed by `linked`. alpha: f64, /// "The sum of the congestion windows of all subflows." total: usize,
/// One path's window and smoothed RTT, for `linked`. pub const Path = struct { window: usize, rtt: Duration };
/// RFC 6356 §3's alpha over `paths`: /// /// alpha = cwnd_total * max_i(cwnd_i / rtt_i^2) / (sum_i(cwnd_i / rtt_i))^2 /// /// which is 1 for one path, and 1/n for n paths alike -- so n paths /// through a shared bottleneck together take what one flow would. /// /// `rtt` is in any unit so long as every path uses the same one, since /// it cancels. Null when there is nothing to couple: an empty list, a /// total window of zero, or any path with no RTT yet, for which /// `rtt_i^2` would divide by zero. pub fn linked(paths: []const Path) ?Coupling { var total: usize = 0; var best: f64 = 0; var sum: f64 = 0; for (paths) |p| { if (p.rtt == 0) return null; const w: f64 = @floatFromInt(p.window); const r: f64 = @floatFromInt(p.rtt); total += p.window; best = @max(best, w / (r * r)); sum += w / r; } if (total == 0 or sum == 0) return null; return .{ .alpha = @as(f64, @floatFromInt(total)) * best / (sum * sum), .total = total }; }
test linked { // Two paths with the same window and RTT share one flow's // aggressiveness between them. const k = Coupling.linked(&.{ .{ .window = 12_000, .rtt = 40 * std.time.ns_per_ms }, .{ .window = 12_000, .rtt = 40 * std.time.ns_per_ms }, }).?; try std.testing.expectApproxEqAbs(@as(f64, 0.5), k.alpha, 1e-9); try std.testing.expectEqual(@as(usize, 24_000), k.total);
// A path with no RTT sample yet leaves nothing to compute. try std.testing.expectEqual(@as(?Coupling, null), Coupling.linked(&.{.{ .window = 12_000, .rtt = 0 }})); }
fn increase(k: Coupling, acked: usize, mss: usize) usize { const bytes: f64 = @floatFromInt(acked * mss); return @intFromFloat(k.alpha * bytes / @as(f64, @floatFromInt(k.total))); }};
/// A NewReno sender's window: one per path, shared by the packet number/// spaces on it.pub const Controller = struct { /// §B.2: "The sender's current maximum payload size... with a minimum /// value of 1200 bytes." Path MTU discovery would raise it; nothing in /// this library does yet, so it stays at the floor QUIC guarantees. max_datagram_size: usize = min_datagram_size, window: usize = initialWindow(min_datagram_size), in_flight: usize = 0, /// §7.3.1: "A sender begins in slow start because the slow start /// threshold is initialized to an infinite value." ssthresh: usize = std.math.maxInt(usize), /// §B.2: when the current recovery period began. A packet sent before /// this does not grow the window when it is acknowledged, which is what /// limits the window to one reduction per round trip. recovery_start: ?Instant = null, /// §7.6.2: "The persistent congestion period SHOULD NOT start until there /// is at least one RTT sample", because before one the probe timeout is /// built on a 333ms guess that may be far larger than the path. first_rtt_sample: ?Instant = null, /// §B.5: "Do not increase congestion_window if application limited." /// /// A sender with nothing to send leaves the window unused, and an unused /// window is not evidence the path would have carried it. Growing on that /// evidence is how a controller talks itself into a window the network /// never agreed to — which matters here, because a handshake is almost /// entirely application limited. app_limited: bool = false, /// §B.7: the highest ECN-CE count the peer has reported, per space. An /// increase is a congestion signal from the path itself rather than an /// inference drawn from a missing packet. ce_count: [3]u64 = .{ 0, 0, 0 },
/// How many more bytes may be put on the path. /// /// §7: "An endpoint MUST NOT send a packet if it would cause /// bytes_in_flight to be larger than the congestion window, unless the /// packet is sent on a PTO timer expiration or when entering recovery." /// Those two exceptions are the caller's to make — a probe that the /// window forbade would leave a stalled connection with no way to find /// out that it was stalled. pub fn available(c: *const Controller) usize { return c.window -| c.in_flight; }
test available { var c: Controller = .{}; c.onSent(10_000); // 12,000 of window, 10,000 of it in the air. try std.testing.expectEqual(@as(usize, 2000), c.available()); }
/// §B.4: counts `bytes` as in flight, for a packet containing anything /// but ACK frames -- including PADDING -- that has just been sent. An /// ACK-only packet is not reported at all. pub fn onSent(c: *Controller, bytes: usize) void { c.in_flight += bytes; }
test onSent { var c: Controller = .{}; c.onSent(1200); try std.testing.expectEqual(@as(usize, 1200), c.in_flight); }
/// Notes that an RTT sample was taken at `now`. Only the first call /// matters: it is when §7.6.2's persistent congestion may start being /// counted from, so a packet sent before it cannot be part of one. pub fn onRttSample(c: *Controller, now: Instant) void { if (c.first_rtt_sample == null) c.first_rtt_sample = now; }
test onRttSample { var c: Controller = .{}; c.onRttSample(5000); c.onRttSample(9000); try std.testing.expectEqual(@as(?Instant, 5000), c.first_rtt_sample); }
/// §B.5, on a packet the peer acknowledged: its bytes leave flight, and /// the window grows unless the sender is application limited or the /// packet predates the current recovery period. `now` is not used. pub fn onAcked(c: *Controller, sent: recovery.Sent, now: Instant) void { c.onAckedCoupled(sent, now, null); }
test onAcked { var c: Controller = .{}; const packet: recovery.Sent = .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }; c.onSent(packet.size); c.onAcked(packet, 50_000_000); // Slow start: the window grows by what was acknowledged. try std.testing.expectEqual(@as(usize, 0), c.in_flight); try std.testing.expectEqual(initialWindow(min_datagram_size) + 1200, c.window); }
/// The same, with congestion avoidance coupled to the connection's other /// paths by `coupling` -- RFC 6356's linked increases, which /// draft-ietf-quic-multipath-21 §5.3 says "can immediately be adapted to /// Multipath QUIC". Slow start and the response to loss are unchanged: /// "the algorithm only applies to the increase phase of the congestion /// avoidance state" (RFC 6356 §3). pub fn onAckedCoupled(c: *Controller, sent: recovery.Sent, now: Instant, coupling: ?Coupling) void { _ = now; c.in_flight -|= sent.size; if (c.app_limited) return; // §B.5: a packet sent before the current recovery period began says // nothing about whether the reduction worked, so it does not grow the // window. This is what makes a recovery period one round trip long // rather than one packet long. if (c.inRecovery(sent.time)) return;
if (c.window < c.ssthresh) { // §7.3.1 slow start: "the congestion window increases by the // number of bytes acknowledged", which doubles it every round // trip until something goes wrong. c.window +|= sent.size; } else { // §7.3.3 congestion avoidance: at most one datagram per window // acknowledged, so the window grows by one packet per round trip // instead of doubling. The division is done last to keep the // integer arithmetic from rounding the increase away. const uncoupled = c.max_datagram_size * sent.size / c.window; const increase = if (coupling) |k| @min(k.increase(sent.size, c.max_datagram_size), uncoupled) else uncoupled; c.window +|= increase; } }
test onAckedCoupled { // Two paths alike, both past slow start. const k = Coupling.linked(&.{ .{ .window = 12_000, .rtt = 40 * std.time.ns_per_ms }, .{ .window = 12_000, .rtt = 40 * std.time.ns_per_ms }, }).?; var c: Controller = .{ .ssthresh = 1 }; const packet: recovery.Sent = .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }; c.onSent(packet.size); c.onAckedCoupled(packet, 50_000_000, k); // alpha * acked * MSS / cwnd_total = 0.5 * 1200 * 1200 / 24,000 = // 30 octets, where one path alone would have grown by 120. try std.testing.expectEqual(@as(usize, 12_030), c.window); }
/// §B.8, on packets loss detection has declared gone. /// /// Their bytes leave flight, and unless the newest of them was sent /// before the current recovery period began, the window is halved and a /// new period starts at `now`. If they also span a persistent congestion /// period, the window drops to the minimum. /// /// `pto` is the probe timeout computed with `max_ack_delay` included /// whatever the space — §7.6.1 is explicit that persistent congestion /// uses it unconditionally, unlike §6.2.1's timer. pub fn onLost(c: *Controller, lost: []const recovery.Sent, pto: Duration, now: Instant) void { if (lost.len == 0) return;
var latest: Instant = 0; for (lost) |p| { c.in_flight -|= p.size; latest = @max(latest, p.time); } c.onCongestionEvent(latest, now);
// §7.6.2, and §B.8's guard: only packets sent after the first RTT // sample count, because before one the probes were spaced by a guess. const first = c.first_rtt_sample orelse return; const duration = pto *| persistent_congestion_threshold; if (!persistent(lost, first, duration)) return;
// §7.6.2: "When persistent congestion is declared, the sender's // congestion window MUST be reduced to the minimum congestion // window." The path has stopped carrying anything for several probe // timeouts; there is no window left to defend. c.window = minimumWindow(c.max_datagram_size); c.recovery_start = null; }
test onLost { var c: Controller = .{}; c.onSent(3600); const lost = [_]recovery.Sent{ .{ .number = 4, .time = 1000, .ack_eliciting = true, .size = 1200 }, .{ .number = 5, .time = 1001, .ack_eliciting = true, .size = 1200 }, }; c.onLost(&lost, 300 * std.time.ns_per_ms, 2000); // One congestion event for both, so the window is halved once. try std.testing.expectEqual(initialWindow(min_datagram_size) / 2, c.window); try std.testing.expectEqual(@as(usize, 1200), c.in_flight); }
/// §B.7: the peer's ACK frame reported `ce` Congestion Experienced marks /// in packet number space `space` (0 Initial, 1 Handshake, 2 application /// data). A count higher than any seen before for that space is a /// congestion event, dated by `largest_sent` -- when the largest packet /// that ACK acknowledged was sent -- so that it starts no new recovery /// period when that packet predates the current one. pub fn onEcn(c: *Controller, space: usize, ce: u64, largest_sent: Instant, now: Instant) void { if (ce <= c.ce_count[space]) return; c.ce_count[space] = ce; c.onCongestionEvent(largest_sent, now); }
test onEcn { var c: Controller = .{}; // The application space's CE count went from zero to one. c.onEcn(2, 1, 1000, 2000); try std.testing.expectEqual(initialWindow(min_datagram_size) / 2, c.window); // Reported again in the next ACK, it is the same mark. c.onEcn(2, 1, 3000, 4000); try std.testing.expectEqual(initialWindow(min_datagram_size) / 2, c.window); }
/// §B.9: when Initial or Handshake keys are discarded, what was sent in /// that space is neither in flight nor ever going to be acknowledged. /// The window is untouched; nothing about the path was learned. pub fn onDiscarded(c: *Controller, discarded: []const recovery.Sent) void { for (discarded) |p| c.in_flight -|= p.size; }
test onDiscarded { var storage: [4]recovery.Sent = undefined; var initial: recovery.Space = undefined; initial.init(&storage); var c: Controller = .{}; const packet: recovery.Sent = .{ .number = 0, .time = 1, .ack_eliciting = true, .size = 1200 }; c.onSent(packet.size); _ = initial.onSent(packet);
// The Initial keys go: everything still outstanding there goes too. c.onDiscarded(initial.unacked()); initial.reset(); try std.testing.expectEqual(@as(usize, 0), c.in_flight); }
/// A packet this endpoint has stopped tracking because its table was /// full, which is not the same thing as a packet the network lost. Also /// a 0-RTT packet the server refused to read (§4.6.3 of RFC 9001), which /// will never be acknowledged and was not lost either. /// /// The bytes stop counting against the window, because nothing will ever /// acknowledge or declare lost a packet there is no longer a record of, /// and a connection whose `bytes_in_flight` only grows is one that stops /// sending. The window itself is untouched: §B.8's reduction is a /// response to evidence of congestion, and this is evidence of nothing /// but a bounded table. pub fn onForgotten(c: *Controller, forgotten: recovery.Sent) void { c.in_flight -|= forgotten.size; }
test onForgotten { var storage: [1]recovery.Sent = undefined; var space: recovery.Space = undefined; space.init(&storage); var c: Controller = .{}; for (0..2) |i| { const packet: recovery.Sent = .{ .number = i, .time = 1, .ack_eliciting = true, .size = 1200 }; c.onSent(packet.size); if (space.onSent(packet)) |forgotten| c.onForgotten(forgotten); } // Only the packet still on record counts against the window. try std.testing.expectEqual(@as(usize, 1200), c.in_flight); }
/// §B.5: whether a packet was sent before the current recovery period. fn inRecovery(c: *const Controller, sent_time: Instant) bool { const start = c.recovery_start orelse return false; return sent_time <= start; }
/// §B.6: enter a recovery period and halve the window, unless already in /// one. /// /// "A sender that is already in a recovery period stays in it and does not /// reenter it" — §7.3.2. Everything lost in one round trip is one piece of /// evidence about the path, not one piece per packet, and a controller /// that halved per packet would collapse to nothing on a single burst of /// loss. fn onCongestionEvent(c: *Controller, sent_time: Instant, now: Instant) void { if (c.inRecovery(sent_time)) return; c.recovery_start = now; c.ssthresh = c.window * loss_reduction_numerator / loss_reduction_denominator; c.window = @max(c.ssthresh, minimumWindow(c.max_datagram_size)); }};
/// §7.6.2: whether two ack-eliciting packets, far enough apart in time, were/// both lost with nothing acknowledged between them.////// The "nothing acknowledged between them" half is checked against/// consecutive entries of the lost set, which is where this is approximate:/// a packet acknowledged between two lost ones has already been removed from/// the tracked set by the time loss detection runs, so it leaves no trace/// here. The error is in the safe direction — persistent congestion may be/// declared when it should not be, which drops the window to two packets and/// costs throughput, rather than missed, which would leave a sender pushing/// into a path that has stopped carrying anything. §7.6.2 makes the same/// trade for its own simplification about packet number spaces.fn persistent(lost: []const recovery.Sent, first_rtt_sample: Instant, duration: Duration) bool { var previous: ?recovery.Sent = null; for (lost) |p| { // §B.8: "Only consider packets sent after getting an RTT sample." if (p.time <= first_rtt_sample) { previous = null; continue; } if (!p.ack_eliciting) { // §7.6.2: "These two packets MUST be ack-eliciting, since a // receiver is required to acknowledge only ack-eliciting packets // within its maximum acknowledgment delay." previous = null; continue; } if (previous) |earlier| { if (p.time -| earlier.time > duration) return true; } else { previous = p; } } return false;}
const testing = std.testing;
test "RFC 9002 7.2: the initial window is ten packets, capped" { // Ten times the datagram size, but never more than the larger of 14,720 // and two datagrams -- RFC 6928's ten TCP segments, adjusted for UDP's // smaller header. try testing.expectEqual(@as(usize, 12_000), initialWindow(1200)); try testing.expectEqual(@as(usize, 14_720), initialWindow(1500)); // A jumbo path hits the ceiling rather than asking for 90 KB up front -- // and the ceiling is two datagrams once those are larger than 7,360, so a // large MTU is not punished down to ten small packets' worth. try testing.expectEqual(@as(usize, 18_000), initialWindow(9000)); try testing.expectEqual(@as(usize, 20_000), initialWindow(10_000));}
test "RFC 9002 7.3.1: slow start doubles the window every round trip" { var c: Controller = .{}; const start = c.window;
// A window's worth acknowledged, in packets. var acked: usize = 0; var n: u64 = 0; while (acked < start) : (acked += 1200) { c.onAcked(.{ .number = n, .time = 1, .ack_eliciting = true, .size = 1200 }, 100); n += 1; } try testing.expectEqual(start * 2, c.window);}
test "RFC 6356 3: alpha is one for one path and one over n for n alike" { const one = Coupling.linked(&.{.{ .window = 12000, .rtt = 50 }}).?; try testing.expectApproxEqAbs(@as(f64, 1), one.alpha, 1e-9); const alike = Coupling.linked(&.{ .{ .window = 12000, .rtt = 50 }, .{ .window = 12000, .rtt = 50 }, }).?; try testing.expectApproxEqAbs(@as(f64, 0.5), alike.alpha, 1e-9); try testing.expectEqual(@as(usize, 24000), alike.total);}
test "RFC 6356 3: two coupled paths alike grow by alpha packets between them" { // Each acknowledges a window's worth. Uncoupled, each would grow by a // packet, two between them. Coupled, each acknowledgement adds // alpha*acked*MSS/cwnd_total, so a round trip adds alpha*MSS to the pair // -- half a packet, with alpha = 1/2. Set against each path halving on // loss as a single flow does, that is what leaves the pair taking no // more of a shared bottleneck than one flow would (RFC 6356 §2's "do no // harm"). var a: Controller = .{ .ssthresh = 1 }; var b: Controller = .{ .ssthresh = 1 }; const start = a.window; const k = Coupling.linked(&.{ .{ .window = a.window, .rtt = 50 }, .{ .window = b.window, .rtt = 50 }, }).?; var acked: usize = 0; var n: u64 = 0; while (acked < start) : (acked += 1200) { a.onAckedCoupled(.{ .number = n, .time = 1, .ack_eliciting = true, .size = 1200 }, 100, k); b.onAckedCoupled(.{ .number = n, .time = 1, .ack_eliciting = true, .size = 1200 }, 100, k); n += 1; } const grown = (a.window - start) + (b.window - start); try testing.expect(grown <= 600); try testing.expect(grown >= 550);}
test "RFC 6356 3: coupling never grows a path faster than it would alone" { // A short path beside a long one with a larger window: alpha is well // above one, and alpha*MSS/cwnd_total on the long path exceeds its own // MSS/cwnd_i. The min() in the increase is what holds it to one packet // per round trip -- RFC 6356 §2's first goal the other way round, that a // path never does better coupled than alone. const k = Coupling.linked(&.{ .{ .window = 12000, .rtt = 10 }, .{ .window = 48000, .rtt = 1000 }, }).?; try testing.expect(k.alpha > 4); try testing.expect(k.increase(1200, 1200) > 1200 * 1200 / 48000); var coupled: Controller = .{ .ssthresh = 1, .window = 48000 }; var alone: Controller = .{ .ssthresh = 1, .window = 48000 }; coupled.onAckedCoupled(.{ .number = 0, .time = 1, .ack_eliciting = true, .size = 1200 }, 100, k); alone.onAcked(.{ .number = 0, .time = 1, .ack_eliciting = true, .size = 1200 }, 100); try testing.expectEqual(alone.window, coupled.window);}
test "RFC 9002 7.3.3: congestion avoidance adds one packet per round trip" { var c: Controller = .{}; // Put it above the threshold, which is where slow start ends. c.ssthresh = 1; const start = c.window;
var acked: usize = 0; var n: u64 = 0; while (acked < start) : (acked += 1200) { c.onAcked(.{ .number = n, .time = 1, .ack_eliciting = true, .size = 1200 }, 100); n += 1; } // One maximum datagram larger, not twice as large. Integer division // loses a little of it, so this is the shape of the answer rather than // the exact octet. try testing.expect(c.window > start); try testing.expect(c.window <= start + 1200); try testing.expect(c.window >= start + 1100);}
test "RFC 9002 7.3.2: a loss halves the window once, not once per packet" { var c: Controller = .{}; c.onSent(6000); const start = c.window;
// Three packets from the same round trip, lost together. const lost = [_]recovery.Sent{ .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }, .{ .number = 1, .time = 1001, .ack_eliciting = true, .size = 1200 }, .{ .number = 2, .time = 1002, .ack_eliciting = true, .size = 1200 }, }; c.onLost(&lost, 100 * std.time.ns_per_ms, 2000);
try testing.expectEqual(start / 2, c.window); try testing.expectEqual(start / 2, c.ssthresh); // And the bytes are no longer in flight. try testing.expectEqual(@as(usize, 6000 - 3600), c.in_flight);
// More loss from the same period changes nothing: "A sender that is // already in a recovery period stays in it and does not reenter it." const halved = c.window; c.onLost(&.{.{ .number = 3, .time = 1003, .ack_eliciting = true, .size = 1200 }}, 100 * std.time.ns_per_ms, 2100); try testing.expectEqual(halved, c.window);
// A loss of something sent *after* the recovery period began is new // evidence, and halves it again. c.onLost(&.{.{ .number = 9, .time = 3000, .ack_eliciting = true, .size = 1200 }}, 100 * std.time.ns_per_ms, 4000); try testing.expectEqual(halved / 2, c.window);}
test "RFC 9002 7.2: the window never falls below two packets" { var c: Controller = .{}; var now: Instant = 1000; // Halve it until it cannot be halved any further. for (0..20) |_| { c.onLost(&.{.{ .number = 0, .time = now, .ack_eliciting = true, .size = 100 }}, 1, now + 1); now += 1000; } try testing.expectEqual(minimumWindow(min_datagram_size), c.window);}
test "RFC 9002 7.3.2: a packet from before the recovery period does not grow the window" { var c: Controller = .{}; c.onLost(&.{.{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }}, 1, 2000); const reduced = c.window;
// Sent at 1500, before the recovery period began at 2000: it was already // on the path when the loss was detected, so its arrival says nothing // about whether the reduced window is working. c.onAcked(.{ .number = 1, .time = 1500, .ack_eliciting = true, .size = 1200 }, 3000); try testing.expectEqual(reduced, c.window);
// Sent after, so it does: this is what ends the recovery period in // §7.3.2's state machine. c.onAcked(.{ .number = 2, .time = 2500, .ack_eliciting = true, .size = 1200 }, 3000); try testing.expect(c.window > reduced);}
test "RFC 9002 B.5: an application-limited sender does not grow its window" { // A sender with nothing to send leaves the window unused, and an unused // window is not evidence that the path would have carried it. A handshake // is almost entirely application limited, so without this the window // would balloon on the strength of four packets. var c: Controller = .{}; const start = c.window; c.app_limited = true; for (0..20) |i| { c.onAcked(.{ .number = i, .time = 1, .ack_eliciting = true, .size = 1200 }, 100); } try testing.expectEqual(start, c.window);}
test "RFC 9002 7.6: a path that stops carrying anything takes the window to the floor" { var c: Controller = .{}; c.onRttSample(500); c.onSent(12_000);
const pto = 100 * std.time.ns_per_ms; // Two ack-eliciting packets more than three probe timeouts apart, both // lost, with nothing acknowledged between: §7.6.2's definition. const lost = [_]recovery.Sent{ .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }, .{ .number = 1, .time = 1000 + 4 * pto, .ack_eliciting = true, .size = 1200 }, }; c.onLost(&lost, pto, 1000 + 5 * pto);
try testing.expectEqual(minimumWindow(min_datagram_size), c.window);}
test "RFC 9002 7.6.2: persistent congestion needs an RTT sample first" { // "Before the first RTT sample, a sender arms its PTO timer based on the // initial RTT, which could be substantially larger than the actual RTT. // Requiring a prior RTT sample prevents a sender from establishing // persistent congestion with potentially too few probes." var c: Controller = .{}; const pto = 100 * std.time.ns_per_ms; const lost = [_]recovery.Sent{ .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }, .{ .number = 1, .time = 1000 + 4 * pto, .ack_eliciting = true, .size = 1200 }, };
// No sample: halved, not floored. c.onLost(&lost, pto, 1000 + 5 * pto); try testing.expectEqual(initialWindow(min_datagram_size) / 2, c.window); try testing.expect(c.window > minimumWindow(min_datagram_size));
// And a sample taken after those packets were sent does not count them // either, for the same reason. var later: Controller = .{}; later.onRttSample(1000 + 5 * pto); later.onLost(&lost, pto, 1000 + 6 * pto); try testing.expect(later.window > minimumWindow(min_datagram_size));}
test "RFC 9002 7.6.2: two losses close together are not persistent congestion" { var c: Controller = .{}; c.onRttSample(500); const pto = 100 * std.time.ns_per_ms; const lost = [_]recovery.Sent{ .{ .number = 0, .time = 1000, .ack_eliciting = true, .size = 1200 }, .{ .number = 1, .time = 1000 + pto, .ack_eliciting = true, .size = 1200 }, }; c.onLost(&lost, pto, 2000); // One congestion event, so halved -- but the path answered recently // enough that there is still a window worth defending. try testing.expectEqual(initialWindow(min_datagram_size) / 2, c.window);}
test "RFC 9002 7.1: the peer's CE counter rising is a congestion event" { var c: Controller = .{}; const start = c.window;
c.onEcn(2, 3, 1000, 2000); try testing.expectEqual(start / 2, c.window);
// The same count reported again is the same event, not a new one. const halved = c.window; c.onEcn(2, 3, 3000, 4000); try testing.expectEqual(halved, c.window);
// A rise, on a packet sent after the recovery period, is new evidence. c.onEcn(2, 4, 3000, 4000); try testing.expectEqual(halved / 2, c.window);}
test "RFC 9002 7: what may be sent is the window less what is in the air" { var c: Controller = .{}; try testing.expectEqual(initialWindow(min_datagram_size), c.available());
c.onSent(1200); try testing.expectEqual(initialWindow(min_datagram_size) - 1200, c.available());
// A probe sent on a PTO expiry may exceed the window -- §7.5 requires it, // since a probe the window forbade would leave a stalled sender with no // way to discover that it had stalled. The excess is still counted. c.onSent(initialWindow(min_datagram_size)); try testing.expectEqual(@as(usize, 0), c.available());}
test "a packet the sender forgot leaves flight with it" { // The failure this prevents is a silent, permanent stall, and it needs no // help from the network. `recovery.Space` remembers `max_tracked` // unacknowledged packets and drops the oldest to make room; §B.2's // `bytes_in_flight` is only ever decremented by walking that table. So a // dropped entry used to take its bytes out of the table and leave them in // the count, where nothing could ever remove them -- and once enough had // accumulated, `available()` was zero for the rest of the connection and // the sender simply stopped, with the controller believing the path was // full. // // It is reachable by going faster, which is the worst possible trigger: a // flow control window of sixty-four kilobytes puts about sixty-four // packets in the air at once, and this table holds sixty-four. var c: Controller = .{}; var storage: [recovery.max_tracked]recovery.Sent = undefined; var s: recovery.Space = .{ .sent = &storage };
var number: u64 = 0; while (number < recovery.max_tracked * 4) : (number += 1) { const packet: recovery.Sent = .{ .number = number, .time = 1, .ack_eliciting = true, .size = 1200, }; c.onSent(packet.size); if (s.onSent(packet)) |forgotten| c.onForgotten(forgotten); }
// Everything the sender still remembers is in flight, and nothing else // is. Without the report the count would be four times the truth and // three quarters of it unreachable. try testing.expectEqual(recovery.max_tracked * 1200, c.in_flight); try testing.expectEqual(@as(usize, recovery.max_tracked), s.inFlight());
// And the window is untouched: a table that overflowed is evidence about // this endpoint's bookkeeping, not about the path. try testing.expectEqual(initialWindow(min_datagram_size), c.window);}
test "RFC 9002 B.9: discarded keys take their packets out of flight" { // A packet sent in a space whose keys are gone will never be // acknowledged, so leaving it counted would shrink the usable window for // the rest of the connection. var c: Controller = .{}; c.onSent(2400); c.onDiscarded(&.{ .{ .number = 0, .time = 1, .ack_eliciting = true, .size = 1200 }, .{ .number = 1, .time = 2, .ack_eliciting = true, .size = 1200 }, }); try testing.expectEqual(@as(usize, 0), c.in_flight);}