Skip to main content

moq_mux/
rate.rs

1//! Shared rate control for media senders.
2//!
3//! [`Control`] turns each grant from a [`bandwidth::Consumer`] into the target
4//! rate a sender should produce, so audio, video, and transcode back off the
5//! same way. [`Grant`] drives it from a live grant. A rendition encoded beside
6//! lower ones of the same source sets [`Policy::lower`], and stops once its grant
7//! can no longer fund it, so the lower renditions keep their share.
8
9use std::{
10	pin::Pin,
11	task::{Poll, ready},
12	time::Duration,
13};
14
15use kio::clock::Instant;
16
17use moq_net::bandwidth;
18
19/// Ignore moves smaller than 1/`HYSTERESIS` (5%) of the current target, so a
20/// jittering estimate doesn't reconfigure the sender on every 100ms sample.
21const HYSTERESIS: u64 = 20;
22
23/// How long the target takes to climb by its own size: 25% of the current target per
24/// second (~3s from the floor back to a 2x higher rate).
25///
26/// Drops ignore this and apply at once. Overshooting a closing uplink stalls media,
27/// while undershooting an opening one costs a few seconds of lower quality,
28/// so the response is deliberately asymmetric.
29const RAMP: Duration = Duration::from_secs(4);
30
31/// The soonest a failed change is retried: the time the ramp takes to clear the
32/// hysteresis band, so a sender that keeps failing is asked at most this often.
33pub const RETRY: Duration = Duration::from_millis(RAMP.as_millis() as u64 / HYSTERESIS);
34
35/// How a bandwidth estimate maps onto the bitrate a sender should produce at.
36///
37/// Build one with [`Policy::new`]. The behaviour is tuned for a live contribution
38/// sender on a cellular uplink: give back bandwidth immediately when the pipe closes,
39/// take it back slowly when it opens, and don't twitch at every jitter in the estimate.
40/// The deadband and ramp that implement that are deliberately not knobs; they are
41/// properties of how congestion control behaves, not of any one sender.
42///
43/// The estimate handed in is expected to be this sender's alone. Splitting one
44/// connection's estimate among the senders sharing it is
45/// [`bandwidth::Allocator`]'s job, one layer down,
46/// so nothing here holds a fraction back for anyone else.
47///
48/// `#[non_exhaustive]`: construct via [`Policy::new`] and set fields, so new
49/// knobs stay additive.
50#[derive(Clone, Debug, PartialEq, Eq)]
51#[non_exhaustive]
52pub struct Policy {
53	/// Upper bound, normally the bitrate the caller asked for. The estimate can only
54	/// ever take the target *down* from here: an optimistic estimate is not a reason
55	/// to send more than was configured.
56	pub max: bandwidth::Rate,
57
58	/// Lower bound. Below some rate the media isn't worth sending, so the target
59	/// holds here and the transport's priority queue sheds the excess instead.
60	/// Defaults to a tenth of `max`.
61	pub min: bandwidth::Rate,
62
63	/// The next lower rendition's [`max`](Self::max), when this one is encoded beside
64	/// lower renditions of the same source.
65	///
66	/// A grant below the band boundary `(max + 2 * lower) / 3` disables this rendition,
67	/// since the lower one then serves viewers better than a starved copy of this one.
68	/// It resumes at the boundary once the grant clears it by the same 5% hysteresis
69	/// every move needs. It only disables while a session probes for it (see
70	/// [`Control::set_probed`]), since nothing else could raise the estimate to resume it.
71	///
72	/// `None`, the default, for the lowest or only rendition, which never disables. A
73	/// `lower` at or above `max` leaves no band, so it never disables either.
74	pub lower: Option<bandwidth::Rate>,
75}
76
77impl Policy {
78	/// A policy targeting at most `max`, with a floor a tenth of it.
79	pub fn new(max: bandwidth::Rate) -> Self {
80		Self {
81			max,
82			// A tenth of the ceiling: low enough to ride out a bad uplink, high
83			// enough that what we do send is still worth decoding.
84			min: bandwidth::Rate::from_bps(max.as_bps() / 10),
85			lower: None,
86		}
87	}
88
89	/// The band boundary [`lower`](Self::lower) sets, below which this rendition
90	/// disables, or `None` when it never does.
91	fn boundary(&self) -> Option<bandwidth::Rate> {
92		let lower = self.lower.filter(|lower| *lower < self.max)?;
93		let boundary = (u128::from(self.max.as_bps()) + 2 * u128::from(lower.as_bps())) / 3;
94		// Below `max`, which fits a `u64`.
95		Some(bandwidth::Rate::from_bps(boundary as u64))
96	}
97}
98
99/// What a sender should be doing, per its [`Control`].
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum Target {
102	/// Encode at this rate, and advertise the rendition as enabled.
103	Enabled(bandwidth::Rate),
104	/// Stop encoding, and advertise the rendition as disabled. Only a [`Policy`] with a
105	/// [`lower`](Policy::lower) rendition ever asks for this.
106	Disabled,
107}
108
109/// Maps bandwidth estimates onto a target bitrate, per a [`Policy`].
110///
111/// Feed it every estimate from a
112/// [`bandwidth::Consumer`]; it returns a new
113/// target only when one is worth applying, so a caller can hand the result
114/// straight to a sender without rate-limiting it further:
115///
116/// ```
117/// # use moq_mux::rate::{Control, Policy, Target};
118/// # use moq_net::bandwidth;
119/// # use kio::clock::Instant;
120/// let mut control = Control::new(Policy::new(bandwidth::Rate::from_mbps(4)));
121/// // A 2 Mbps estimate takes the 4 Mbps target down to what the link will carry.
122/// assert_eq!(
123///     control.update(Some(bandwidth::Rate::from_mbps(2)), kio::clock::now()),
124///     Some(Target::Enabled(bandwidth::Rate::from_mbps(2)))
125/// );
126///
127/// // A 5 Mbps rendition above a 2.5 Mbps one disables below 3.33 Mbps, once a
128/// // session probes for it.
129/// let mut policy = Policy::new(bandwidth::Rate::from_mbps(5));
130/// policy.lower = Some(bandwidth::Rate::from_kbps(2_500));
131/// let mut control = Control::new(policy);
132/// control.set_probed(true);
133/// assert_eq!(
134///     control.update(Some(bandwidth::Rate::from_mbps(3)), kio::clock::now()),
135///     Some(Target::Disabled)
136/// );
137/// ```
138///
139/// A raise climbs over several updates, and a grant that has settled sends no
140/// further estimate to climb on, so a sender following a live grant uses
141/// [`Grant`], which also wakes when the ramp allows the next step.
142///
143/// The time source is a parameter rather than an [`Instant::now`] call so the
144/// policy stays pure and testable. Pass the time the estimate was observed.
145#[derive(Clone, Debug)]
146pub struct Control {
147	policy: Policy,
148	target: bandwidth::Rate,
149	/// Whether the sender should encode at all; see [`Policy::lower`].
150	enabled: bool,
151	/// Whether a session probes for this sender, which disabling needs.
152	probed: bool,
153	/// When the target last moved, anchoring the [`RAMP`] limit. `None`
154	/// until the first change, when there's nothing to ramp from.
155	applied: Option<Instant>,
156	/// When an update with the same estimate will move the target. `None` when
157	/// only a new estimate can.
158	deadline: Option<Instant>,
159	/// What the change [`update`](Self::update) last returned replaced, so
160	/// [`failed`](Self::failed) can take it back.
161	last: Option<Change>,
162}
163
164/// The state a returned change replaced, and the clamped estimate that asked for it.
165#[derive(Clone, Copy, Debug)]
166struct Change {
167	target: bandwidth::Rate,
168	enabled: bool,
169	applied: Option<Instant>,
170	desired: bandwidth::Rate,
171}
172
173impl Control {
174	/// Start at [`Policy::max`], the optimistic case: until an estimate says
175	/// otherwise, send what the caller configured.
176	pub fn new(policy: Policy) -> Self {
177		Self {
178			target: policy.max,
179			policy,
180			enabled: true,
181			probed: false,
182			applied: None,
183			deadline: None,
184			last: None,
185		}
186	}
187
188	/// What the sender should currently be doing.
189	pub fn target(&self) -> Target {
190		match self.enabled {
191			true => Target::Enabled(self.target),
192			false => Target::Disabled,
193		}
194	}
195
196	/// Whether a session probes the connection for this sender, as
197	/// [`Consumer::probed`](bandwidth::Consumer::probed) reports it, from the next
198	/// [`update`](Self::update) on.
199	///
200	/// A rendition only disables while one does: without a sender probing for it,
201	/// the estimate stops rising once the connection is app-limited, so a stopped
202	/// rendition could never resume. One disabled when probing stops resumes at the
203	/// next estimate instead, following the grant down like any sender. `false`
204	/// until set.
205	pub fn set_probed(&mut self, probed: bool) {
206		self.probed = probed;
207	}
208
209	/// Follow `policy` from the next [`update`](Self::update), returning whether it changed;
210	/// see [`Grant::set_policy`].
211	fn set_policy(&mut self, policy: Policy) -> bool {
212		if policy == self.policy {
213			return false;
214		}
215		if policy.max == self.policy.max && policy.min == self.policy.min {
216			self.policy = policy;
217		} else {
218			let (enabled, probed) = (self.enabled, self.probed);
219			*self = Control::new(policy);
220			self.enabled = enabled;
221			self.probed = probed;
222		}
223		true
224	}
225
226	/// When to [`update`](Self::update) again with the latest estimate, changed or
227	/// not, to continue a raise or retry a failed change; `None` once the target has
228	/// settled.
229	///
230	/// An update at this instant with an unchanged estimate always returns a change.
231	fn deadline(&self) -> Option<Instant> {
232		self.deadline
233	}
234
235	/// Feed a new estimate, returning the new target when it moved enough to be
236	/// worth applying and `None` when it didn't.
237	///
238	/// A `None` estimate (no congestion controller, or disconnected) holds the
239	/// current target rather than resetting to [`Policy::max`]: losing the
240	/// estimate is not evidence the uplink got better.
241	pub fn update(&mut self, estimate: Option<bandwidth::Rate>, now: Instant) -> Option<Target> {
242		self.last = None;
243		let Some(estimate) = estimate else {
244			self.deadline = None;
245			return None;
246		};
247
248		// Normalize rather than trusting the fields: `min > max` would make the
249		// clamp below panic.
250		let min = self.policy.min.min(self.policy.max);
251		let desired = estimate.clamp(min, self.policy.max);
252		let boundary = self.policy.boundary().filter(|_| self.probed);
253
254		if !self.enabled {
255			let resume = match boundary {
256				Some(boundary) => {
257					// Capped at the ceiling, or a boundary within the deadband of it could
258					// never be cleared by an estimate clamped to that ceiling.
259					let clear = boundary
260						.as_bps()
261						.saturating_add(band(boundary).as_bps())
262						.min(self.policy.max.as_bps());
263					if desired.as_bps() < clear {
264						// A retry of a failed resume is no longer due either.
265						self.deadline = None;
266						return None;
267					}
268					// Restart at the boundary and ramp: the estimate was measured while
269					// this rendition sent nothing, so its whole share is the least
270					// trustworthy number here.
271					boundary.clamp(min, self.policy.max)
272				}
273				// Nothing probes for it any more, so it can't wait for the estimate to
274				// rise: follow the grant like any sender instead.
275				None => desired,
276			};
277			self.last = Some(Change {
278				target: self.target,
279				enabled: false,
280				applied: self.applied,
281				desired,
282			});
283			self.enabled = true;
284			self.target = resume;
285			self.applied = Some(now);
286			self.deadline = self.raise(desired);
287			return Some(Target::Enabled(resume));
288		}
289
290		let next = if desired <= self.target {
291			// Attack: the pipe is closing, give the bandwidth back now.
292			desired
293		} else {
294			// Decay: climb back at no more than `RAMP` allows since the last
295			// change. Before the first change there's nothing to ramp from.
296			match self.applied {
297				Some(applied) => grown(self.target, now.saturating_duration_since(applied))
298					.min(desired)
299					.clamp(min, self.policy.max),
300				None => desired,
301			}
302		};
303
304		// Hysteresis is checked against the *applied* target and deliberately
305		// does not touch `applied` when it suppresses a move. The ramp allowance
306		// therefore keeps growing while small raises are suppressed, so a raise
307		// lands once it clears the threshold instead of being starved forever by
308		// a per-tick allowance smaller than the threshold.
309		//
310		// A raise landing exactly on [`Policy::max`] is exempt: that's the last step
311		// of a recovery, not a twitch. `next` stops growing once it reaches the
312		// ceiling, so a target arriving within `hysteresis` of it has no move left
313		// that could ever clear the threshold, and the sender would sit a few
314		// percent under its configured rate for good after one congestion event.
315		//
316		// Scoped to the *configured* ceiling, not to any `desired`. Every raise
317		// eventually lands on `desired`, so exempting all of them would let a
318		// slowly-rising estimate reconfigure the sender on every tick, which is
319		// precisely what the deadband exists to prevent. Stalling a few percent
320		// below a merely estimate-limited ceiling is the deadband working; stalling
321		// below the rate the caller asked for is not.
322		//
323		// Drops keep the deadband either way: sitting a little above a falling
324		// estimate is what it's for. That is also what keeps a grant jittering
325		// around the band boundary from flapping the rendition off and on.
326		//
327		// The deadband only holds a rung on above a boundary that was already holding
328		// it. One whose applied target is under the boundary, because probing just
329		// started or the lower rendition rose, disables at once on a grant below it.
330		let disable = boundary.is_some_and(|boundary| desired < boundary);
331		let under = boundary.is_some_and(|boundary| self.target < boundary);
332		let settling = next > self.target && next == self.policy.max;
333		// A sender above the ceiling, such as an assumed one, always comes down to it.
334		let over = self.target > self.policy.max;
335		let suppressed = next == self.target || (!settling && !over && next.abs_diff(self.target) < band(self.target));
336		if suppressed && !(disable && under) {
337			self.deadline = self.raise(desired);
338			return None;
339		}
340
341		self.last = Some(Change {
342			target: self.target,
343			enabled: true,
344			applied: self.applied,
345			desired,
346		});
347		// On `desired` rather than `next`: a ramp still climbing from under the boundary
348		// toward a grant above it is funded, so it stays on.
349		if disable {
350			// Only a new estimate clearing the boundary resumes it, so nothing is due.
351			self.enabled = false;
352			self.deadline = None;
353			return Some(Target::Disabled);
354		}
355		self.target = next;
356		self.applied = Some(now);
357		self.deadline = self.raise(desired);
358		Some(Target::Enabled(next))
359	}
360
361	/// Take back the target the last [`update`](Self::update) returned, because the
362	/// sender failed to apply it at `now`.
363	///
364	/// The previous target is restored, and [`deadline`](Self::deadline) asks for the
365	/// change again no sooner than one ramp step after `now`, so a quiet grant still
366	/// retries and a sender that keeps failing is not hammered. Does nothing when the
367	/// last update returned no change.
368	fn failed(&mut self, now: Instant) {
369		let Some(change) = self.last.take() else { return };
370		// The old anchor too, so the retry keeps the ramp allowance it had earned,
371		// the same as a raise suppressed by the deadband.
372		let toggled = self.enabled != change.enabled;
373		self.target = change.target;
374		self.enabled = change.enabled;
375		self.applied = change.applied;
376		let retry = now.checked_add(RETRY);
377		self.deadline = if toggled || change.desired < self.target {
378			// A returned drop already cleared the deadband, and drops don't ramp. A
379			// returned disable or resume already cleared its boundary.
380			retry
381		} else {
382			self.raise(change.desired).zip(retry).map(|(at, retry)| at.max(retry))
383		};
384	}
385
386	/// The earliest instant the ramp lets the target climb toward `desired` by enough
387	/// to apply, or `None` when it never will without a new estimate.
388	///
389	/// Exact, in the same integer math as [`grown`]: an update at this instant applies
390	/// the raise, so a caller sleeping until then never wakes for nothing and spins.
391	fn raise(&self, desired: bandwidth::Rate) -> Option<Instant> {
392		if desired <= self.target {
393			return None;
394		}
395
396		// The smallest raise that clears the deadband, or the configured ceiling,
397		// which is exempt from it.
398		let target = self.target.as_bps();
399		let goal = target.saturating_add(band(self.target).as_bps().max(1));
400		let goal = if desired == self.policy.max {
401			goal.min(desired.as_bps())
402		} else if goal <= desired.as_bps() {
403			goal
404		} else {
405			// The raise is capped at `desired`, inside the deadband: only a new
406			// estimate can move it.
407			return None;
408		};
409
410		// A zero target has nothing to grow from.
411		if target == 0 {
412			return None;
413		}
414		let nanos = (u128::from(goal - target) * RAMP.as_nanos()).div_ceil(u128::from(target));
415		self.applied?
416			.checked_add(Duration::from_nanos(u64::try_from(nanos).ok()?))
417	}
418}
419
420/// Follows a bandwidth grant through a [`Control`] on the ambient clock.
421///
422/// Wakes on every change to the grant and whenever the ramp allows the next step of
423/// a raise or the retry of a refused change, so a sender climbs back to its ceiling
424/// even after the grant goes quiet.
425///
426/// Follow a [`Reservation`](bandwidth::Reservation)'s consumer: it reports whether a
427/// session probes for it, which a rendition needs before it disables, and the slice it
428/// would get back while unwatched, which it needs to resume after its viewers left.
429pub struct Grant {
430	grant: bandwidth::Consumer,
431	control: Control,
432	/// Armed at the control's deadline, created on first use.
433	timer: Option<kio::clock::Sleep>,
434	/// Feed the current grant on the next poll, after [`set_policy`](Self::set_policy)
435	/// changed it.
436	refeed: bool,
437}
438
439impl Grant {
440	/// Follow `grant` under `policy`, starting at [`Policy::max`].
441	pub fn new(grant: bandwidth::Consumer, policy: Policy) -> Self {
442		Self {
443			grant,
444			control: Control::new(policy),
445			timer: None,
446			refeed: false,
447		}
448	}
449
450	/// Follow on from a sender already producing at `target`, such as one moving to a new
451	/// grant, rather than at [`Policy::max`]. The current grant is fed on the next poll, so a
452	/// sender below a grant that has room climbs back without waiting for the grant to change,
453	/// and one above [`Policy::max`] is lowered to it.
454	pub fn assume(&mut self, target: Target) {
455		match target {
456			Target::Enabled(rate) => {
457				self.control.target = rate;
458				self.control.enabled = true;
459				// The sender is at this rate now, so a raise ramps from here.
460				self.control.applied = Some(kio::clock::now());
461			}
462			Target::Disabled => {
463				self.control.enabled = false;
464				self.control.applied = None;
465			}
466		}
467		self.control.deadline = None;
468		self.control.last = None;
469		self.refeed = true;
470	}
471
472	/// The policy the target follows.
473	pub fn policy(&self) -> &Policy {
474		&self.control.policy
475	}
476
477	/// Follow under `policy` from now on, feeding it the current grant on the next poll.
478	///
479	/// A new ceiling or floor starts over at its [`Policy::max`], as a fresh [`Grant`]
480	/// would, since the sender applied that ceiling itself. A new
481	/// [`lower`](Policy::lower) alone keeps the target and ramp, since nothing retuned
482	/// the sender. Either way a disabled sender stays disabled until that grant resumes
483	/// it under the new policy, since nothing told it to start.
484	pub fn set_policy(&mut self, policy: Policy) {
485		if self.control.set_policy(policy) {
486			self.refeed = true;
487		}
488	}
489
490	/// The next target the sender should produce at, or the error that closed the grant.
491	#[cfg_attr(feature = "async", kio::wrapper)]
492	pub fn poll_next(&mut self, waiter: &kio::Waiter) -> Poll<Result<Target, moq_net::Error>> {
493		loop {
494			let estimate = if std::mem::take(&mut self.refeed) {
495				self.grant.peek()
496			} else if let Poll::Ready(estimate) = self.grant.poll_changed(waiter) {
497				estimate?
498			} else {
499				// Due only when an update with the unchanged grant moves the target, so
500				// this never spins.
501				ready!(self.poll_deadline(waiter));
502				self.grant.peek()
503			};
504			self.control.set_probed(self.grant.probed());
505			if let Some(target) = self.control.update(estimate, kio::clock::now()) {
506				return Poll::Ready(Ok(target));
507			}
508		}
509	}
510
511	/// Take back the target [`poll_next`](Self::poll_next) last returned, because the sender
512	/// failed to apply it.
513	///
514	/// The previous target is restored and asked for again no sooner than one ramp
515	/// step from now, so a quiet grant still retries and a sender that keeps failing
516	/// is not hammered. Does nothing once another poll has fed the grant.
517	pub fn failed(&mut self) {
518		self.control.failed(kio::clock::now());
519	}
520
521	fn poll_deadline(&mut self, waiter: &kio::Waiter) -> Poll<()> {
522		let Some(at) = self.control.deadline() else {
523			self.timer = None;
524			return Poll::Pending;
525		};
526		let timer = self.timer.get_or_insert_with(|| kio::clock::sleep_until(at));
527		if timer.deadline() != at {
528			timer.reset(at);
529		}
530		waiter.poll_future(Pin::new(timer))
531	}
532}
533
534/// The hysteresis band around `target`: moves smaller than this are suppressed.
535fn band(target: bandwidth::Rate) -> bandwidth::Rate {
536	bandwidth::Rate::from_bps(target.as_bps() / HYSTERESIS)
537}
538
539/// `target` plus the [`RAMP`] allowance for `elapsed`, saturating.
540fn grown(target: bandwidth::Rate, elapsed: Duration) -> bandwidth::Rate {
541	let target = target.as_bps();
542	let allowance = u128::from(target) * elapsed.as_nanos() / RAMP.as_nanos();
543	bandwidth::Rate::from_bps(target.saturating_add(u64::try_from(allowance).unwrap_or(u64::MAX)))
544}
545
546#[cfg(test)]
547mod tests {
548	use std::time::Duration;
549
550	use super::*;
551
552	/// Bits per second, so the tables below stay readable.
553	fn bps(bps: u64) -> bandwidth::Rate {
554		bandwidth::Rate::from_bps(bps)
555	}
556
557	/// An enabled target at `rate`.
558	fn on(rate: bandwidth::Rate) -> Target {
559		Target::Enabled(rate)
560	}
561
562	/// 4 Mbps ceiling, so the max/10 floor lands on a round 400 kbps.
563	fn control() -> Control {
564		Control::new(Policy::new(bps(4_000_000)))
565	}
566
567	#[test]
568	fn drop_applies_immediately() {
569		let mut control = control();
570		// A 2 Mbps pipe: take the target down to it at once, no ramp, no waiting.
571		assert_eq!(
572			control.update(Some(bps(2_000_000)), kio::clock::now()),
573			Some(on(bps(2_000_000)))
574		);
575		assert_eq!(control.target(), on(bps(2_000_000)));
576	}
577
578	#[test]
579	fn missing_estimate_holds_the_target() {
580		let mut control = control();
581		let now = kio::clock::now();
582		control.update(Some(bps(2_000_000)), now).unwrap();
583
584		// Losing the estimate (disconnected) is not evidence the uplink is
585		// healthy again, so the target must not jump back to max.
586		assert_eq!(control.update(None, now.saturating_add(Duration::from_secs(10))), None);
587		assert_eq!(control.target(), on(bps(2_000_000)));
588	}
589
590	#[test]
591	fn estimate_never_raises_above_max() {
592		let mut control = control();
593		// A wildly optimistic estimate is not licence to exceed what was configured.
594		assert_eq!(control.update(Some(bps(100_000_000)), kio::clock::now()), None);
595		assert_eq!(control.target(), on(bps(4_000_000)));
596	}
597
598	#[test]
599	fn target_never_falls_below_min() {
600		let mut control = control();
601		// A near-dead uplink floors at min (max/10) rather than chasing to zero.
602		assert_eq!(control.update(Some(bps(1)), kio::clock::now()), Some(on(bps(400_000))));
603		assert_eq!(control.target(), on(bps(400_000)));
604	}
605
606	#[test]
607	fn raise_is_ramp_limited() {
608		let mut control = control();
609		let start = kio::clock::now();
610		control.update(Some(bps(1_000_000)), start).unwrap(); // target 1M
611
612		// The pipe reopens to 4 Mbps. One second later the default 25%/s ramp
613		// allows only 1M -> 1.25M, not the full 4 Mbps the estimate wants.
614		let raised = control
615			.update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1)))
616			.unwrap();
617		assert_eq!(raised, on(bps(1_250_000)));
618	}
619
620	/// Regression: the ramp allowance per tick (25%/s * 100ms = 2.5%) is smaller
621	/// than the hysteresis threshold (5%), so a raise is suppressed on any single
622	/// tick. Suppression must not reset the ramp anchor, or the allowance would be
623	/// recomputed from `now` every tick, never clear the threshold, and the target
624	/// would be starved at the floor forever while the uplink sat idle.
625	#[test]
626	fn suppressed_raises_do_not_starve_the_ramp() {
627		let mut control = control();
628		let start = kio::clock::now();
629		control.update(Some(bps(1_000_000)), start).unwrap(); // target 1M
630
631		// Tick at 100ms: each tick alone is under the 5% threshold.
632		let mut raised = None;
633		for tick in 1..=10 {
634			if let Some(next) = control.update(
635				Some(bps(4_000_000)),
636				start.saturating_add(Duration::from_millis(100 * tick)),
637			) {
638				raised = Some((tick, next));
639				break;
640			}
641		}
642
643		let (tick, next) = raised.expect("a raise must eventually clear hysteresis");
644		// 5% of 1M needs 0.05/0.25 = 0.2s of ramp, i.e. the tick at 200ms.
645		assert_eq!(tick, 2);
646		assert_eq!(next, on(bps(1_050_000)));
647	}
648
649	/// Regression: the ramp stops growing `next` once it reaches the ceiling, so a
650	/// target that lands within the 5% deadband of it has no move left that can
651	/// clear hysteresis. Without the exemption for a raise that reaches `desired`,
652	/// the walk below stalls at 3_866_256 and the sender never returns to the
653	/// bitrate it was configured with.
654	#[test]
655	fn a_raise_reaching_the_ceiling_beats_hysteresis() {
656		let mut control = control();
657		let start = kio::clock::now();
658		control.update(Some(bps(1_000_000)), start).unwrap();
659
660		// Walk up until it settles, then confirm where it settled.
661		let mut last = None;
662		for tick in 1..=200 {
663			if let Some(next) = control.update(
664				Some(bps(4_000_000)),
665				start.saturating_add(Duration::from_millis(100 * tick)),
666			) {
667				last = Some(next);
668			}
669		}
670
671		assert_eq!(last, Some(on(bps(4_000_000))));
672		// And it stops there rather than reapplying the same value forever.
673		assert_eq!(
674			control.update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(60))),
675			None
676		);
677	}
678
679	/// Regression: the ceiling exemption above must not swallow the deadband. Every
680	/// raise eventually lands on `desired`, so keying it on that rather than on the
681	/// configured ceiling let a slowly-rising estimate retune the sender on every
682	/// single tick, which is the exact behavior `hysteresis` exists to prevent.
683	#[test]
684	fn upward_jitter_stays_inside_the_deadband() {
685		let mut control = control();
686		let start = kio::clock::now();
687		control.update(Some(bps(2_000_000)), start).unwrap(); // target 2M, well under the 4M ceiling
688
689		// A 0.5% rise: inside the 5% deadband, and nowhere near the ceiling.
690		assert_eq!(
691			control.update(Some(bps(2_010_000)), start.saturating_add(Duration::from_millis(100))),
692			None
693		);
694
695		// A whole walk of them still doesn't, rather than one reconfigure per tick.
696		// Stops short of 2.1M, which is exactly 5% up and so clears the threshold.
697		for tick in 2..=9 {
698			let estimate = 2_000_000 + tick * 10_000;
699			assert_eq!(
700				control.update(
701					Some(bps(estimate)),
702					start.saturating_add(Duration::from_millis(100 * tick))
703				),
704				None,
705				"estimate {estimate} is inside the deadband"
706			);
707		}
708		assert_eq!(control.target(), on(bps(2_000_000)));
709
710		// And the deadband is still only a deadband: once the estimate does clear it,
711		// the raise lands normally, without needing the ceiling exemption.
712		assert_eq!(
713			control.update(Some(bps(2_200_000)), start.saturating_add(Duration::from_secs(2))),
714			Some(on(bps(2_200_000)))
715		);
716	}
717
718	#[test]
719	fn small_moves_are_suppressed() {
720		let mut control = control();
721		let now = kio::clock::now();
722		control.update(Some(bps(2_000_000)), now).unwrap(); // target 2M
723
724		// 2% under the current target: inside the 5% deadband, so no reconfigure.
725		assert_eq!(
726			control.update(Some(bps(1_960_000)), now.saturating_add(Duration::from_secs(1))),
727			None
728		);
729		assert_eq!(control.target(), on(bps(2_000_000)));
730
731		// 20% under: outside the deadband, so it applies.
732		assert_eq!(
733			control.update(Some(bps(1_600_000)), now.saturating_add(Duration::from_secs(2))),
734			Some(on(bps(1_600_000)))
735		);
736	}
737
738	/// `min > max` is normalized to the ceiling at construction and update.
739	#[test]
740	fn inverted_bounds_use_the_ceiling() {
741		let mut policy = Policy::new(bps(1_000_000));
742		policy.min = bps(5_000_000);
743		let mut control = Control::new(policy);
744
745		assert_eq!(control.target(), on(bps(1_000_000)));
746		assert_eq!(control.update(Some(bps(2_000_000)), kio::clock::now()), None);
747		assert_eq!(control.target(), on(bps(1_000_000)));
748	}
749
750	/// Feed `estimate` at every deadline until the target settles, asserting each one
751	/// applies a change. Returns the targets applied and when the last one landed.
752	fn follow(control: &mut Control, estimate: bandwidth::Rate) -> (Vec<bandwidth::Rate>, Option<Instant>) {
753		let mut applied = Vec::new();
754		let mut last = None;
755		while let Some(at) = control.deadline() {
756			assert!(applied.len() < 1_000, "the deadline never settled: {applied:?}");
757			let next = control.update(Some(estimate), at);
758			let next = next.unwrap_or_else(|| panic!("a deadline at {at:?} applied nothing after {applied:?}"));
759			let Target::Enabled(next) = next else {
760				panic!("a deadline at {at:?} disabled the sender after {applied:?}")
761			};
762			applied.push(next);
763			last = Some(at);
764		}
765		(applied, last)
766	}
767
768	/// After an attack, the target climbs back to the ceiling on deadlines alone: the
769	/// grant restored a second later never changes again.
770	#[test]
771	fn a_quiet_grant_recovers_on_deadlines() {
772		let mut control = control();
773		let start = kio::clock::now();
774		control.update(Some(bps(1_000_000)), start).unwrap();
775		assert_eq!(control.deadline(), None, "a drop lands at once");
776
777		let recovered = start.saturating_add(Duration::from_secs(1));
778		assert_eq!(
779			control.update(Some(bps(4_000_000)), recovered),
780			Some(on(bps(1_250_000)))
781		);
782		let (applied, last) = follow(&mut control, bps(4_000_000));
783
784		assert_eq!(applied.last(), Some(&bps(4_000_000)));
785		assert!(applied.windows(2).all(|pair| pair[0] < pair[1]), "{applied:?}");
786		// 1.25M to 4M at 25%/s compounding with each 5% step is about 4.7s.
787		let took = last.unwrap().duration_since(recovered);
788		assert!(
789			took > Duration::from_secs(4) && took < Duration::from_secs(6),
790			"{took:?}"
791		);
792	}
793
794	/// The deadline holds for awkward rates too, where integer rounding or a zero-width
795	/// band could leave a deadline that applies nothing and spins its caller.
796	#[test]
797	fn every_deadline_applies_a_change() {
798		let start = kio::clock::now();
799		for max in [15, 20, 21, 999, 1_000_003, 4_000_000, 1 << 50] {
800			for floor in [1, max / 10, max / 3, max - max / 25] {
801				let mut control = Control::new(Policy::new(bps(max)));
802				control.update(Some(bps(floor)), start);
803				let at = start.saturating_add(Duration::from_millis(7));
804				control.update(Some(bps(max)), at);
805				let (applied, _) = follow(&mut control, bps(max));
806				assert_eq!(control.target(), on(bps(max)), "{max} from {floor}: {applied:?}");
807			}
808		}
809	}
810
811	/// A raise that reaches the estimate stops asking.
812	#[test]
813	fn reaching_the_estimate_clears_the_deadline() {
814		let mut control = control();
815		let start = kio::clock::now();
816		control.update(Some(bps(1_000_000)), start).unwrap();
817		assert_eq!(
818			control.update(Some(bps(1_100_000)), start.saturating_add(Duration::from_secs(1))),
819			Some(on(bps(1_100_000)))
820		);
821		assert_eq!(control.deadline(), None);
822	}
823
824	/// A climb toward an estimate below the ceiling settles within the deadband of it,
825	/// which only a new estimate can clear, and stops asking there.
826	#[test]
827	fn a_climb_below_the_ceiling_settles_in_the_deadband() {
828		let mut control = control();
829		let start = kio::clock::now();
830		control.update(Some(bps(1_000_000)), start).unwrap();
831		control
832			.update(Some(bps(2_000_000)), start.saturating_add(Duration::from_secs(1)))
833			.unwrap();
834		assert!(control.deadline().is_some());
835
836		let (applied, _) = follow(&mut control, bps(2_000_000));
837		let settled = *applied.last().unwrap();
838		assert!(settled <= bps(2_000_000) && bps(2_000_000).abs_diff(settled) < band(settled));
839	}
840
841	/// A remainder inside the deadband below the ceiling can never clear it, so it is
842	/// not scheduled, whether it is all of the raise or what one step leaves over.
843	#[test]
844	fn a_raise_inside_the_deadband_is_not_scheduled() {
845		let start = kio::clock::now();
846		let mut whole = control();
847		whole.update(Some(bps(2_000_000)), start).unwrap();
848		assert_eq!(
849			whole.update(Some(bps(2_050_000)), start.saturating_add(Duration::from_secs(1))),
850			None
851		);
852		assert_eq!(whole.deadline(), None);
853
854		// 1M to 1.3M: one second allows 1.25M, leaving 50k under the 62.5k band.
855		let mut remainder = control();
856		remainder.update(Some(bps(1_000_000)), start).unwrap();
857		assert_eq!(
858			remainder.update(Some(bps(1_300_000)), start.saturating_add(Duration::from_secs(1))),
859			Some(on(bps(1_250_000)))
860		);
861		assert_eq!(remainder.deadline(), None);
862	}
863
864	/// Losing the estimate or a drop cancels a scheduled raise.
865	#[test]
866	fn a_missing_estimate_or_a_drop_clears_the_deadline() {
867		let start = kio::clock::now();
868		let scheduled = || {
869			let mut control = control();
870			control.update(Some(bps(1_000_000)), start).unwrap();
871			control
872				.update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1)))
873				.unwrap();
874			assert!(control.deadline().is_some());
875			control
876		};
877
878		let mut control = scheduled();
879		assert_eq!(control.update(None, start.saturating_add(Duration::from_secs(2))), None);
880		assert_eq!(control.deadline(), None);
881
882		let mut control = scheduled();
883		assert_eq!(
884			control.update(Some(bps(800_000)), start.saturating_add(Duration::from_secs(2))),
885			Some(on(bps(800_000)))
886		);
887		assert_eq!(control.deadline(), None);
888	}
889
890	/// A raise the sender refused is taken back and retried no sooner than one ramp
891	/// step later, even on the final step to the ceiling, which is otherwise due early.
892	#[test]
893	fn a_failed_raise_is_retried() {
894		let mut control = control();
895		let start = kio::clock::now();
896		control.update(Some(bps(1_000_000)), start).unwrap();
897		control
898			.update(Some(bps(4_000_000)), start.saturating_add(Duration::from_secs(1)))
899			.unwrap();
900		let (applied, last) = follow(&mut control, bps(4_000_000));
901		assert_eq!(applied.last(), Some(&bps(4_000_000)));
902		let before = applied[applied.len() - 2];
903
904		let failed = last.unwrap().saturating_add(Duration::from_millis(1));
905		control.failed(failed);
906		assert_eq!(control.target(), on(before), "the previous target is restored");
907		let retry = control.deadline().expect("the failed raise is retried");
908		assert!(
909			retry >= failed.saturating_add(RETRY),
910			"{retry:?} is sooner than one step after {failed:?}"
911		);
912
913		// A second report has nothing left to take back.
914		control.failed(failed.saturating_add(Duration::from_secs(1)));
915		assert_eq!(control.target(), on(before));
916		assert_eq!(control.deadline(), Some(retry));
917
918		assert_eq!(control.update(Some(bps(4_000_000)), retry), Some(on(bps(4_000_000))));
919		assert_eq!(control.deadline(), None);
920	}
921
922	/// A drop the sender refused is retried too: the sender is still above the grant.
923	#[test]
924	fn a_failed_drop_is_retried() {
925		let mut control = control();
926		let start = kio::clock::now();
927		control.update(Some(bps(1_000_000)), start).unwrap();
928		control.failed(start);
929		assert_eq!(control.target(), on(bps(4_000_000)));
930		assert_eq!(control.deadline(), Some(start.saturating_add(RETRY)));
931		assert_eq!(
932			control.update(Some(bps(1_000_000)), start.saturating_add(RETRY)),
933			Some(on(bps(1_000_000)))
934		);
935		assert_eq!(control.deadline(), None);
936	}
937
938	/// Only the change the last update returned can be taken back.
939	#[test]
940	fn a_failure_after_no_change_does_nothing() {
941		let mut control = control();
942		let start = kio::clock::now();
943		control.update(Some(bps(2_000_000)), start).unwrap();
944		assert_eq!(
945			control.update(Some(bps(1_960_000)), start.saturating_add(Duration::from_secs(1))),
946			None
947		);
948		control.failed(start.saturating_add(Duration::from_secs(1)));
949		assert_eq!(control.target(), on(bps(2_000_000)));
950		assert_eq!(control.deadline(), None);
951	}
952
953	/// The grant recovers once and never changes again, and the sender refuses the final
954	/// raise once: the follower still wakes on its own and carries the target to the ceiling.
955	#[tokio::test(start_paused = true)]
956	async fn a_follower_recovers_a_quiet_grant() {
957		let grant = bandwidth::Producer::new();
958		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
959
960		grant.set(Some(bps(1_000_000))).unwrap();
961		assert_eq!(follower.next().await.unwrap(), on(bps(1_000_000)));
962
963		tokio::time::advance(Duration::from_secs(1)).await;
964		grant.set(Some(bps(4_000_000))).unwrap();
965
966		let mut applied = Vec::new();
967		let mut refused = false;
968		// A minute without a wake is far past anything the ramp still needs.
969		while let Ok(target) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await {
970			let Target::Enabled(target) = target.unwrap() else {
971				panic!("a policy without a lower rendition disabled the sender")
972			};
973			if target == bps(4_000_000) && !refused {
974				refused = true;
975				follower.failed();
976				continue;
977			}
978			applied.push(target);
979		}
980		assert!(refused, "the final raise was never asked for: {applied:?}");
981		assert_eq!(applied.last(), Some(&bps(4_000_000)), "{applied:?}");
982		assert!(applied.windows(2).all(|pair| pair[0] < pair[1]), "{applied:?}");
983	}
984
985	/// A follower that assumes its sender's state corrects it against an unchanged grant: a
986	/// sender below a full grant ramps back up, and a disabled one resumes.
987	#[tokio::test(start_paused = true)]
988	async fn an_assumed_target_climbs_to_the_grant() {
989		let grant = bandwidth::Producer::new();
990		grant.set(Some(bps(4_000_000))).unwrap();
991
992		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
993		follower.assume(on(bps(1_000_000)));
994		let mut applied = Vec::new();
995		while let Ok(target) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await {
996			applied.push(target.unwrap());
997		}
998		assert_eq!(applied.last(), Some(&on(bps(4_000_000))));
999		assert!(applied.len() > 1, "the climb ramps rather than jumping: {applied:?}");
1000
1001		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
1002		follower.assume(Target::Disabled);
1003		assert!(matches!(follower.next().await.unwrap(), Target::Enabled(_)));
1004	}
1005
1006	/// A follower that assumes a sender above its ceiling lowers it to the ceiling, even from
1007	/// inside the deadband, with the grant unchanged.
1008	#[tokio::test(start_paused = true)]
1009	async fn an_assumed_target_above_the_ceiling_comes_down() {
1010		let grant = bandwidth::Producer::new();
1011		grant.set(Some(bps(2_000_000))).unwrap();
1012		for above in [4_000_000, 2_050_000] {
1013			let mut follower = Grant::new(grant.consume(), Policy::new(bps(2_000_000)));
1014			follower.assume(on(bps(above)));
1015			assert_eq!(follower.next().await.unwrap(), on(bps(2_000_000)), "from {above}");
1016		}
1017	}
1018
1019	/// A new policy feeds the unchanged grant through it at once, and setting the same
1020	/// policy again changes nothing.
1021	#[tokio::test(start_paused = true)]
1022	async fn a_new_policy_feeds_the_current_grant() {
1023		let grant = bandwidth::Producer::new();
1024		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
1025		grant.set(Some(bps(3_000_000))).unwrap();
1026		assert_eq!(follower.next().await.unwrap(), on(bps(3_000_000)));
1027
1028		follower.set_policy(Policy::new(bps(2_000_000)));
1029		assert_eq!(follower.policy().max, bps(2_000_000));
1030		// The 3 Mbps grant no longer fits under the new 2 Mbps ceiling, which is where a
1031		// new policy starts, so nothing moves until the grant does.
1032		assert!(
1033			kio::clock::timeout(Duration::from_secs(60), follower.next())
1034				.await
1035				.is_err()
1036		);
1037
1038		follower.set_policy(Policy::new(bps(4_000_000)));
1039		assert_eq!(follower.next().await.unwrap(), on(bps(3_000_000)));
1040		follower.set_policy(Policy::new(bps(4_000_000)));
1041		assert!(
1042			kio::clock::timeout(Duration::from_secs(60), follower.next())
1043				.await
1044				.is_err()
1045		);
1046	}
1047
1048	/// A raised ceiling set before the follower polls a grant between the old and new
1049	/// ceilings follows that grant, rather than clamping it to the old ceiling and
1050	/// reporting nothing while the sender runs at the new one.
1051	#[tokio::test(start_paused = true)]
1052	async fn a_raised_policy_follows_the_next_grant() {
1053		let grant = bandwidth::Producer::new();
1054		let mut follower = Grant::new(grant.consume(), Policy::new(bps(2_000_000)));
1055		grant.set(Some(bps(2_000_000))).unwrap();
1056		assert!(
1057			kio::clock::timeout(Duration::from_secs(60), follower.next())
1058				.await
1059				.is_err(),
1060			"settled at the 2 Mbps ceiling"
1061		);
1062
1063		grant.set(Some(bps(3_000_000))).unwrap();
1064		follower.set_policy(Policy::new(bps(4_000_000)));
1065		assert_eq!(follower.next().await.unwrap(), on(bps(3_000_000)));
1066	}
1067
1068	/// A new lower rendition alone keeps the target the sender is actually at, so a
1069	/// grant at the ceiling still ramps it there instead of reading as already applied.
1070	#[tokio::test(start_paused = true)]
1071	async fn a_new_lower_keeps_the_applied_target() {
1072		let grant = bandwidth::Producer::new();
1073		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
1074		grant.set(Some(bps(2_000_000))).unwrap();
1075		assert_eq!(follower.next().await.unwrap(), on(bps(2_000_000)));
1076
1077		grant.set(Some(bps(4_000_000))).unwrap();
1078		let mut policy = Policy::new(bps(4_000_000));
1079		policy.lower = Some(bps(1_000_000));
1080		follower.set_policy(policy);
1081
1082		let mut applied = Vec::new();
1083		while let Ok(target) = kio::clock::timeout(Duration::from_secs(60), follower.next()).await {
1084			applied.push(target.unwrap());
1085		}
1086		assert_eq!(applied.last(), Some(&on(bps(4_000_000))), "{applied:?}");
1087		assert!(applied.len() > 1, "a raise from 2 Mbps ramps: {applied:?}");
1088	}
1089
1090	/// A grant no session probes for, like a whole estimate, never disables a rendition,
1091	/// however far it falls under the band boundary.
1092	#[tokio::test(start_paused = true)]
1093	async fn an_unprobed_follower_never_disables() {
1094		let grant = bandwidth::Producer::new();
1095		let mut policy = Policy::new(bps(4_000_000));
1096		policy.lower = Some(bps(2_000_000));
1097		let mut follower = Grant::new(grant.consume(), policy);
1098		grant.set(Some(bps(1_000_000))).unwrap();
1099		assert_eq!(follower.next().await.unwrap(), on(bps(1_000_000)));
1100	}
1101
1102	/// A closed grant ends the follower with the reason.
1103	#[tokio::test(start_paused = true)]
1104	async fn a_closed_grant_ends_the_follower() {
1105		let grant = bandwidth::Producer::new();
1106		let mut follower = Grant::new(grant.consume(), Policy::new(bps(4_000_000)));
1107		drop(grant);
1108		assert!(follower.next().await.is_err());
1109	}
1110
1111	/// A 5 Mbps rendition above a 2.5 Mbps one, probed, so the boundary lands on 3_333_333.
1112	fn rung() -> Control {
1113		let mut policy = Policy::new(bps(5_000_000));
1114		policy.lower = Some(bps(2_500_000));
1115		let mut control = Control::new(policy);
1116		control.set_probed(true);
1117		control
1118	}
1119
1120	#[test]
1121	fn a_rung_disables_below_its_boundary() {
1122		let mut rung = rung();
1123		let start = kio::clock::now();
1124
1125		// Squeezed, but still inside its band: it adapts like any sender.
1126		assert_eq!(rung.update(Some(bps(3_500_000)), start), Some(on(bps(3_500_000))));
1127		// Below it, the lower rendition is the better picture, so stop.
1128		let off = start.saturating_add(Duration::from_millis(100));
1129		assert_eq!(rung.update(Some(bps(3_000_000)), off), Some(Target::Disabled));
1130		assert_eq!(rung.target(), Target::Disabled);
1131		assert_eq!(rung.deadline(), None, "only a new estimate resumes it");
1132	}
1133
1134	/// The lowest rendition has no lower one, so no grant disables it: it floors at
1135	/// `min` and leaves the rest to the transport, which can only probe with what it sends.
1136	#[test]
1137	fn the_lowest_rung_never_disables() {
1138		let mut lowest = Control::new(Policy::new(bps(350_000)));
1139		lowest.set_probed(true);
1140		assert_eq!(lowest.update(Some(bps(1)), kio::clock::now()), Some(on(bps(35_000))));
1141	}
1142
1143	/// Without a session probing for it, a stopped rendition could never see the estimate
1144	/// rise, so it keeps encoding and follows its grant down instead.
1145	#[test]
1146	fn an_unprobed_rung_never_disables() {
1147		let mut rung = rung();
1148		rung.set_probed(false);
1149		assert_eq!(
1150			rung.update(Some(bps(1_000_000)), kio::clock::now()),
1151			Some(on(bps(1_000_000)))
1152		);
1153	}
1154
1155	/// A rendition disabled while probing resumes at the next estimate once probing stops,
1156	/// following that grant rather than waiting on an estimate that can no longer rise.
1157	#[test]
1158	fn a_disabled_rung_resumes_when_probing_stops() {
1159		let mut rung = rung();
1160		let start = kio::clock::now();
1161		assert_eq!(rung.update(Some(bps(1_000_000)), start), Some(Target::Disabled));
1162
1163		rung.set_probed(false);
1164		assert_eq!(
1165			rung.update(Some(bps(1_000_000)), start.saturating_add(Duration::from_secs(1))),
1166			Some(on(bps(1_000_000)))
1167		);
1168	}
1169
1170	#[test]
1171	fn a_rung_resumes_past_the_hysteresis_and_ramps() {
1172		let mut rung = rung();
1173		let start = kio::clock::now();
1174		assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled));
1175
1176		// Back over the boundary, but not by the 5% hysteresis: stay off.
1177		assert_eq!(
1178			rung.update(Some(bps(3_400_000)), start.saturating_add(Duration::from_secs(1))),
1179			None
1180		);
1181		assert_eq!(
1182			rung.update(Some(bps(3_499_000)), start.saturating_add(Duration::from_secs(2))),
1183			None
1184		);
1185		assert_eq!(rung.target(), Target::Disabled);
1186
1187		// Clear of it: resume at the boundary rather than the whole estimate.
1188		let resumed = start.saturating_add(Duration::from_secs(3));
1189		assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333))));
1190
1191		// Then ramp at 25%/s like any raise, on deadlines alone.
1192		let (applied, _) = follow(&mut rung, bps(5_000_000));
1193		assert_eq!(applied.last(), Some(&bps(5_000_000)), "{applied:?}");
1194	}
1195
1196	/// A grant jittering around the boundary must not flap the catalog: the deadband
1197	/// keeps a rung on until the grant falls well under its applied target, and the
1198	/// resume margin keeps it off until the grant is clearly back.
1199	#[test]
1200	fn jitter_at_the_boundary_does_not_flap() {
1201		let mut rung = rung();
1202		let start = kio::clock::now();
1203		rung.update(Some(bps(3_400_000)), start).unwrap();
1204
1205		// About 3% either side of the boundary, every 100ms for 10s.
1206		let jitter = |tick: u64| if tick.is_multiple_of(2) { 3_250_000 } else { 3_430_000 };
1207		for tick in 1..=100u64 {
1208			let at = start.saturating_add(Duration::from_millis(100 * tick));
1209			assert_eq!(rung.update(Some(bps(jitter(tick))), at), None, "tick {tick}");
1210		}
1211		assert_eq!(rung.target(), on(bps(3_400_000)));
1212
1213		// A real drop turns it off, and the same jitter can't bring it back.
1214		let off = start.saturating_add(Duration::from_secs(20));
1215		assert_eq!(rung.update(Some(bps(3_000_000)), off), Some(Target::Disabled));
1216		for tick in 1..=100u64 {
1217			let at = off.saturating_add(Duration::from_millis(100 * tick));
1218			assert_eq!(rung.update(Some(bps(jitter(tick))), at), None, "tick {tick}");
1219		}
1220		assert_eq!(rung.target(), Target::Disabled);
1221	}
1222
1223	#[test]
1224	fn a_missing_estimate_holds_a_disabled_rung() {
1225		let mut rung = rung();
1226		let now = kio::clock::now();
1227		rung.update(Some(bps(1_000_000)), now).unwrap();
1228		assert_eq!(rung.update(None, now.saturating_add(Duration::from_secs(10))), None);
1229		assert_eq!(rung.target(), Target::Disabled);
1230	}
1231
1232	/// A resume margin above the ceiling could never be met by an estimate clamped to
1233	/// that ceiling, so it is capped there.
1234	#[test]
1235	fn a_rung_just_above_its_lower_still_resumes() {
1236		let mut policy = Policy::new(bps(1_000_000));
1237		policy.lower = Some(bps(950_000));
1238		let mut rung = Control::new(policy);
1239		rung.set_probed(true);
1240		let now = kio::clock::now();
1241		assert_eq!(rung.update(Some(bps(500_000)), now), Some(Target::Disabled));
1242		assert_eq!(
1243			rung.update(Some(bps(10_000_000)), now.saturating_add(Duration::from_secs(1))),
1244			Some(on(bps(966_666)))
1245		);
1246	}
1247
1248	/// A lower rendition at or above this one's ceiling leaves no band to encode in.
1249	#[test]
1250	fn a_rung_without_a_band_never_disables() {
1251		let mut policy = Policy::new(bps(1_000_000));
1252		policy.lower = Some(bps(1_000_000));
1253		let mut rung = Control::new(policy);
1254		rung.set_probed(true);
1255		assert_eq!(rung.update(Some(bps(1)), kio::clock::now()), Some(on(bps(100_000))));
1256	}
1257
1258	/// A disable or resume the sender failed to apply is taken back and retried, so the
1259	/// catalog follows what the encoder did rather than what was asked.
1260	#[test]
1261	fn a_failed_toggle_is_retried() {
1262		let mut rung = rung();
1263		let start = kio::clock::now();
1264		assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled));
1265		rung.failed(start);
1266		assert_eq!(rung.target(), on(bps(5_000_000)));
1267		assert_eq!(rung.deadline(), Some(start.saturating_add(RETRY)));
1268		assert_eq!(
1269			rung.update(Some(bps(3_000_000)), start.saturating_add(RETRY)),
1270			Some(Target::Disabled)
1271		);
1272
1273		let resumed = start.saturating_add(Duration::from_secs(5));
1274		assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333))));
1275		rung.failed(resumed);
1276		assert_eq!(rung.target(), Target::Disabled);
1277		assert_eq!(rung.deadline(), Some(resumed.saturating_add(RETRY)));
1278		assert_eq!(
1279			rung.update(Some(bps(5_000_000)), resumed.saturating_add(RETRY)),
1280			Some(on(bps(3_333_333)))
1281		);
1282	}
1283
1284	/// A resume the sender failed, whose grant then falls back under the margin, drops
1285	/// its retry: an update at that deadline would change nothing, so a follower woken
1286	/// by it would spin.
1287	#[test]
1288	fn a_failed_resume_under_the_margin_stops_retrying() {
1289		let mut rung = rung();
1290		let start = kio::clock::now();
1291		assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(Target::Disabled));
1292		let resumed = start.saturating_add(Duration::from_secs(1));
1293		assert_eq!(rung.update(Some(bps(5_000_000)), resumed), Some(on(bps(3_333_333))));
1294		rung.failed(resumed);
1295		assert_eq!(rung.deadline(), Some(resumed.saturating_add(RETRY)));
1296
1297		assert_eq!(
1298			rung.update(Some(bps(3_000_000)), resumed.saturating_add(RETRY / 2)),
1299			None
1300		);
1301		assert_eq!(rung.target(), Target::Disabled);
1302		assert_eq!(rung.deadline(), None);
1303	}
1304
1305	/// A rung following an unprobed grant under its boundary disables once probing starts,
1306	/// though the grant never moves, unless the grant can fund it.
1307	#[test]
1308	fn a_rung_under_its_boundary_disables_when_probing_starts() {
1309		let mut rung = rung();
1310		rung.set_probed(false);
1311		let start = kio::clock::now();
1312		assert_eq!(rung.update(Some(bps(3_000_000)), start), Some(on(bps(3_000_000))));
1313
1314		let mut funded = rung.clone();
1315		rung.set_probed(true);
1316		assert_eq!(
1317			rung.update(Some(bps(3_000_000)), start.saturating_add(Duration::from_millis(100))),
1318			Some(Target::Disabled)
1319		);
1320
1321		// A grant over the boundary funds it, so it ramps up from under it instead.
1322		funded.set_probed(true);
1323		assert_eq!(
1324			funded.update(Some(bps(5_000_000)), start.saturating_add(Duration::from_secs(1))),
1325			Some(on(bps(3_750_000)))
1326		);
1327	}
1328
1329	/// The same when the lower rendition rises over the applied target.
1330	#[test]
1331	fn a_rung_under_a_raised_boundary_disables() {
1332		let mut rung = rung();
1333		let start = kio::clock::now();
1334		assert_eq!(rung.update(Some(bps(3_500_000)), start), Some(on(bps(3_500_000))));
1335
1336		// The boundary moves from 3.33 Mbps to 3.67 Mbps, over the applied target.
1337		let mut policy = rung.policy.clone();
1338		policy.lower = Some(bps(3_000_000));
1339		assert!(rung.set_policy(policy));
1340		assert_eq!(
1341			rung.update(Some(bps(3_500_000)), start.saturating_add(Duration::from_millis(100))),
1342			Some(Target::Disabled)
1343		);
1344	}
1345
1346	/// End to end through the allocator: descending priority down the renditions fills
1347	/// the lower ones first, so a shrinking estimate disables the top rendition and leaves
1348	/// the lower ones at their full share. The top ones come back once the estimate
1349	/// does, even after their viewers have left, since an idle reservation still reads
1350	/// the slice it would get back.
1351	#[test]
1352	fn the_top_rung_yields_to_the_lower_ones() {
1353		use moq_net::{broadcast, track};
1354
1355		let estimate = bandwidth::Producer::new();
1356		let allocator = bandwidth::Allocator::new(estimate.consume());
1357		let broadcast = broadcast::Info::default().produce();
1358		// Lowest first, each a step below the last in priority and a doubling in ceiling.
1359		let ladder = [
1360			(1_000_000, None),
1361			(2_000_000, Some(1_000_000)),
1362			(4_000_000, Some(2_000_000)),
1363		];
1364		let mut tracks = Vec::new();
1365		let mut viewers = Vec::new();
1366		let mut reservations = Vec::new();
1367		let mut controls = Vec::new();
1368		for (index, (max, lower)) in ladder.into_iter().enumerate() {
1369			let priority = 60 - index as i8;
1370			let track = broadcast
1371				.create_track(format!("{max}"), track::Info::default().with_priority(priority))
1372				.unwrap();
1373			viewers.push(Some(track.subscribe(None)));
1374			reservations.push(allocator.reserve(&track.demand(), bps(max)));
1375			let mut policy = Policy::new(bps(max));
1376			policy.lower = lower.map(bps);
1377			let mut control = Control::new(policy);
1378			control.set_probed(true);
1379			controls.push(control);
1380			tracks.push(track);
1381		}
1382		let start = kio::clock::now();
1383		let mut update = |at: Instant| -> Vec<Target> {
1384			controls
1385				.iter_mut()
1386				.zip(&reservations)
1387				.map(|(control, reservation)| {
1388					control.update(reservation.rate(), at);
1389					control.target()
1390				})
1391				.collect()
1392		};
1393
1394		// 4.5 Mbps funds the lower two in full and leaves 1.5 Mbps, under the top
1395		// rendition's 2.67 Mbps boundary.
1396		estimate.set(Some(bps(4_500_000))).unwrap();
1397		assert_eq!(
1398			update(start),
1399			[on(bps(1_000_000)), on(bps(2_000_000)), Target::Disabled]
1400		);
1401
1402		// Shrinking further takes the middle one next, still keeping the lowest whole.
1403		estimate.set(Some(bps(2_000_000))).unwrap();
1404		assert_eq!(
1405			update(start.saturating_add(Duration::from_secs(1))),
1406			[on(bps(1_000_000)), Target::Disabled, Target::Disabled]
1407		);
1408
1409		// Below every boundary, the lowest still encodes at what it gets.
1410		estimate.set(Some(bps(200_000))).unwrap();
1411		assert_eq!(
1412			update(start.saturating_add(Duration::from_secs(2))),
1413			[on(bps(200_000)), Target::Disabled, Target::Disabled]
1414		);
1415
1416		// The viewers of the stopped renditions fall back to the lowest and leave, and
1417		// the uplink recovers: both resume at their boundaries without a viewer.
1418		viewers[1] = None;
1419		viewers[2] = None;
1420		estimate.set(Some(bps(8_000_000))).unwrap();
1421		let recovered = update(start.saturating_add(Duration::from_secs(3)));
1422		assert_eq!(recovered[1], on(bps(1_333_333)));
1423		assert_eq!(recovered[2], on(bps(2_666_666)));
1424	}
1425
1426	/// Random walks of grants, probing, policy changes, refused changes, and time,
1427	/// replayed through [`Control`] the way [`Grant`] drives it, checking the rung's
1428	/// invariants after every wake.
1429	mod model {
1430		use proptest::prelude::*;
1431		use proptest::test_runner::{Config, RngAlgorithm, RngSeed, TestRunner};
1432
1433		use super::*;
1434
1435		#[derive(Clone, Debug)]
1436		enum Op {
1437			Grant(Option<u64>),
1438			/// Move the grant by this many per mille, around the deadband and the margins.
1439			Jitter(i16),
1440			Probed(bool),
1441			Lower(Option<u64>),
1442			Max(u64),
1443			Min(u64),
1444			Advance(Duration),
1445		}
1446
1447		fn op() -> impl Strategy<Value = Op> {
1448			let rate = || prop_oneof![0..12_000_000u64, 0..2_000u64];
1449			prop_oneof![
1450				3 => proptest::option::weighted(0.9, rate()).prop_map(Op::Grant),
1451				3 => (-80i16..=80).prop_map(Op::Jitter),
1452				2 => any::<bool>().prop_map(Op::Probed),
1453				2 => proptest::option::weighted(0.8, rate()).prop_map(Op::Lower),
1454				1 => (1..10_000_000u64).prop_map(Op::Max),
1455				1 => rate().prop_map(Op::Min),
1456				4 => prop_oneof![0..400u64, 0..20_000u64].prop_map(|ms| Op::Advance(Duration::from_millis(ms))),
1457			]
1458		}
1459
1460		/// What the follower feeds the control, and when.
1461		struct Model {
1462			control: Control,
1463			now: Instant,
1464			grant: Option<bandwidth::Rate>,
1465			probed: bool,
1466		}
1467
1468		impl Model {
1469			fn apply(&mut self, op: Op, fail: bool) {
1470				let mut policy = self.control.policy.clone();
1471				match op {
1472					Op::Grant(grant) => self.set_grant(grant.map(bps), fail),
1473					Op::Jitter(per_mille) => {
1474						let Some(grant) = self.grant else { return };
1475						let moved = i128::from(grant.as_bps()) * (1_000 + i128::from(per_mille)) / 1_000;
1476						self.set_grant(Some(bps(moved as u64)), fail);
1477					}
1478					Op::Probed(probed) => {
1479						// The grant reports a flip, and only a flip.
1480						if probed != self.probed {
1481							self.probed = probed;
1482							self.wake(fail);
1483						}
1484					}
1485					Op::Lower(lower) => {
1486						policy.lower = lower.map(bps);
1487						self.set_policy(policy, fail);
1488					}
1489					Op::Max(max) => {
1490						policy.max = bps(max);
1491						self.set_policy(policy, fail);
1492					}
1493					Op::Min(min) => {
1494						policy.min = bps(min);
1495						self.set_policy(policy, fail);
1496					}
1497					Op::Advance(elapsed) => {
1498						let end = self.now.saturating_add(elapsed);
1499						while let Some(at) = self.control.deadline().filter(|at| *at <= end) {
1500							self.now = at;
1501							self.wake(fail);
1502						}
1503						self.now = end;
1504					}
1505				}
1506			}
1507
1508			fn set_grant(&mut self, grant: Option<bandwidth::Rate>, fail: bool) {
1509				// The grant wakes the follower only when it moves.
1510				if grant != self.grant {
1511					self.grant = grant;
1512					self.wake(fail);
1513				}
1514			}
1515
1516			fn set_policy(&mut self, policy: Policy, fail: bool) {
1517				if self.control.set_policy(policy) {
1518					self.wake(fail);
1519				}
1520			}
1521
1522			/// One update, as the follower makes on any wake, then the sender refusing what
1523			/// it returned when `fail`.
1524			fn wake(&mut self, fail: bool) {
1525				let before = self.control.clone();
1526				self.control.set_probed(self.probed);
1527				let change = self.control.update(self.grant, self.now);
1528				self.check(&before, change);
1529				if fail && change.is_some() {
1530					self.control.failed(self.now);
1531				}
1532				// Anything already due would wake the follower again at once, for nothing.
1533				if let Some(at) = self.control.deadline() {
1534					assert!(at > self.now, "a deadline at {at:?} is already due at {:?}", self.now);
1535				}
1536			}
1537
1538			fn check(&self, before: &Control, change: Option<Target>) {
1539				let policy = &self.control.policy;
1540				let min = policy.min.min(policy.max);
1541				let boundary = policy.boundary();
1542				if let Target::Enabled(rate) = self.control.target() {
1543					assert!(rate <= policy.max, "{rate:?} over {policy:?}");
1544					assert!(rate >= min, "{rate:?} under {policy:?}");
1545				}
1546
1547				if change == Some(Target::Disabled) {
1548					let boundary = boundary.expect("a policy without a band disabled the rung");
1549					assert!(self.probed, "an unprobed rung disabled");
1550					let desired = self
1551						.grant
1552						.expect("a missing estimate disabled the rung")
1553						.clamp(min, policy.max);
1554					assert!(desired < boundary, "{desired:?} is not under {boundary:?}");
1555					let Target::Enabled(was) = before.target() else {
1556						panic!("a disabled rung disabled again")
1557					};
1558					// Outside the deadband, unless the applied target was already under the boundary.
1559					assert!(
1560						was < boundary || was.as_bps() - desired.as_bps() >= band(was).as_bps(),
1561						"{was:?} to {desired:?} is inside the deadband"
1562					);
1563				}
1564
1565				// A missing estimate holds whatever the rung was doing.
1566				let Some(estimate) = self.grant else { return };
1567				let desired = estimate.clamp(min, policy.max);
1568				match self.control.target() {
1569					Target::Disabled => {
1570						assert!(self.probed, "an unprobed rung stayed disabled");
1571						let boundary = boundary.expect("a policy without a band stayed disabled");
1572						let clear = (boundary.as_bps() + band(boundary).as_bps()).min(policy.max.as_bps());
1573						assert!(
1574							desired.as_bps() < clear,
1575							"{desired:?} clears {boundary:?} by the margin, yet the rung stayed disabled"
1576						);
1577					}
1578					Target::Enabled(rate) => {
1579						if let Some(boundary) = boundary.filter(|boundary| self.probed && desired < *boundary) {
1580							assert!(rate >= boundary, "{rate:?} stayed on under {boundary:?} at {desired:?}");
1581							assert!(
1582								rate.as_bps() - desired.as_bps() < band(rate).as_bps(),
1583								"{rate:?} stayed on past the deadband at {desired:?}"
1584							);
1585						}
1586					}
1587				}
1588			}
1589		}
1590
1591		#[test]
1592		fn invariants_hold_on_random_walks() {
1593			let mut runner = TestRunner::new(Config {
1594				cases: 512,
1595				rng_seed: RngSeed::Fixed(6781),
1596				// Every op forks the runner's RNG, which ChaCha makes the bulk of a debug run.
1597				rng_algorithm: RngAlgorithm::XorShift,
1598				failure_persistence: None,
1599				..Default::default()
1600			});
1601			let walk = (
1602				1..10_000_000u64,
1603				proptest::option::of(0..12_000_000u64),
1604				proptest::collection::vec((op(), proptest::bool::weighted(0.1)), 1..200),
1605			);
1606			runner
1607				.run(&walk, |(max, lower, ops)| {
1608					let mut policy = Policy::new(bps(max));
1609					policy.lower = lower.map(bps);
1610					let mut model = Model {
1611						control: Control::new(policy),
1612						now: kio::clock::now(),
1613						grant: None,
1614						probed: false,
1615					};
1616					for (op, fail) in ops {
1617						model.apply(op, fail);
1618					}
1619					Ok(())
1620				})
1621				.unwrap();
1622		}
1623	}
1624}