diff --git a/.github/workflows/ts.yml b/.github/workflows/ts.yml index 13fdb88032e..5b78243eb13 100644 --- a/.github/workflows/ts.yml +++ b/.github/workflows/ts.yml @@ -244,7 +244,7 @@ jobs: run: nix develop --command just test ts --headroom --rate 7000000 --queue 250ms --duration 120 env: HARNESS_RUNS: ${{ runner.temp }}/moq-test-runs - MOQ_QUIC_CONGESTION_CONTROL: loss + MOQ_QUIC_CONGESTION_CONTROL: cubic # Passthrough over the overflowing path, under its 10 Mb/s multiplex: what arrives must be # the source's packets in place, through the source's last packet. @@ -253,7 +253,7 @@ jobs: run: nix develop --command just test ts --passthrough --rate 7000000 --queue 250ms --duration 120 env: HARNESS_RUNS: ${{ runner.temp }}/moq-test-runs - MOQ_QUIC_CONGESTION_CONTROL: loss + MOQ_QUIC_CONGESTION_CONTROL: cubic # Two minutes of MoQ content faults and a congested bottleneck, on a paused clock: each # recovery graded against what was delivered and decoded, and the latency must not drift. diff --git a/cpp/obs/src/moq-settings.cpp b/cpp/obs/src/moq-settings.cpp index 855b4eb17a6..8850c76d9e5 100644 --- a/cpp/obs/src/moq-settings.cpp +++ b/cpp/obs/src/moq-settings.cpp @@ -211,11 +211,10 @@ const std::vector &Fields() "forever. A first connect that reaches no server fails the stream at once.")); // QUIC transport. - f.push_back(Choose( - QUIC_CONGESTION_CONTROL, "Congestion control", - {{"Automatic", AUTO}, {"Delay-based (BBR)", "delay"}, {"Loss-based (CUBIC)", "loss"}}, false, - "Delay-based keeps queues short and the send rate steady enough for an " - "encoder to track. Loss-based chases throughput instead.")); + f.push_back(Choose(QUIC_CONGESTION_CONTROL, "Congestion control", + {{"Automatic", AUTO}, {"BBR", "bbr"}, {"CUBIC", "cubic"}}, false, + "BBR, the default, keeps queues short and the send rate steady enough for an " + "encoder to track. CUBIC chases throughput instead.")); f.push_back(Number(QUIC_MAX_STREAMS, "Max concurrent streams", static_cast(d.quic.max_streams.value_or(0)), 1, 65536, 1, "MoQ opens a stream per group, so a busy publisher wants this high.")); @@ -346,15 +345,18 @@ std::string Configure(obs_data_t *settings, moq::ClientConfig &config) if (const auto timeout = Milliseconds(settings, BACKOFF_TIMEOUT, error); timeout.count() != 0) config.backoff.timeout = timeout; - // Automatic leaves the tri-states and the congestion family unset, which keeps the - // transport free to pick. - if (const char *family = OptionalString(settings, QUIC_CONGESTION_CONTROL)) { - if (strcmp(family, "delay") == 0) - config.quic.congestion_control = moq::CongestionControl::delay(); - else if (strcmp(family, "loss") == 0) - config.quic.congestion_control = moq::CongestionControl::loss(); + // Automatic leaves the tri-states and the congestion control unset, which keeps the + // library default. A scene saved with a released family name (`delay`, `loss`) is + // refused rather than mapped, and the message tells the user how to fix it. + if (const char *algorithm = OptionalString(settings, QUIC_CONGESTION_CONTROL)) { + if (strcmp(algorithm, "bbr") == 0) + config.quic.congestion_control = moq::CongestionControl::bbr(); + else if (strcmp(algorithm, "cubic") == 0) + config.quic.congestion_control = moq::CongestionControl::cubic(); else - Refuse(error, std::string("unknown congestion control: ") + family); + Refuse(error, std::string("congestion control '") + algorithm + + "' is not supported: pick BBR or CUBIC for Congestion control in " + "the output's Advanced settings"); } config.quic.max_streams = Amount(settings, QUIC_MAX_STREAMS, error); config.quic.idle_timeout = Milliseconds(settings, QUIC_IDLE_TIMEOUT, error); diff --git a/cpp/obs/test/moq-settings-test.cpp b/cpp/obs/test/moq-settings-test.cpp index 1cd273357ea..db8fa72aaf8 100644 --- a/cpp/obs/test/moq-settings-test.cpp +++ b/cpp/obs/test/moq-settings-test.cpp @@ -180,7 +180,7 @@ int main() settings.ints["connect_timeout_ms"] = 7000; settings.ints["failover_delay_ms"] = 80; settings.strings["tls_host_name"] = "relay.example"; - settings.strings["quic_congestion_control"] = "loss"; + settings.strings["quic_congestion_control"] = "cubic"; settings.ints["quic_idle_timeout_ms"] = 9000; settings.ints["quic_keep_alive_ms"] = 0; settings.strings["quic_gso"] = "off"; @@ -193,7 +193,7 @@ int main() CHECK(config.race == std::chrono::milliseconds(80)); CHECK(config.tls.host_name == std::string("relay.example")); CHECK(config.quic.congestion_control); - CHECK(config.quic.congestion_control->eq(moq::CongestionControl::loss())); + CHECK(config.quic.congestion_control->eq(moq::CongestionControl::cubic())); CHECK(config.quic.idle_timeout == std::chrono::milliseconds(9000)); CHECK(config.quic.keep_alive == std::chrono::nanoseconds::zero()); CHECK(config.quic.gso == false); @@ -234,14 +234,17 @@ int main() } printf("key log is opt-in: ok\n"); - // A hand-edited scene collection naming an unknown family refuses rather than ignores it. - { + // A hand-edited scene collection naming an unknown algorithm, or one saved with a + // released family name, refuses rather than ignores it. + for (const char *algorithm : {"fast", "delay", "loss"}) { obs_data settings; MoQSettings::Defaults(&settings); settings.bools["advanced"] = true; - settings.strings["quic_congestion_control"] = "fast"; + settings.strings["quic_congestion_control"] = algorithm; moq::ClientConfig config; - CHECK(MoQSettings::Configure(&settings, config).find("congestion") != std::string::npos); + const std::string refused = MoQSettings::Configure(&settings, config); + CHECK(refused.find(algorithm) != std::string::npos); + CHECK(refused.find("pick BBR or CUBIC") != std::string::npos); } printf("unknown congestion control refused: ok\n"); diff --git a/dart/moq/lib/src/aliases.dart b/dart/moq/lib/src/aliases.dart index 16b599c9243..3a488d7368d 100644 --- a/dart/moq/lib/src/aliases.dart +++ b/dart/moq/lib/src/aliases.dart @@ -39,9 +39,9 @@ typedef Request = MoqRequest; /// The network transport carrying an incoming session. typedef Transport = MoqTransport; -/// The congestion control family for a QUIC connection. Build one with -/// `CongestionControl.delay()`, `.loss()`, or `.none()`; a new algorithm joins as -/// a new constructor. +/// The congestion control algorithm for a QUIC connection. Build one with +/// `CongestionControl.bbr()`, `.cubic()`, or `.unlimited()`; a new algorithm joins +/// as a new constructor named after it. typedef CongestionControl = MoqCongestionControl; /// Certificate trust and the mTLS identity for `ConnectOptions.tls`. diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index 606313c3a74..22d787ab48e 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -129,7 +129,7 @@ final class QuicConfig { /// Path MTU discovery; null leaves the choice to the backend. final bool? mtuDiscovery; - /// The congestion control family; null leaves the choice to the backend. + /// The congestion control algorithm; null runs BBR v3. final CongestionControl? congestionControl; /// Directory, which must exist, to write qlog traces into. diff --git a/dart/moq/test/moq_test.dart b/dart/moq/test/moq_test.dart index 1cd1739b35c..537dc5d63bc 100644 --- a/dart/moq/test/moq_test.dart +++ b/dart/moq/test/moq_test.dart @@ -592,7 +592,7 @@ void main() { keepAlive: Duration.zero, gso: false, mtuDiscovery: true, - congestionControl: CongestionControl.loss(), + congestionControl: CongestionControl.cubic(), keylog: false, ), once: true, diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index 756052f816f..825fcc3a455 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -110,7 +110,7 @@ Transport tuning, applied to accepted and dialed connections alike. ```toml [quic] -congestion_control = "delay" # "delay" (BBR v3, the default), "loss" (CUBIC), or "none". +congestion_control = "bbr" # "bbr" (BBR v3, the default), "cubic", or "unlimited". max_streams = 10000 # Concurrent streams per connection, bidi and uni; 0 is refused. Default. idle_timeout = "10s" # Drop a connection after this long with nothing on it. Default. # keep_alive = "3s" # Ping interval; unset or "0s" derives it from the idle timeout. @@ -123,8 +123,8 @@ qlog = "/var/log/moq/qlog" # Existing directory. # keylog = "/private/keys.log" # Explicit secret log path; unset is off. ``` -`congestion_control = "none"` runs no congestion control and no pacing. It is -meant for tests and controlled links, where nothing else shares the path. +`congestion_control = "unlimited"` runs no congestion control and no pacing. It +is meant for tests and controlled links, where nothing else shares the path. Set `keylog` only while debugging, since the file decrypts every captured session. Tokio and io\_uring open the configured path at initialization. New Unix files are diff --git a/go/wrapper/client.go b/go/wrapper/client.go index dd41fea4e38..87f69548a89 100644 --- a/go/wrapper/client.go +++ b/go/wrapper/client.go @@ -105,7 +105,7 @@ type QUICConfig struct { GSO *bool // MTUDiscovery toggles path MTU discovery. MTUDiscovery *bool - // CongestionControl picks the congestion control family; nil leaves the choice to the backend. + // CongestionControl picks the congestion control algorithm; nil runs BBR v3. CongestionControl *CongestionControl // Qlog is a directory, which must exist, to write qlog traces into. Qlog string diff --git a/go/wrapper/reconnect_test.go b/go/wrapper/reconnect_test.go index 691d091a194..41e38063458 100644 --- a/go/wrapper/reconnect_test.go +++ b/go/wrapper/reconnect_test.go @@ -330,7 +330,7 @@ func TestDialConnectionOptions(t *testing.T) { KeepAlive: ptr(time.Duration(0)), GSO: ptr(false), MTUDiscovery: ptr(true), - CongestionControl: moq.LossCongestionControl(), + CongestionControl: moq.CubicCongestionControl(), }, WebSocket: moq.WebSocketConfig{Enabled: ptr(false)}, }) diff --git a/go/wrapper/types.go b/go/wrapper/types.go index c284d6067c1..b012dac4f20 100644 --- a/go/wrapper/types.go +++ b/go/wrapper/types.go @@ -19,9 +19,9 @@ type ( AudioSampleFormat = ffi.MoqAudioSampleFormat // AudioFrame is one audio frame: PCM payload plus a presentation Timestamp. AudioFrame = ffi.MoqAudioFrame - // CongestionControl is the congestion control family for a QUIC connection. Build one with - // DelayCongestionControl, LossCongestionControl, or NoneCongestionControl; a new algorithm - // joins as a new builder. + // CongestionControl is the congestion control algorithm for a QUIC connection. Build one with + // BBRCongestionControl, CubicCongestionControl, or UnlimitedCongestionControl; a new algorithm + // joins as a new builder named after it. CongestionControl = ffi.MoqCongestionControl // ErrorScope is whether a protocol code is from the session or stream registry. ErrorScope = ffi.MoqErrorScope @@ -170,19 +170,19 @@ func DeflateCompression() *Compression { return ffi.MoqCompressionDeflate() } -// LossCongestionControl is loss-based (CUBIC): it chases throughput, so the send rate sawtooths. -func LossCongestionControl() *CongestionControl { - return ffi.MoqCongestionControlLoss() +// BBRCongestionControl is BBR v3, the default: it keeps queues short and the send rate steady. +func BBRCongestionControl() *CongestionControl { + return ffi.MoqCongestionControlBbr() } -// DelayCongestionControl is delay-based (BBR v3), the default: it keeps queues short and the send rate steady. -func DelayCongestionControl() *CongestionControl { - return ffi.MoqCongestionControlDelay() +// CubicCongestionControl is CUBIC: it chases throughput, so the send rate sawtooths. +func CubicCongestionControl() *CongestionControl { + return ffi.MoqCongestionControlCubic() } -// NoneCongestionControl runs no congestion control and no pacing, for tests and controlled links. -func NoneCongestionControl() *CongestionControl { - return ffi.MoqCongestionControlNone() +// UnlimitedCongestionControl runs no congestion control and no pacing, for tests and controlled links. +func UnlimitedCongestionControl() *CongestionControl { + return ffi.MoqCongestionControlUnlimited() } // ParseInstance names an instance with text, failing with ErrInvalidInstance when it is empty. diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt index badf6becf54..c2e33504612 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Aliases.kt @@ -41,8 +41,8 @@ typealias ServerTls = uniffi.moq.MoqServerTls typealias QuicConfig = uniffi.moq.MoqQuicConfig /** - * The congestion control family for a QUIC connection. Build one with `CongestionControl.delay()`, - * `loss()`, or `none()`; a new algorithm joins as a new constructor. + * The congestion control algorithm for a QUIC connection. Build one with `CongestionControl.bbr()`, + * `cubic()`, or `unlimited()`; a new algorithm joins as a new constructor named after it. */ typealias CongestionControl = uniffi.moq.MoqCongestionControl diff --git a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt index e1221825b47..7bc5ce1f24b 100644 --- a/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt +++ b/kt/moq/src/jvmAndAndroidTest/kotlin/dev/moq/SmokeTest.kt @@ -203,7 +203,7 @@ class SmokeTest { assertNotNull(defaults.timeout) assertNull(defaults.quic.congestionControl) assertTrue(versions().isNotEmpty()) - val congestion: CongestionControl = CongestionControl.delay() + val congestion: CongestionControl = CongestionControl.bbr() assertEquals(congestion, QuicConfig(congestionControl = congestion).congestionControl) // Dialing with the reported defaults is the same as dialing with none. Client(defaults).close() diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index d0031a0af79..aa1d7c68a64 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -141,7 +141,7 @@ client = moq.Client( - `fingerprints`. Hex SHA-256 fingerprint(s) to pin the peer's certificate to, the native equivalent of `serverCertificateHashes`. Accepts the values a server reports via `cert_fingerprints()`, so you can trust a self-signed certificate without `insecure=True`. - `cert`, `key`. Paired PEM certificate chain and private key paths for mTLS. - `host_name`. Verify the certificate against this name (SNI) instead of the URL's host. - - `quic=QuicConfig(...)`. QUIC tuning: `max_streams` raises the peer's inbound stream cap; `idle_timeout`, `keep_alive` (`timedelta(0)` uses the default), `gso`, `mtu_discovery`, `congestion_control` (a `CongestionControl`, such as `CongestionControl.delay()`), and `qlog` (a trace directory, which must exist). `keylog=True` writes TLS session secrets to the file `SSLKEYLOGFILE` names, for decrypting a capture; without `SSLKEYLOGFILE` the client refuses to build. + - `quic=QuicConfig(...)`. QUIC tuning: `max_streams` raises the peer's inbound stream cap; `idle_timeout`, `keep_alive` (`timedelta(0)` uses the default), `gso`, `mtu_discovery`, `congestion_control` (a `CongestionControl`: `CongestionControl.bbr()`, `.cubic()`, or `.unlimited()`), and `qlog` (a trace directory, which must exist). `keylog=True` writes TLS session secrets to the file `SSLKEYLOGFILE` names, for decrypting a capture; without `SSLKEYLOGFILE` the client refuses to build. - `websocket=WebSocketConfig(...)`. The fallback raced against QUIC: `enabled=False` turns it off, and `delay` is QUIC's head start. - `once`, `backoff`. Redial with a `Backoff` when the transport drops; `once=True` dials once. - `.session`. The connecting or connected `Session` (or `None` before entering / after exit). diff --git a/py/moq-rs/moq/_records.py b/py/moq-rs/moq/_records.py index 3f62dffd917..36702a24c8f 100644 --- a/py/moq-rs/moq/_records.py +++ b/py/moq-rs/moq/_records.py @@ -412,8 +412,8 @@ class QuicConfig: ``max_streams`` caps the concurrent streams the peer may open toward this endpoint (0 is refused); MoQ opens one per group, so a subscriber to many tracks wants it raised. ``idle_timeout`` is how long an idle connection survives, and ``keep_alive`` - the ping interval (zero uses the default). ``gso``, ``mtu_discovery``, and - ``congestion_control`` leave the choice to the backend when ``None``. ``qlog`` is a + the ping interval (zero uses the default). ``gso`` and ``mtu_discovery`` leave the + choice to the backend when ``None``, and a ``None`` ``congestion_control`` runs BBR v3. ``qlog`` is a directory, which must exist, for qlog traces. ``keylog=True`` writes TLS session secrets to the file ``SSLKEYLOGFILE`` names, for decrypting a capture; without ``SSLKEYLOGFILE`` the client refuses to build. diff --git a/py/moq-rs/tests/test_server.py b/py/moq-rs/tests/test_server.py index 8d2716cb32f..1c79515a072 100644 --- a/py/moq-rs/tests/test_server.py +++ b/py/moq-rs/tests/test_server.py @@ -369,7 +369,7 @@ async def accept_loop() -> None: keep_alive=timedelta(0), gso=False, mtu_discovery=True, - congestion_control=moq.CongestionControl.loss(), + congestion_control=moq.CongestionControl.cubic(), keylog=False, ), websocket=moq.WebSocketConfig(enabled=False), diff --git a/quest/m2/README.md b/quest/m2/README.md index 0f156eb979f..dd3be0e23e3 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -40,7 +40,6 @@ removal, a rename, or a wire, catalog, or format change that is free until demos return to their earlier format. - **Unused API.** [One sweep per area](/quest/m2/unused-api/README.md), each item re-checked for a downstream caller first. -- **Relay and transports.** [Congestion names](/quest/m2/congestion-names.md). - **Auth and crypto.** End-to-end encryption is its own unpublished crate again ([moq-dev/moq#8947](https://github.com/moq-dev/moq/pull/8947)); its [finished format](/quest/m3/e2ee-format.md) follows in m3. diff --git a/quest/m2/congestion-names.md b/quest/m2/congestion-names.md deleted file mode 100644 index 2d74ce1b7d5..00000000000 --- a/quest/m2/congestion-names.md +++ /dev/null @@ -1,85 +0,0 @@ -# [M] Congestion control is chosen by algorithm name, from one enum - -## Goal - -A QUIC endpoint picks its congestion controller by the algorithm's name: -`bbr` (the default), `cubic`, or `unlimited`, in `quic.congestion_control`, -its flag and environment variable, the Rust API, and every binding. One enum -in moq-tokio says so, both runtimes build their controller from it, and no -application can install a controller of its own. - -## Plan - -Decided 2026-11-16 (maintainer, /quest-plan of the pre-cut audit): - -- ✅ One enum of algorithm names, no families (rejected: the family names - `loss`, `delay`, `none` kept; algorithm names beside goal names such as - `real-time`, which the maintainer raised and then dropped: "just do - algorithms no families"). A family name stops meaning one thing once two - delay-based algorithms exist, and the enum's own doc already promises "a - new algorithm joins as a variant named after it". -- ✅ Delete the moq-uring duplicate and `quic::Config::controller` (rejected: - keeping the application hook). The hook publishes - `moq_congestion::Controller` as a plugin interface while that trait is - still moving. - -Facts found by the audit: - -- `moq_tokio::quic::CongestionControl { Loss, Delay, None }` - (`rs/moq-tokio/src/quic.rs:97`) and `moq_uring::quic::Congestion { Loss, - Delay, None }` (`rs/moq-uring/src/quic/mod.rs:50`) are the same enum, each - with its own mapping to a factory (`rs/moq-tokio/src/quic/backend.rs:29`, - `rs/moq-uring/src/quic/mod.rs:62`). moq-relay maps one onto the other - variant by variant (`rs/moq-relay/src/uring.rs:507-514`), so a new - algorithm is three edits. -- `quic::Controller` and `quic::Config::controller` - (`rs/moq-tokio/src/quic.rs:80`, `:248`, `:668`) are set only by moq-tokio's - own unit tests (`rs/moq-tokio/src/quic/backend.rs:1377`, `:1411`): - `grep -rn 'controller:' rs` outside moq-quic and moq-congestion finds - nothing else, and no binding, doc, or downstream quest names it. - `Controller` gained `on_loss` before `on_ack` on 2026-11-15 - ([moq-dev/moq#8807](https://github.com/moq-dev/moq/pull/8807)). -- The field is `Option`, so `None` is "the default, BBR" - and `Some(None)` is "no congestion control". moq-congestion calls the - second `Unlimited`. -- GCC and SCReAM sit behind moq-congestion's `lab` feature for the - [realtime bake-off](/quest/m4/quic-realtime.md). Both are delay-based, so - the family names cannot name the bake-off's winner. -- moq-ffi already changed the selector's shape in every binding in - [moq-dev/moq#8850](https://github.com/moq-dev/moq/pull/8850) - (`MoqCongestionControl`, `rs/moq-ffi/src/session.rs:148`), so the bindings - take new names at no extra break. -- `loss`, `delay`, and `none` are published: `release` has both enums. - -For the PR: - -- Name the variants `Bbr`, `Cubic`, `Unlimited`, spelled `bbr`, `cubic`, - `unlimited`. Keep the enum `#[non_exhaustive]`. The default stays BBR v3, - and "which BBR" lives in the variant's doc, not its name. -- moq-uring takes the moq-tokio enum or, since its `transport::Config` - already takes a factory, no enum at all; the relay's variant-by-variant - match and its `bail!` for an unknown family go. -- Recommended, the maintainer did not pick: `loss`, `delay`, and `none` are - refused at startup with a message naming `cubic`, `bbr`, and `unlimited`, - as other removed settings are (`moq_tokio::cli::Deprecated`), rather than - accepted as aliases. A silent alias keeps the family names alive in every - deployed config. -- Rename the moq-ffi constructors and every wrapper to match (Swift, Kotlin, - Dart, Python, Go, C, C++), and their `MIGRATE.md` notes. `@moq/net` has no - QUIC stack to configure: it passes the browser's own `congestionControl` - hint (`js/net/src/connection/connect.ts:836`), which is unchanged. -- Update `doc/bin/relay/config.md` (`congestion_control = "delay"` at line - 119, and the `none` paragraph), the CLI docs, and `rs/moq-tokio/MIGRATE.md`. -- Tests: each spelling parses from TOML, flag, and environment; each old - spelling refuses naming its replacement; an io_uring relay and a tokio relay - given `cubic` both run CUBIC. - -Public API: breaking for `moq_tokio::quic` (`CongestionControl` variants, -`Config::controller` and `Controller` removed), `moq_uring::quic` -(`Congestion` removed), and the moq-ffi selector in every binding. Config -and CLI: `quic.congestion_control` takes `bbr`, `cubic`, `unlimited`. Wire: -none. - -## Related - -- [Realtime uplink congestion control](/quest/m4/quic-realtime.md) - its winner joins this enum under its own name diff --git a/quest/m4/quic-realtime.md b/quest/m4/quic-realtime.md index 454bbb8eb5d..33c9e25bc09 100644 --- a/quest/m4/quic-realtime.md +++ b/quest/m4/quic-realtime.md @@ -65,9 +65,9 @@ spike assumed no consumer; teleoperation uplinks are one): - Naming (revised 2026-11-14, below): each winner joins `moq_tokio::quic::CongestionControl` as a variant named after its algorithm (`gcc`, `scream` on the CLI and in TOML), which is `non_exhaustive`, so it is - additive, as is a new moq-ffi `MoqCongestionControl` constructor. `Delay` - keeps meaning BBR3, documented as model-based BBR v3. A new variant rather - than upgrading `Delay`, so current users see no behavior change. + additive, as is a new moq-ffi `MoqCongestionControl` constructor. `Bbr` + keeps meaning BBR v3. A new variant rather than upgrading `Bbr`, so current + users see no behavior change. - Docs: inline only. The congestion-control lines in `doc/bin/cli.md` and `doc/lib/*` gain the new variant; no new page. - SCReAMv2 landed as `moq_congestion::scream::Scream` @@ -98,7 +98,7 @@ Collapse evidence for the comparison (maintainer, ✅ 2026-11-05, on response time bounds its reported estimate; the loss-bound estimate and Startup/recovery ordering fixes complete that quest. The lossless bufferbloat case belongs in this comparison rather than a new estimator or enabling the -delay bound on `CongestionControl::Delay` before the bake-off: +delay bound on `CongestionControl::Bbr` before the bake-off: - Real sockets, `just rs rung-disable`, FFI ladder over moq-shaper's `cellular-step` (2 → 0.5 → 0.1 → 2 Mbit/s at 8 / 20 / 32 s): the diff --git a/rs/moq-c/src/api.rs b/rs/moq-c/src/api.rs index 356e7066ce2..71b84a39c28 100644 --- a/rs/moq-c/src/api.rs +++ b/rs/moq-c/src/api.rs @@ -1619,7 +1619,7 @@ pub struct moq_client_config { /// Whether `quic_mtu_discovery` is present. pub has_quic_mtu_discovery: bool, - /// Congestion control family name (`loss` for CUBIC, `delay` for BBR v3, or `none`), or NULL for the backend's choice. + /// Congestion control algorithm name (`bbr`, `cubic`, or `unlimited`), or NULL for the default, BBR v3. pub quic_congestion_control: *const c_char, /// The length in bytes of `quic_congestion_control`. pub quic_congestion_control_len: usize, diff --git a/rs/moq-c/src/client.rs b/rs/moq-c/src/client.rs index 1fc154e7b1d..9179a0206b3 100644 --- a/rs/moq-c/src/client.rs +++ b/rs/moq-c/src/client.rs @@ -44,9 +44,9 @@ impl Quic<'_> { quic.keep_alive = self.keep_alive_us.map(micros); quic.gso = self.gso; quic.mtu_discovery = self.mtu_discovery; - if let Some(family) = self.congestion_control { + if let Some(algorithm) = self.congestion_control { quic.congestion_control = - Some(moq_tokio::quic::CongestionControl::from_str(family).map_err(Error::InvalidConfig)?); + Some(moq_tokio::quic::CongestionControl::from_str(algorithm).map_err(Error::InvalidConfig)?); } quic.qlog = self.qlog.map(Into::into); quic.keylog = self diff --git a/rs/moq-c/src/test.rs b/rs/moq-c/src/test.rs index cfd2380ebba..11c47d145f3 100644 --- a/rs/moq-c/src/test.rs +++ b/rs/moq-c/src/test.rs @@ -7904,11 +7904,21 @@ fn config_rejects_unknown_congestion_control() { config.quic_congestion_control_len = bogus.len(); assert_eq!(dial(Some(&config)), Error::InvalidConfig(String::new()).code()); + // A released family name is refused like any unknown word. let delay = "delay"; let mut config = client_config(); config.quic_congestion_control = delay.as_ptr() as *const c_char; config.quic_congestion_control_len = delay.len(); - assert!(parsed(&config).quic.congestion_control.is_some()); + assert_eq!(dial(Some(&config)), Error::InvalidConfig(String::new()).code()); + + let cubic = "cubic"; + let mut config = client_config(); + config.quic_congestion_control = cubic.as_ptr() as *const c_char; + config.quic_congestion_control_len = cubic.len(); + assert_eq!( + parsed(&config).quic.congestion_control, + Some(moq_tokio::quic::CongestionControl::Cubic) + ); // NULL leaves it on the backend default, so the knob can stay automatic. assert!(parsed(&client_config()).quic.congestion_control.is_none()); diff --git a/rs/moq-congestion/README.md b/rs/moq-congestion/README.md index 93dbe2be474..13ca6376351 100644 --- a/rs/moq-congestion/README.md +++ b/rs/moq-congestion/README.md @@ -1,6 +1,6 @@ # moq-congestion -BBR3, Cubic, and Unlimited congestion controllers, consumed by moq-quic and the native transport drivers. Applications pick one through `moq_tokio::quic::CongestionControl`, where `delay` is BBR3 and the default. +BBR3, Cubic, and Unlimited congestion controllers, consumed by moq-quic and the native transport drivers. Applications pick one through `moq_tokio::quic::CongestionControl`, by algorithm name: `bbr` (BBR3, the default), `cubic`, or `unlimited`. Candidates still under test compile only with the `lab` test-support feature, which the comparisons in moq-quic and moq-tokio enable as a dev-dependency: the `gcc` and `scream` modules, and BBR3's delay bound (`bbr3::Config::delay_bound`), which brakes when the peer's receive timestamps show the bottleneck queue growing. A winner joins `CongestionControl` as a new variant, or BBR3 as an option, and leaves the feature. diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 669a1e27638..91df5e9e37a 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -106,7 +106,7 @@ pub struct MoqClientTls { /// QUIC transport tuning, mirroring moq-tokio's QUIC config. Ignored by the WebSocket fallback. /// /// Null fields use the library default, which [`moq_client_defaults`] reports where there is -/// one; `gso`, `mtu_discovery`, and `congestion_control` leave the choice to the backend. +/// one; `gso` and `mtu_discovery` leave the choice to the backend. #[derive(Clone, Debug, Default, PartialEq, Eq, uniffi::Record)] pub struct MoqQuicConfig { /// Cap on the concurrent QUIC streams the peer may open toward this endpoint; 0 is refused. @@ -127,7 +127,7 @@ pub struct MoqQuicConfig { /// Path MTU discovery: probes for the largest packet size the path allows. #[uniffi(default = None)] pub mtu_discovery: Option, - /// The congestion control family. + /// The congestion control algorithm, BBR v3 when null. #[uniffi(default = None)] pub congestion_control: Option>, /// Directory, which must exist, to write qlog traces into. @@ -139,7 +139,7 @@ pub struct MoqQuicConfig { pub keylog: Option, } -/// The congestion control family for a QUIC connection. +/// The congestion control algorithm for a QUIC connection. /// /// An immutable object rather than an enum, so a new algorithm joins as a constructor without /// breaking callers that switch over a closed enum. @@ -149,23 +149,23 @@ pub struct MoqCongestionControl(moq_tokio::quic::CongestionControl); #[uniffi::export] impl MoqCongestionControl { - /// Loss-based (CUBIC): chases throughput, so the send rate sawtooths. + /// BBR v3, the default: keeps queues short and the send rate steady enough for an encoder + /// to track. #[uniffi::constructor] - pub fn loss() -> Arc { - Arc::new(Self(moq_tokio::quic::CongestionControl::Loss)) + pub fn bbr() -> Arc { + Arc::new(Self(moq_tokio::quic::CongestionControl::Bbr)) } - /// Delay-based (BBR v3), the default: keeps queues short and the send rate steady enough for - /// an encoder to track. + /// CUBIC: chases throughput, so the send rate sawtooths. #[uniffi::constructor] - pub fn delay() -> Arc { - Arc::new(Self(moq_tokio::quic::CongestionControl::Delay)) + pub fn cubic() -> Arc { + Arc::new(Self(moq_tokio::quic::CongestionControl::Cubic)) } /// No congestion control and no pacing, for tests and controlled links. #[uniffi::constructor] - pub fn none() -> Arc { - Arc::new(Self(moq_tokio::quic::CongestionControl::None)) + pub fn unlimited() -> Arc { + Arc::new(Self(moq_tokio::quic::CongestionControl::Unlimited)) } } @@ -177,7 +177,7 @@ impl From for moq_tokio::quic::Config { quic.keep_alive = config.keep_alive.map(Into::into); quic.gso = config.gso; quic.mtu_discovery = config.mtu_discovery; - quic.congestion_control = config.congestion_control.map(|family| family.0); + quic.congestion_control = config.congestion_control.map(|algorithm| algorithm.0); quic.qlog = config.qlog.map(Into::into); quic.keylog = config .keylog diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index 5f0bcbbb2b6..e08419e3a30 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -7204,7 +7204,7 @@ async fn client_connects_with_every_knob_set() { keep_alive: Some(Duration::ZERO), gso: Some(false), mtu_discovery: Some(true), - congestion_control: Some(MoqCongestionControl::loss()), + congestion_control: Some(MoqCongestionControl::cubic()), qlog: None, keylog: Some(false), }, diff --git a/rs/moq-ffi/src/test/rung.rs b/rs/moq-ffi/src/test/rung.rs index 1146b41754d..c021c70a45f 100644 --- a/rs/moq-ffi/src/test/rung.rs +++ b/rs/moq-ffi/src/test/rung.rs @@ -46,7 +46,7 @@ async fn shaped_uplink_disables_and_resumes() { tls: insecure_tls(), once: true, quic: MoqQuicConfig { - congestion_control: Some(MoqCongestionControl::delay()), + congestion_control: Some(MoqCongestionControl::bbr()), ..Default::default() }, websocket: MoqWebSocketConfig { diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index b932c62d7a5..5a9b10fe877 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -685,6 +685,39 @@ mod tests { assert_eq!(config.quic.max_streams, Some(crate::DEFAULT_MAX_STREAMS)); } + /// The environment picks the congestion controller by algorithm name. + #[test] + fn congestion_control_from_the_environment() { + if !test_env::Env::default() + .set("MOQ_QUIC_CONGESTION_CONTROL", "unlimited") + .isolate() + { + return; + } + let config = Config::parse_and_merge(["moq-relay"]).unwrap(); + assert_eq!( + config.quic.congestion_control, + Some(moq_tokio::quic::CongestionControl::Unlimited) + ); + } + + /// A released family name in a file stops the relay, naming the algorithms. + #[test] + fn congestion_family_in_a_file_refuses_to_boot() { + if !test_env::Env::without(&["MOQ_QUIC_CONGESTION_CONTROL"]).isolate() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("relay.toml"); + std::fs::write(&path, "[quic]\ncongestion_control = \"delay\"\n").unwrap(); + let err = + Config::parse_and_merge(["moq-relay", path.to_str().unwrap()]).expect_err("a family name must not boot"); + let err = format!("{err:#}"); + for name in ["bbr", "cubic", "unlimited"] { + assert!(err.contains(name), "{err}"); + } + } + /// A released `--server-*` spelling stops the relay and names its replacement. /// /// Booting anyway is the failure this replaced: those flags land on hidden @@ -1540,13 +1573,13 @@ ws = false }, Case { name: "enum-from-file", - toml: "[quic]\ncongestion_control = \"delay\"\n", + toml: "[quic]\ncongestion_control = \"cubic\"\n", cli: &[], key: "quic.congestion_control", check: |config| { assert_eq!( config.quic.congestion_control, - Some(moq_tokio::quic::CongestionControl::Delay) + Some(moq_tokio::quic::CongestionControl::Cubic) ) }, source: "congestion_control", diff --git a/rs/moq-relay/src/uring.rs b/rs/moq-relay/src/uring.rs index 1d722577dd8..052371b6278 100644 --- a/rs/moq-relay/src/uring.rs +++ b/rs/moq-relay/src/uring.rs @@ -502,18 +502,7 @@ fn transport(quic: &moq_tokio::quic::Resolved) -> anyhow::Result controller.0.clone(), - (None, Some(moq_tokio::quic::CongestionControl::Loss)) => moq_uring::quic::Congestion::Loss.into(), - // Unset means the backend's own default, and live media wants a steady - // send rate an encoder can track over CUBIC's sawtooth. - (None, Some(moq_tokio::quic::CongestionControl::Delay) | None) => moq_uring::quic::Congestion::Delay.into(), - (None, Some(moq_tokio::quic::CongestionControl::None)) => moq_uring::quic::Congestion::None.into(), - // A family added to the tokio stack later, rather than a silent - // substitution the operator would never learn about. - (None, Some(other)) => anyhow::bail!("io_uring workers cannot run the {other:?} congestion controller"), - }; + transport.congestion = quic.congestion_control.into(); Ok(transport) } diff --git a/rs/moq-relay/tests/integration/runtime_uring.rs b/rs/moq-relay/tests/integration/runtime_uring.rs index 75a9f15d81a..7088f0fae1d 100644 --- a/rs/moq-relay/tests/integration/runtime_uring.rs +++ b/rs/moq-relay/tests/integration/runtime_uring.rs @@ -752,24 +752,16 @@ async fn an_mtls_client_authenticates_without_a_token() { let _ = running.await; } -/// `quic.qlog` captures traces from the io_uring workers, the same as it does -/// from the tokio ones. -/// -/// A real session keeps both trace writers active through worker shutdown, so -/// the test covers capture on the io_uring data path and the final flush. -#[tokio::test] -async fn uring_workers_write_qlog_traces() { - let _ = rind_rustls::default_provider().unwrap().install_default(); - if !supported() { - return; - } - +/// Runs one real session through io_uring workers running `congestion` and returns +/// every qlog record they wrote, each checked to be JSON on a line of its own. +async fn traced_session(congestion: Option) -> Vec { let dir = tempfile::tempdir().expect("tempdir"); let (cert, key) = certificate(dir.path()); let traces = dir.path().join("qlog"); std::fs::create_dir(&traces).expect("create qlog dir"); let mut config = uring_config(&cert, &key); config.quic.qlog = Some(traces.clone()); + config.quic.congestion_control = congestion; let relay = Relay::load(config).await.expect("load relay").with_signals(false); let port = relay.addr().expect("workers bound an address").port(); let ready = relay.ready(); @@ -834,6 +826,7 @@ async fn uring_workers_write_qlog_traces() { // Every record has to be JSON on a line of its own, or the trace is not // something a qlog reader can open. + let mut parsed = Vec::new(); for path in written { let raw = std::fs::read_to_string(&path).expect("read trace"); let records: Vec<&str> = raw @@ -843,10 +836,51 @@ async fn uring_workers_write_qlog_traces() { .collect(); assert!(!records.is_empty(), "{} holds no records", path.display()); for record in records { - serde_json::from_str::(record) - .unwrap_or_else(|err| panic!("{}: {err}: {record}", path.display())); + parsed.push( + serde_json::from_str::(record) + .unwrap_or_else(|err| panic!("{}: {err}: {record}", path.display())), + ); } } + parsed +} + +/// `quic.qlog` captures traces from the io_uring workers, the same as it does +/// from the tokio ones. +/// +/// A real session keeps both trace writers active through worker shutdown, so +/// the test covers capture on the io_uring data path and the final flush. +#[tokio::test] +async fn uring_workers_write_qlog_traces() { + let _ = rind_rustls::default_provider().unwrap().install_default(); + if !supported() { + return; + } + traced_session(None).await; +} + +/// Whether any recovery metrics update in `records` reports `field`. +fn reports(records: &[serde_json::Value], field: &str) -> bool { + records.iter().any(|record| record["data"].get(field).is_some()) +} + +/// The workers run the algorithm `[quic]` names, read back from the trace: CUBIC +/// reports a slow-start threshold and no pacing rate, BBR v3 the reverse. +#[tokio::test] +async fn uring_workers_run_the_configured_congestion_control() { + let _ = rind_rustls::default_provider().unwrap().install_default(); + if !supported() { + return; + } + + let cubic = traced_session(Some(moq_tokio::quic::CongestionControl::Cubic)).await; + assert!(reports(&cubic, "ssthresh"), "cubic reported no ssthresh"); + assert!(!reports(&cubic, "pacing_rate"), "cubic reported a pacing rate"); + + // Unset is BBR v3. + let bbr = traced_session(None).await; + assert!(reports(&bbr, "pacing_rate"), "bbr reported no pacing rate"); + assert!(!reports(&bbr, "ssthresh"), "bbr reported an ssthresh"); } /// A session the workers refuse reaches `/metrics` like one the shared runtime @@ -1114,7 +1148,7 @@ fn uring_workers_bound_stalled_handshakes() { let (cert, key) = certificate(dir.path()); let mut config = uring_config(&cert, &key); config.listen.timeout = Some(LISTEN.into()); - config.quic.congestion_control = Some(moq_tokio::quic::CongestionControl::None); + config.quic.congestion_control = Some(moq_tokio::quic::CongestionControl::Unlimited); let relay = Relay::load(config).await.expect("load relay").with_signals(false); let port = relay.addr().expect("workers bound an address").port(); let addr = SocketAddr::from(([127, 0, 0, 1], port)); diff --git a/rs/moq-tokio/src/quic.rs b/rs/moq-tokio/src/quic.rs index 56f00aeedd8..1c06ea06f2a 100644 --- a/rs/moq-tokio/src/quic.rs +++ b/rs/moq-tokio/src/quic.rs @@ -89,46 +89,46 @@ pub(crate) struct Forward { pub peers: PathBuf, } -/// A congestion controller of the application's own, built fresh for each connection. +/// The congestion control algorithm for a QUIC connection. /// -/// Implement [`moq_congestion::Factory`] and install it with [`Config::controller`]. -#[derive(Clone)] -pub struct Controller(pub std::sync::Arc); - -impl std::fmt::Debug for Controller { - /// Opaque: a factory carries no description of its own. - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("Controller(..)") - } -} - -/// The congestion control family for a QUIC connection. -/// -/// CUBIC is used for loss-based control and BBR v3 for delay-based control, the default. A new -/// algorithm joins as a variant named after it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, usage_rs::ValueEnum, serde::Serialize, serde::Deserialize)] +/// A new algorithm joins as a variant named after it. +#[derive( + Clone, Copy, Debug, Default, PartialEq, Eq, Hash, usage_rs::ValueEnum, serde::Serialize, serde::Deserialize, +)] #[usage(ignore_case)] #[serde(rename_all = "kebab-case")] #[non_exhaustive] pub enum CongestionControl { - /// Loss-based (CUBIC): grows until it drops packets, so the send rate sawtooths. - /// Throughput-oriented, and the default on most stacks. - Loss, - /// Delay-based (BBR v3): tracks the measured delivery rate and RTT instead of waiting + /// BBR v3, the default: tracks the measured delivery rate and RTT instead of waiting /// for loss, which keeps queues short and the send rate steady enough for an encoder /// to track. - Delay, + #[default] + Bbr, + /// CUBIC: grows until it drops packets, so the send rate sawtooths. + /// Throughput-oriented, and the default on most stacks. + Cubic, /// No congestion control and no pacing, for tests and controlled links. - None, + Unlimited, } -/// Parses the same spellings the CLI and TOML accept (`loss`, `delay`, `none`), case-insensitively. +/// Parses the same spellings the CLI and TOML accept (`bbr`, `cubic`, `unlimited`), case-insensitively. impl std::str::FromStr for CongestionControl { type Err = String; fn from_str(s: &str) -> std::result::Result { ::from_choice(s) - .ok_or_else(|| format!("unknown congestion control: {s}")) + .ok_or_else(|| format!("unknown congestion control: {s} (expected bbr, cubic, or unlimited)")) + } +} + +/// The controller factory a QUIC transport config holds, so every runtime builds the same one. +impl From for std::sync::Arc { + fn from(algorithm: CongestionControl) -> Self { + match algorithm { + CongestionControl::Bbr => std::sync::Arc::new(moq_congestion::bbr3::Config::default()), + CongestionControl::Cubic => std::sync::Arc::new(moq_congestion::cubic::Config::default()), + CongestionControl::Unlimited => std::sync::Arc::new(moq_congestion::Unlimited), + } } } @@ -243,7 +243,7 @@ pub struct Config { )] pub mtu_discovery: Option, - /// Congestion control family. Defaults to `delay`, which uses BBRv3. + /// Congestion control algorithm: `bbr` (BBR v3, the default), `cubic`, or `unlimited`. #[serde(skip_serializing_if = "Option::is_none")] #[usage( name = "quic-congestion-control", @@ -254,15 +254,6 @@ pub struct Config { )] pub congestion_control: Option, - /// A congestion controller of your own for every connection, in place of - /// [`congestion_control`](Self::congestion_control)'s families. - /// - /// Code-only, since a controller has no text form: no flag or setting reaches it. - /// Both the QUIC backend and the relay's io_uring runtime run it. - #[serde(skip)] - #[usage(skip)] - pub controller: Option, - /// Connection-wide receive window, in bytes: how much data the peer may have /// in flight or in incomplete messages across every stream at once. Defaults to /// 4 MiB, and must fit the largest unit a session assembles, one 1 MiB segment. @@ -442,19 +433,17 @@ pub(crate) struct Legacy { name = "client-quic-congestion-control", long = "client-quic-congestion-control", env = "MOQ_CLIENT_QUIC_CONGESTION_CONTROL", - value_enum, hide = true )] - client_congestion_control: Option, + client_congestion_control: Option, #[usage( name = "server-quic-congestion-control", long = "server-quic-congestion-control", env = "MOQ_SERVER_QUIC_CONGESTION_CONTROL", - value_enum, hide = true )] - server_congestion_control: Option, + server_congestion_control: Option, #[usage( name = "client-quic-qlog", @@ -636,8 +625,7 @@ impl Config { idle_timeout, keep_alive, mtu_discovery: self.mtu_discovery.unwrap_or(false), - congestion_control: self.congestion_control, - controller: self.controller.clone(), + congestion_control: self.congestion_control.unwrap_or_default(), receive_window: self.receive_window.unwrap_or(DEFAULT_RECEIVE_WINDOW), stream_receive_window: self.stream_receive_window.unwrap_or(DEFAULT_STREAM_RECEIVE_WINDOW), send_window: self.send_window.unwrap_or(DEFAULT_SEND_WINDOW), @@ -678,10 +666,8 @@ pub struct Resolved { pub keep_alive: Option, /// Whether to run path MTU discovery. pub mtu_discovery: bool, - /// Congestion control override, or `None` for the default. - pub congestion_control: Option, - /// The application's own congestion controller, in place of the family. - pub controller: Option, + /// Congestion control algorithm, defaulting to [`CongestionControl::Bbr`]. + pub congestion_control: CongestionControl, /// Connection-wide receive window in bytes, defaulting to [`DEFAULT_RECEIVE_WINDOW`]. /// /// The windows are resolved here rather than by each backend, whose own defaults @@ -699,15 +685,6 @@ pub struct Resolved { } impl Resolved { - /// The congestion control family to install. - /// - /// Delay-based unless the operator says otherwise: BBR keeps queues short and the - /// send rate steady enough for a live encoder to track, which is what this stack - /// carries. - pub(crate) fn congestion(&self) -> CongestionControl { - self.congestion_control.unwrap_or(CongestionControl::Delay) - } - /// The directory to write qlog traces into, if any. pub(crate) fn qlog_dir(&self) -> Option<&std::path::Path> { self.qlog.as_deref() @@ -762,6 +739,16 @@ mod tests { Cli::try_parse_from(&argv).expect("valid test arguments").quic } + /// The parse error rendered as the process would print it. + fn try_parse(args: &[&str]) -> Result { + let mut argv = vec![std::ffi::OsString::from("test")]; + argv.extend(args.iter().map(std::ffi::OsString::from)); + let argv: Vec<_> = argv.iter().map(std::ffi::OsString::as_os_str).collect(); + Cli::try_parse_from(&argv) + .map(|cli| cli.quic) + .map_err(|err| usage_rs::render_failure(Cli::spec(), &argv, &err)) + } + #[test] fn defaults_apply_when_unset() { assert!(Config::default().idle_timeout.is_none()); @@ -802,7 +789,7 @@ mod tests { "5000", "--quic-gso=false", "--quic-congestion-control", - "delay", + "cubic", "--quic-qlog", "/tmp/qlog", "--quic-keylog", @@ -810,19 +797,49 @@ mod tests { ]); assert_eq!(quic.max_streams, Some(5000)); assert_eq!(quic.gso, Some(false)); - assert_eq!(quic.congestion_control, Some(CongestionControl::Delay)); + assert_eq!(quic.congestion_control, Some(CongestionControl::Cubic)); assert_eq!(quic.qlog.as_deref(), Some(std::path::Path::new("/tmp/qlog"))); assert_eq!(quic.keylog.as_deref(), Some(std::path::Path::new("/tmp/keys.log"))); } - /// `none` is spelled the same on the CLI, in TOML, and through `FromStr`. + /// Each algorithm is spelled the same on the CLI, in TOML, and through `FromStr`, + /// and unset resolves to BBR. #[test] - fn congestion_control_none_parses() { - let quic = parse(&["--quic-congestion-control", "none"]); - assert_eq!(quic.congestion_control, Some(CongestionControl::None)); - let quic: Config = toml::from_str(r#"congestion_control = "none""#).expect("parse"); - assert_eq!(quic.congestion_control, Some(CongestionControl::None)); - assert_eq!("NONE".parse(), Ok(CongestionControl::None)); + fn congestion_control_parses_by_algorithm_name() { + for (word, algorithm) in [ + ("bbr", CongestionControl::Bbr), + ("cubic", CongestionControl::Cubic), + ("unlimited", CongestionControl::Unlimited), + ] { + let quic = parse(&["--quic-congestion-control", word]); + assert_eq!(quic.congestion_control, Some(algorithm)); + let quic: Config = toml::from_str(&format!("congestion_control = \"{word}\"")).expect("parse"); + assert_eq!(quic.congestion_control, Some(algorithm)); + assert_eq!(word.to_uppercase().parse(), Ok(algorithm)); + } + assert_eq!(Resolved::default().congestion_control, CongestionControl::Bbr); + } + + /// The released family names are refused rather than aliased, with an error that + /// names every algorithm, so a deployed config learns the new spelling. + #[test] + fn congestion_control_family_names_are_refused() { + for family in ["loss", "delay", "none"] { + let err = try_parse(&["--quic-congestion-control", family]).expect_err(family); + for name in ["bbr", "cubic", "unlimited"] { + assert!(err.contains(name), "{family}: {err}"); + } + let err = toml::from_str::(&format!("congestion_control = \"{family}\"")) + .expect_err(family) + .to_string(); + for name in ["bbr", "cubic", "unlimited"] { + assert!(err.contains(name), "{family}: {err}"); + } + let err = family.parse::().expect_err(family); + for name in ["bbr", "cubic", "unlimited"] { + assert!(err.contains(name), "{family}: {err}"); + } + } } /// Every old role-prefixed spelling parses into a hidden field and is reported, diff --git a/rs/moq-tokio/src/quic/backend.rs b/rs/moq-tokio/src/quic/backend.rs index 9b8fa3a4b9d..19e0fe483bb 100644 --- a/rs/moq-tokio/src/quic/backend.rs +++ b/rs/moq-tokio/src/quic/backend.rs @@ -4,7 +4,6 @@ use super::{driver, web}; use crate::RedactedUrl; use crate::connect; use crate::listen; -use crate::quic::CongestionControl; use crate::quic::Resolved; use crate::quic::ServerId; use crate::tls::FingerprintVerifier; @@ -26,10 +25,7 @@ fn transport(quic: &Resolved, role: &str) -> Result { if let Some(gso) = quic.gso { transport.segmentation_offload = gso; } - transport.congestion = match &quic.controller { - Some(controller) => controller.0.clone(), - None => congestion_factory(quic.congestion()), - }; + transport.congestion = quic.congestion_control.into(); transport.validate()?; apply_qlog(&mut transport, quic, role)?; Ok(transport) @@ -64,15 +60,6 @@ fn apply_qlog(transport: &mut driver::transport::Config, quic: &Resolved, role: Ok(()) } -/// The controller factory for a congestion control family. moq-quic's BBR is v3. -fn congestion_factory(family: CongestionControl) -> Arc { - match family { - CongestionControl::Loss => Arc::new(moq_congestion::cubic::Config::default()), - CongestionControl::Delay => Arc::new(moq_congestion::bbr3::Config::default()), - CongestionControl::None => Arc::new(moq_congestion::Unlimited), - } -} - /// Errors specific to the QUIC backend. #[derive(Debug, thiserror::Error)] #[non_exhaustive] @@ -1254,33 +1241,45 @@ mod tests { assert_eq!(limits.send_window.unwrap().get(), crate::quic::DEFAULT_SEND_WINDOW); } - /// Each family supplies its advertised congestion behavior. + /// Each algorithm builds the controller it is named after. #[test] - fn congestion_factory_maps_each_family() { + fn each_algorithm_builds_its_controller() { + use crate::quic::CongestionControl; + let init = moq_congestion::Init { now: kio::clock::Instant::now(), mtu: 1200, rtt: std::time::Duration::from_millis(333), seed: 0, }; + let build = |algorithm: CongestionControl| { + let factory: Arc = algorithm.into(); + factory.build(init) + }; - let loss = congestion_factory(CongestionControl::Loss).build(init); - assert!(loss.metrics().ssthresh.is_some()); - assert!(!loss.probes()); + let cubic = build(CongestionControl::Cubic); + assert!(cubic.metrics().ssthresh.is_some()); + assert!(!cubic.probes()); - let delay = congestion_factory(CongestionControl::Delay).build(init); - assert!(delay.probes()); - assert!(delay.metrics().pacing_rate.is_some()); + let bbr = build(CongestionControl::Bbr); + assert!(bbr.probes()); + assert!(bbr.metrics().pacing_rate.is_some()); - let none = congestion_factory(CongestionControl::None).build(init); - assert_eq!(none.window(), u64::MAX); - assert!(!none.probes()); + let unlimited = build(CongestionControl::Unlimited); + assert_eq!(unlimited.window(), u64::MAX); + assert!(!unlimited.probes()); } - /// Loopback regression test: with the knob unset, live QUIC connections must run - /// BBRv3 on both ends. - #[tokio::test] - async fn default_reaches_the_live_connection() { + /// Each end's controller on a live loopback connection, and whether the client's offers + /// moq-net a probe target. + struct Live { + client: Box, + server: Box, + probe: bool, + } + + /// Dials a loopback server with `quic` on both ends. + async fn live(quic: crate::quic::Config) -> Live { let server_config = listen::Config { bind: Some("127.0.0.1:0".parse().unwrap()), tls: crate::tls::Listen { @@ -1290,9 +1289,6 @@ mod tests { ..Default::default() }; - // The knob left unset, the way a binary that never mentions it runs. - let quic = crate::quic::Config::default(); - let tls = server_config.tls.load().unwrap(); let server = Server::new(Options { config: server_config, @@ -1309,7 +1305,7 @@ mod tests { let accepted = tokio::spawn(async move { let incoming = server.accept().await.expect("no incoming connection"); let conn = incoming.accept().expect("accept").await.expect("handshake"); - conn.congestion_state().probes() + conn.congestion_state() }); // tls::Connect has a private field, so it can't be built with a struct literal. @@ -1327,123 +1323,49 @@ mod tests { // Dial the loopback IP directly so the system resolver is never involved. let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap(); - // Bound the whole connect + accept + assert flow so a handshake - // regression fails fast instead of stalling CI. + // Bound the whole connect + accept flow so a handshake regression fails fast + // instead of stalling CI. kio::clock::timeout(Duration::from_secs(5), async move { let session = client .connect(&tls, url.into(), &moq_net::Versions::default()) .await .expect("connect failed"); - - // Inspect the driver through the explicit connection accessor. - assert!( - session.connection().congestion_state().probes(), - "client controller cannot probe" - ); - // BBRv3 can probe, so moq-net gets a target to write. - assert!( - session.connection().probe().is_some(), - "BBRv3 connection has no probe target" - ); - assert!( - accepted.await.expect("server task panicked"), - "server controller cannot probe" - ); + Live { + client: session.connection().congestion_state(), + probe: session.connection().probe().is_some(), + server: accepted.await.expect("server task panicked"), + } }) .await - .expect("test timed out"); + .expect("test timed out") } - /// A factory that counts the controllers it builds, each a BBRv3. - #[derive(Default)] - struct Counted(std::sync::atomic::AtomicUsize); - - impl moq_congestion::Factory for Counted { - fn build(self: Arc, init: moq_congestion::Init) -> Box { - self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); - Arc::new(moq_congestion::bbr3::Config::default()).build(init) - } + /// Loopback regression test: with the knob unset, live QUIC connections must run + /// BBRv3 on both ends, which can probe. + #[tokio::test] + async fn default_reaches_the_live_connection() { + // The knob left unset, the way a binary that never mentions it runs. + let live = live(crate::quic::Config::default()).await; + assert!(live.client.probes(), "client controller cannot probe"); + assert!(live.server.probes(), "server controller cannot probe"); + // BBRv3 can probe, so moq-net gets a target to write. + assert!(live.probe, "BBRv3 connection has no probe target"); } - /// Loopback test: an application's controller runs both ends' live connections in - /// place of the configured family, here CUBIC. CUBIC cannot probe and BBRv3 can, so a - /// probing connection is running the factory's controller. + /// Loopback test: a configured `cubic` runs both ends' live connections. CUBIC has a + /// slow-start threshold and cannot probe, which BBRv3 can. #[tokio::test] - async fn a_custom_controller_reaches_the_live_connection() { - let server_config = listen::Config { - bind: Some("127.0.0.1:0".parse().unwrap()), - tls: crate::tls::Listen { - generate: vec!["localhost".into()], - ..Default::default() - }, - ..Default::default() - }; - - let server_factory = Arc::new(Counted::default()); - let server_quic = crate::quic::Config { - congestion_control: Some(CongestionControl::Loss), - controller: Some(crate::quic::Controller(server_factory.clone())), - ..Default::default() - }; - - let tls = server_config.tls.load().unwrap(); - let server = Server::new(Options { - config: server_config, - quic: server_quic, - member: None, - tls, - demux: Default::default(), - #[cfg(feature = "test-support")] - sim: None, - }) - .expect("server init"); - let addr = server.local_addr(); - - let accepted = tokio::spawn(async move { - let incoming = server.accept().await.expect("no incoming connection"); - let conn = incoming.accept().expect("accept").await.expect("handshake"); - conn.congestion_state().probes() - }); - - let mut tls_config = crate::tls::Connect::default(); - tls_config.insecure = Some(true); - let client_config = connect::Config { - bind: Some("127.0.0.1:0".parse().unwrap()), - tls: tls_config, - ..Default::default() - }; - - let client_factory = Arc::new(Counted::default()); - let client_quic = crate::quic::Config { - congestion_control: Some(CongestionControl::Loss), - controller: Some(crate::quic::Controller(client_factory.clone())), + async fn cubic_reaches_the_live_connection() { + let quic = crate::quic::Config { + congestion_control: Some(crate::quic::CongestionControl::Cubic), ..Default::default() }; - - let tls = client_config.tls.build().expect("tls config"); - let client = Client::new(&client_config, &client_quic).expect("client init"); - let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap(); - - kio::clock::timeout(Duration::from_secs(5), async move { - let session = client - .connect(&tls, url.into(), &moq_net::Versions::default()) - .await - .expect("connect failed"); - - assert!( - session.connection().congestion_state().probes(), - "client connection is not running its own controller" - ); - assert!( - accepted.await.expect("server task panicked"), - "server connection is not running its own controller" - ); - }) - .await - .expect("test timed out"); - - assert!(client_factory.0.load(std::sync::atomic::Ordering::Relaxed) > 0); - assert!(server_factory.0.load(std::sync::atomic::Ordering::Relaxed) > 0); + let live = live(quic).await; + assert!(!live.probe, "CUBIC connection has a probe target"); + for (end, controller) in [("client", live.client), ("server", live.server)] { + assert!(!controller.probes(), "{end} is not running CUBIC"); + assert!(controller.metrics().ssthresh.is_some(), "{end} is not running CUBIC"); + } } /// The peers file skips this server's own entry, so every server can share it, and refuses diff --git a/rs/moq-uring/src/quic/mod.rs b/rs/moq-uring/src/quic/mod.rs index 520aa9f87d2..74cba381f27 100644 --- a/rs/moq-uring/src/quic/mod.rs +++ b/rs/moq-uring/src/quic/mod.rs @@ -41,33 +41,6 @@ pub use moq_quic::{Limits, LimitsError, Rate}; /// Stream identity, and the varint every QUIC code is. pub use moq_quic::{VarInt, stream}; -/// A built-in congestion control family, which converts into the factory -/// [`transport::Config::congestion`] holds. -/// -/// CUBIC is used for loss-based control and BBRv3 for delay-based control. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum Congestion { - /// Loss-based: grows until it drops packets, so the send rate sawtooths. - Loss, - /// Delay-based: tracks the measured delivery rate and RTT instead of - /// waiting for loss, which keeps queues short and the send rate steady - /// enough for an encoder to track. - Delay, - /// No congestion control and no pacing, for tests and controlled links. - None, -} - -impl From for std::sync::Arc { - fn from(family: Congestion) -> Self { - match family { - Congestion::Loss => std::sync::Arc::new(moq_congestion::cubic::Config::default()), - Congestion::Delay => std::sync::Arc::new(moq_congestion::bbr3::Config::default()), - Congestion::None => std::sync::Arc::new(moq_congestion::Unlimited), - } - } -} - /// Why a connection could not be set up or has ended. /// /// A [`web::Session`] reports it as [`web::Error::Connection`], decoding the diff --git a/rs/moq-uring/src/quic/transport.rs b/rs/moq-uring/src/quic/transport.rs index 51b84b768b8..0794ce45619 100644 --- a/rs/moq-uring/src/quic/transport.rs +++ b/rs/moq-uring/src/quic/transport.rs @@ -1,6 +1,5 @@ //! The per-connection transport knobs, the same for either role. -use super::Congestion; use super::qlog; use crate::quic::Limits; @@ -35,8 +34,7 @@ pub struct Config { /// stream. /// - 4 MiB of unacknowledged outgoing data, whatever the peer allows. pub limits: Limits, - /// The congestion controller each connection runs, BBRv3 by default. A - /// [`Congestion`] family converts into one with `.into()`. + /// The congestion controller each connection runs, BBRv3 by default. pub congestion: std::sync::Arc, /// How often to send an ack-eliciting packet on an otherwise idle /// connection, `None` (the default) to derive it from the negotiated idle @@ -61,7 +59,7 @@ impl Default for Config { idle_timeout: std::time::Duration::from_secs(10), handshake_timeout: moq_quic::transport::Config::default().handshake_timeout, limits: Limits::default(), - congestion: Congestion::Delay.into(), + congestion: std::sync::Arc::new(moq_congestion::bbr3::Config::default()), keep_alive: None, mtu_discovery: false, qlog: None, diff --git a/swift/Sources/Moq/Aliases.swift b/swift/Sources/Moq/Aliases.swift index ab8de5ce2f5..0d2f24aa334 100644 --- a/swift/Sources/Moq/Aliases.swift +++ b/swift/Sources/Moq/Aliases.swift @@ -106,8 +106,8 @@ public typealias ServerTls = MoqFFI.MoqServerTls /// QUIC transport tuning, such as the peer's inbound stream cap. public typealias QuicConfig = MoqFFI.MoqQuicConfig -/// The congestion control family for a QUIC connection. Build one with `CongestionControl.delay()`, -/// `.loss()`, or `.none()`; a new algorithm joins as a new constructor. +/// The congestion control algorithm for a QUIC connection. Build one with `CongestionControl.bbr()`, +/// `.cubic()`, or `.unlimited()`; a new algorithm joins as a new constructor named after it. public typealias CongestionControl = MoqFFI.MoqCongestionControl /// The WebSocket fallback raced against QUIC: whether it runs and QUIC's head start. diff --git a/test/ts/README.md b/test/ts/README.md index f526cd97c7d..7e427b455c7 100644 --- a/test/ts/README.md +++ b/test/ts/README.md @@ -694,7 +694,7 @@ The default queue is twice the export's delay, so a sender that kept it full would make every unit late. The delay-based default (BBRv3) does not: it keeps about a round trip queued, so the backlog lands at the relay, which ages groups out (`Old`), and the queue itself overflows only when it is about a round trip deep. -The loss-based `MOQ_QUIC_CONGESTION_CONTROL=loss` (CUBIC) fills it, latency +The loss-based CUBIC (`MOQ_QUIC_CONGESTION_CONTROL=cubic`) fills it, latency outgrows the delay, and the export refuses the run as a clock drift. So the queue's own tail drop runs as a lane of its own: CUBIC behind a 250 ms @@ -703,7 +703,7 @@ retransmit behind a full queue (about twice 300 ms) still lands inside the 1 s delay. A loss-based run fails unless the queue overflowed. ```bash -MOQ_QUIC_CONGESTION_CONTROL=loss just test ts --headroom --rate 7000000 --queue 250ms +MOQ_QUIC_CONGESTION_CONTROL=cubic just test ts --headroom --rate 7000000 --queue 250ms ``` Measured on 2026-10-18 and 2026-10-19 with other test runs sharing the host: @@ -971,9 +971,9 @@ All recipes use the same pinned Nix FFmpeg and TSDuck locally and in CI. Nightly and manual runs also invoke `just test ts --pair`, `just test ts --live --duration 120`, `just test ts --headroom --rate 7000000 --duration 120`, -the same with `--queue 250ms` and `MOQ_QUIC_CONGESTION_CONTROL=loss`, +the same with `--queue 250ms` and `MOQ_QUIC_CONGESTION_CONTROL=cubic`, and `just test ts --passthrough --rate 7000000 --queue 250ms --duration 120` -with `MOQ_QUIC_CONGESTION_CONTROL=loss`, and `just rs ts-recovery`. +with `MOQ_QUIC_CONGESTION_CONTROL=cubic`, and `just rs ts-recovery`. The pair exercises late-joining subscribers; the live window distinguishes ongoing clock drift from initial buffer filling; the congested paths judge what the export does when the path cannot carry the media. diff --git a/test/ts/run.sh b/test/ts/run.sh index 56a4ad1e1af..7f347ae8fdb 100755 --- a/test/ts/run.sh +++ b/test/ts/run.sh @@ -798,10 +798,10 @@ stop_shaper() { } # The shaper accepts a silent profile while silence is still likely, and never requires a # rate limit to act; a lossy run needs loss, and a congested one a rate limit that held - # datagrams back. A loss-based sender (MOQ_QUIC_CONGESTION_CONTROL=loss) grows until it + # datagrams back. A loss-based sender (MOQ_QUIC_CONGESTION_CONTROL=cubic) grows until it # loses, and the queue's tail drop is the only loss here, so its run must overflow too. local counter overflow="" - [[ -n "$RATE" && "${MOQ_QUIC_CONGESTION_CONTROL:-}" == loss ]] && overflow=overflowed + [[ -n "$RATE" && "${MOQ_QUIC_CONGESTION_CONTROL:-}" == cubic ]] && overflow=overflowed for counter in ${LOSS:+lost} ${RATE:+throttled} $overflow; do if ! python3 -c 'import json, sys; sys.exit(json.load(open(sys.argv[1]))["down"][sys.argv[2]] == 0)' \ "$HARNESS_RUN/shaper.json" "$counter"; then