diff --git a/cpp/obs/src/moq-output.cpp b/cpp/obs/src/moq-output.cpp index 5651a8c4f42..6b3fd66318a 100644 --- a/cpp/obs/src/moq-output.cpp +++ b/cpp/obs/src/moq-output.cpp @@ -391,9 +391,9 @@ void MoQOutput::Reset() broadcast.reset(); origin.reset(); - // Drain once the tracks are finished, so the session delivers their tails instead - // of cutting them off. The future holds the session until the drain settles, and - // dropping it would abort the drain, so keep it past this attempt. + // Drain once tracks finish. Default lite-06 waits for transport ACKs, not + // confirmation that the peer received the tail. Keep the future past this + // attempt because dropping it aborts the drain. if (retired) { draining.erase(std::remove_if(draining.begin(), draining.end(), [](const moq::Future &drain) { diff --git a/dart/moq/lib/src/client.dart b/dart/moq/lib/src/client.dart index 0e811ce8f88..e3119ca4153 100644 --- a/dart/moq/lib/src/client.dart +++ b/dart/moq/lib/src/client.dart @@ -189,7 +189,11 @@ final class Moq { /// the room back. Bandwidth bandwidth() => session.bandwidth(); - /// Gracefully close the session and stop the client. + /// Drain within one second, then stop the client. + /// + /// Explicit `moq-lite-07-wip` waits for the peer to receive finished tails; older + /// Lite versions, including the default lite-06, wait only for transport ACKs. + /// IETF also waits for transport ACKs. Future close() async { try { await session.shutdown(); diff --git a/dart/moq_ffi/lib/src/moq.dart b/dart/moq_ffi/lib/src/moq.dart index 86f382c8533..8f47ff6f1b1 100644 --- a/dart/moq_ffi/lib/src/moq.dart +++ b/dart/moq_ffi/lib/src/moq.dart @@ -13678,7 +13678,7 @@ void _checkApiChecksums() { if (uniffi_moq_ffi_checksum_method_moqsession_publish() != 15240) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } - if (uniffi_moq_ffi_checksum_method_moqsession_shutdown() != 64390) { + if (uniffi_moq_ffi_checksum_method_moqsession_shutdown() != 1301) { throw UniffiInternalError.panicked("UniFFI API checksum mismatch"); } if (uniffi_moq_ffi_checksum_method_moqsession_stats() != 44305) { diff --git a/doc/bin/obs.md b/doc/bin/obs.md index 0938af70489..4b61ae4f1c9 100644 --- a/doc/bin/obs.md +++ b/doc/bin/obs.md @@ -67,7 +67,9 @@ stream limit, and the WebSocket fallback race. A rejected value stops the stream with the reason in the log rather than silently using a default. The plugin is C++ over the [generated C++ bindings](/lib/cpp/) and ships with -every moq-cpp release. +every moq-cpp release. Stopping finishes the tracks and drains for up to one +second. The default lite-06 waits for transport ACKs, which do not confirm that +the peer received the tail. If the relay closes the session for too many requests, reduce the broadcasts or subscribed tracks, or have the operator adjust its diff --git a/doc/lib/cpp/index.md b/doc/lib/cpp/index.md index 8285d3617a8..17f4d282fa6 100644 --- a/doc/lib/cpp/index.md +++ b/doc/lib/cpp/index.md @@ -191,6 +191,11 @@ Obtain a dynamic track request’s `demand()` before accepting it to watch subsc ## Shutdown +`session->shutdown().get()` drains for up to one second and reports any error. +Application delivery requires explicitly selecting `moq-lite-07-wip` on both +peers; older Lite versions (including default lite-06) and IETF wait only for +transport ACKs. Finish or abort live tracks first. + `moq::shutdown()` stops the `moq-ffi` runtime workers, then the executor. Pending calls resolve `Cancelled`, and every object stays safe to drop. Call it once before a plugin or engine module unloads, from a thread that is not diff --git a/doc/lib/dart/index.md b/doc/lib/dart/index.md index 08090415cc8..5f89d426a38 100644 --- a/doc/lib/dart/index.md +++ b/doc/lib/dart/index.md @@ -76,7 +76,7 @@ one to one; the API reference has the names. - **Names.** Types drop the `Moq` prefix (`Session`, `BroadcastProducer`) as aliases, so the generated names still work. `Container`, `Route`, and the exceptions keep it, since Flutter owns those names. `dynamic` is reserved, so the origin method is `dynamic_`. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `cut()`: after every frame, or at a segment cadence to align with video. - **Live encoder timing.** After writing a frame you encoded yourself, call `flush(timestampUs: ...)` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. -- **Closing.** `await moq.close()` or `session.shutdown()` gives finished tracks up to one second to deliver and fails if they did not. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Cancelling a stream subscription releases its native cursor. +- **Closing.** `await moq.close()` or `session.shutdown()` drains for up to one second and reports any error. `session.cancel(code: 0)` closes at once. Finish or abort live tracks first. Cancelling a stream subscription releases its native cursor. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, `estimatedRecvRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. diff --git a/doc/lib/go/index.md b/doc/lib/go/index.md index 92c4053dd8a..d9c791352c7 100644 --- a/doc/lib/go/index.md +++ b/doc/lib/go/index.md @@ -106,7 +106,7 @@ one to one; the API reference has the names. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `Cut()`: after every frame, or at a segment cadence to align with video. - **Live encoder timing.** After writing a frame you encoded yourself, call `Flush(timestamp)` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `Discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `Close` each `VideoDecodedFrame` promptly, or the decoder stalls. `Resize` is best effort, so read each frame's `Width()` and `Height()`. -- **Closing.** `client.Close()` gives finished tracks up to one second to deliver and returns an error if they did not. `session.Shutdown(ctx)` does the same, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. +- **Closing.** `client.Close()` drains for up to one second and returns an error on failure. `session.Shutdown(ctx)` does the same, and `session.Cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Stats.** `Session().Stats()` reports `RTT`, `EstimatedSendRateBps`, `EstimatedRecvRateBps`, and the byte and packet counters (`BytesSent`, `BytesReceived`, `BytesLost`, `PacketsSent`, `PacketsReceived`, `PacketsLost`). A field is nil when the transport does not report it, which is not the same as zero. - **Errors.** Read diagnostic payloads from `Reason` and structured protocol failures from `Details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. diff --git a/doc/lib/js/net.md b/doc/lib/js/net.md index 1d3df7992c1..612d7e5b4d3 100644 --- a/doc/lib/js/net.md +++ b/doc/lib/js/net.md @@ -46,7 +46,7 @@ broadcast.announce(); - **Subscriber staleness is `maxDelay`.** It is media time. Passing the old `maxAge` key throws a `TypeError` naming `maxDelay`. Publisher retention is the separate `Track.Info.maxAge`. - **Hidden paths** stay out of discovery unless the announce request opts in. See [hidden broadcasts](/concept/moq-lite#hidden-broadcasts). - **Authorization is in band.** On moq-lite 07 (offered only when `moq-lite-07-wip` is listed in `webtransport.protocols`; the WebSocket fallback cannot offer it) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `auth.grant` watches what the relay lets this side publish and subscribe to, and `auth.add(token)` presents another token without reconnecting. Publishing outside the grant closes the connection with `SessionCode.Unauthorized`, naming the path. On moq-lite, a subscription the grant stops covering resets with `StreamCode.Unauthorized` and the session stays up. -- **A graceful close waits.** `await connection.close()` withdraws announcements and gives finished tracks up to one second. `abort()` ends immediately. +- **A graceful close waits.** `await connection.close()` withdraws announcements and drains for up to one second. Application delivery requires explicit `moq-lite-07-wip`; older Lite versions wait only for transport ACKs. IETF media streams are not drained. `abort()` ends immediately. Examples: [`js/net/examples/`](https://github.com/moq-dev/moq/tree/main/js/net/examples). diff --git a/doc/lib/kt/index.md b/doc/lib/kt/index.md index 98cc4f5be7e..869edb26b26 100644 --- a/doc/lib/kt/index.md +++ b/doc/lib/kt/index.md @@ -81,7 +81,7 @@ one to one; the API reference has the names. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `cut()`: after every frame, or at a segment cadence to align with video. - **Live encoder timing.** After writing a frame you encoded yourself, call `flush(timestampUs)` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** `close()` each frame from `decodeVideo` promptly (or `use { }` it), or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. -- **Closing.** Suspending `moq.shutdown()` gives finished tracks up to one second to deliver and throws if they did not. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. +- **Closing.** Suspending `moq.shutdown()` drains for up to one second and throws on failure. `Moq.close()`, and so `use { }`, cancels at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, `estimatedRecvRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `null` when the transport does not report it, which is not the same as zero. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. diff --git a/doc/lib/py/index.md b/doc/lib/py/index.md index 9a8e257ba1f..6de3ead7f29 100644 --- a/doc/lib/py/index.md +++ b/doc/lib/py/index.md @@ -97,7 +97,7 @@ one to one; the API reference has the names. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `cut()`: after every frame, or at a segment cadence to align with video. - **Live encoder timing.** After writing a frame you encoded yourself, call `flush(timestamp)` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Drop each frame from `decode_video` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. -- **Closing.** `await session.shutdown()` gives finished tracks up to one second to deliver and raises if they did not. `cancel(code)` closes at once. Finish or abort live tracks first. +- **Closing.** `await session.shutdown()` drains for up to one second and raises on failure. `cancel(code)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Stats.** `session.stats()` reports `rtt`, `estimated_send_rate_bps`, `estimated_recv_rate_bps`, and the byte and packet counters (`bytes_sent`, `bytes_received`, `bytes_lost`, `packets_sent`, `packets_received`, `packets_lost`). A field is `None` when the transport does not report it, which is not the same as zero. - **Errors.** Read diagnostic payloads from `reason` and structured protocol failures from `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. diff --git a/doc/lib/rs/moq-net.md b/doc/lib/rs/moq-net.md index d49c3d9d494..b5143ea5ea6 100644 --- a/doc/lib/rs/moq-net.md +++ b/doc/lib/rs/moq-net.md @@ -25,7 +25,7 @@ What you use it for, beyond what the concept page already describes: - **You drive the session, or `moq-tokio` does.** `connect` and `accept` return a session plus a driver that never reads the clock itself. `moq_net::time::run` polls it on tokio or in the browser. `moq-tokio` and `moq-wasm` hide that. A custom transport implements `moq_net::transport::poll`. - **A session caps what its peer can hold.** `session::Limits` (via `Client::with_limits` and `Server::with_limits`) bounds announces and subscriptions per session; the defaults suit a relay mesh, so lower them for untrusted peers. Past either, the session closes with `TOO_MANY_REQUESTS`. On moq-transport drafts 14 to 16 they also size the request-ID window, which every request counts against, so very low limits can starve it. Peer-declared lengths are capped before they are buffered. - **Authorization is in band.** On moq-lite 07 (`moq-lite-07-wip`, opt-in) and on moq-transport draft-17+ with the [MoQ Auth extension](/draft/moq-auth), `session.auth()` presents tokens without reconnecting and watches the grant the peer sent back. A server verifies tokens itself by taking `handshake.auth().requests()` before `ok()`. `authorize(&grant)` narrows or widens a live session on any version: what falls outside resets with `Unauthorized` and the session stays up. A client that publishes outside its grant closes the session, naming the path. -- **A graceful close waits.** `session.close().await` withdraws announcements and gives finished tracks up to one second to deliver. `abort` ends immediately. IETF drafts 14 through 16 send withdrawals without waiting. +- **A graceful close waits.** `session.close().await` withdraws announcements and drains for up to one second. Application delivery requires explicit `moq-lite-07-wip`; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. `abort` ends immediately. IETF drafts 14 through 16 send withdrawals without waiting. ```bash cargo add moq-net moq-tokio diff --git a/doc/lib/swift/index.md b/doc/lib/swift/index.md index beb0f08bcf0..104178eb9a3 100644 --- a/doc/lib/swift/index.md +++ b/doc/lib/swift/index.md @@ -81,7 +81,7 @@ one to one; the API reference has the names. - **Audio needs cuts.** Video groups at its keyframes, but audio forms a group only where you call `cut()`: after every frame, or at a segment cadence to align with video. - **Live encoder timing.** After writing a frame you encoded yourself, call `flush(timestampUs:)` with the same timestamp so the catalog advertises your jitter. Skip it for file and network imports. On a seek or pause, call `discontinuity()`, then keep timestamps moving forward and resume video on a keyframe. - **Decoded frames hold decoder buffers.** Release each frame from `decodeVideo` promptly, or the decoder stalls. `resize` is best effort, so read each frame's `width()` and `height()`. -- **Closing.** `try await session.shutdown()` gives finished tracks up to one second to deliver and throws if they did not. `session.cancel(code:)` closes at once. Finish or abort live tracks first. +- **Closing.** `try await session.shutdown()` drains for up to one second and throws on failure. `session.cancel(code:)` closes at once. Finish or abort live tracks first. Application delivery requires explicitly selecting `moq-lite-07-wip` on both peers; older Lite versions (including default lite-06) and IETF wait only for transport ACKs. - **Stats.** `session.stats()` reports `rttUs`, `estimatedSendRateBps`, `estimatedRecvRateBps`, and the byte and packet counters (`bytesSent`, `bytesReceived`, `bytesLost`, `packetsSent`, `packetsReceived`, `packetsLost`). A field is `nil` when the transport does not report it, which is not the same as zero. - **Errors.** Diagnostic cases use the `reason:` argument label; match their associated value to inspect it. Protocol errors carry `details`. - **Disabled renditions.** Audio and video convenience decoders reject a catalog configuration with `enabled: false`. Select an enabled rendition from the latest catalog before opening a decoder. diff --git a/go/wrapper/session.go b/go/wrapper/session.go index 4e9ab981fb2..88cd5cb3664 100644 --- a/go/wrapper/session.go +++ b/go/wrapper/session.go @@ -104,7 +104,10 @@ func (s *Session) Consume() *OriginConsumer { return &OriginConsumer{inner: s.inner.Consume()} } -// Shutdown drains finished tracks within one second, returning any delivery error. +// Shutdown drains finished tracks within one second, returning any drain error. +// Explicit moq-lite-07-wip waits for the peer to receive finished tails; older Lite +// versions, including the default lite-06, wait only for transport ACKs. +// IETF also waits for transport ACKs. // Cancelling ctx aborts the session immediately. func (s *Session) Shutdown(ctx context.Context) error { return bridge.CallErr(ctx, s.abort, s.inner.Shutdown) diff --git a/js/net/src/connection/established.ts b/js/net/src/connection/established.ts index a081f71c606..7695c2c099b 100644 --- a/js/net/src/connection/established.ts +++ b/js/net/src/connection/established.ts @@ -52,7 +52,12 @@ export interface Established { */ stats(): Promise; - /** Withdraw announcements and wait up to one second for delivery, then close the session. */ + /** + * Withdraw announcements and drain for up to one second, then close the session. + * + * Explicit lite-07-wip waits for the subscriber to receive finished tails; older + * Lite versions wait only for transport ACKs. IETF media streams are not drained. + */ close(): Promise; /** End the session immediately without waiting for delivery. */ diff --git a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt index 62bb61c9f8b..a09a3ddfb72 100644 --- a/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt +++ b/kt/moq/src/jvmAndAndroidMain/kotlin/dev/moq/Moq.kt @@ -67,7 +67,12 @@ class Moq internal constructor( */ fun bandwidth(): Bandwidth = session.bandwidth() - /** Drain finished tracks within one second, throwing if delivery times out. */ + /** + * Drain finished tracks within one second, throwing on failure. + * Explicit `moq-lite-07-wip` waits for the peer to receive finished tails; older + * Lite versions, including the default lite-06, wait only for transport ACKs. + * IETF also waits for transport ACKs. + */ suspend fun shutdown() { try { session.shutdown() diff --git a/py/moq-rs/README.md b/py/moq-rs/README.md index dec2b5364e0..03051090c06 100644 --- a/py/moq-rs/README.md +++ b/py/moq-rs/README.md @@ -150,7 +150,7 @@ client = moq.Client( - `.cancel()`. Cancel an in-flight `accept()`/`reject()` call. - **`Session`**. An established connection. Holding it keeps the connection alive; it is also an `async with` context manager that drains on a clean exit and cancels on an error. - `await .closed()`. Wait until the session closes. - - `.cancel(code)`, `await session.shutdown()`. Cancel immediately, or drain finished tracks within one second, raising on failure. + - `.cancel(code)`, `await session.shutdown()`. Cancel immediately, or drain within one second, raising on failure. Explicit `moq-lite-07-wip` waits for the peer to receive finished tails; older Lite versions, including default lite-06, wait only for transport ACKs. IETF also waits for transport ACKs. - `.publish() → OriginProducer`, `.consume() → OriginConsumer`. The wired origin sides. - `.stats() → ConnectionStats`. Snapshot RTT, bandwidth estimates, and byte/packet counters. - `await .status() → ConnectionStatus`, `.connects()`. Watch reconnects; `connects()` counts connections, 1 on the first. diff --git a/py/moq-rs/moq/session.py b/py/moq-rs/moq/session.py index 63254829f5c..08f60eefb2e 100644 --- a/py/moq-rs/moq/session.py +++ b/py/moq-rs/moq/session.py @@ -72,7 +72,12 @@ def cancel(self, code: int) -> None: self._inner.cancel(code) async def shutdown(self) -> None: - """Drain finished tracks within one second, raising if delivery times out.""" + """Drain within one second, raising on failure. + + Explicit ``moq-lite-07-wip`` waits for the peer to receive finished tails; + older Lite versions, including the default lite-06, wait only for transport + ACKs. IETF also waits for transport ACKs. + """ await self._inner.shutdown() def publish(self) -> OriginProducer: diff --git a/quest/m1/test-flakes-2/README.md b/quest/m1/test-flakes-2/README.md index 890c82c7050..f0a9c5e1966 100644 --- a/quest/m1/test-flakes-2/README.md +++ b/quest/m1/test-flakes-2/README.md @@ -40,7 +40,6 @@ Public API: none. Wire: none. - [uring teardown close](/quest/m1/test-flakes-2/uring-teardown-close.md) - moq-uring's published-close teardown test holds under load, fixed at its cause - [Auth serve signals](/quest/m1/test-flakes-2/auth-serve-signals.md) - moq-cli's auth serve signal tests hold under load - [Export exit tests](/quest/m1/test-flakes-2/export-failure-exit.md) - moq-cli's failed-export and interrupted-publisher exit tests hold under load -- [FFI shutdown](/quest/m1/test-flakes-2/ffi-shutdown.md) - moq-ffi's graceful shutdown tests hold under load ## Related diff --git a/quest/m1/test-flakes-2/ffi-shutdown.md b/quest/m1/test-flakes-2/ffi-shutdown.md deleted file mode 100644 index 3acbd0a938f..00000000000 --- a/quest/m1/test-flakes-2/ffi-shutdown.md +++ /dev/null @@ -1,27 +0,0 @@ -# [S] moq-ffi shutdown tests hold under load - -## Goal - -`moq-ffi`'s `shutdown_delivers_the_finished_track` and -`shutdown_times_out_on_an_unfinished_track` (`rs/moq-ffi/src/test.rs`) pass -under a loaded `just check`, fixed at their cause. They still prove that a -graceful shutdown delivers a finished track's tail, and gives up on an -unfinished one after the documented one second with `DeliveryTimeout`. - -## Plan - -Seen 2026-10-13 on #5471 and #5486, once each under a loaded `just check`; -both passed alone. Which assertion failed wasn't recorded. Both tests run a -real QUIC pair on the wall clock and bound most steps with a 10 s `TIMEOUT`, -but not all: the first leaves the detached `shutdown()` unbounded, and the -second leaves `shutdown_pair()`, the subscribe, and `shutdown()` unbounded -while asserting shutdown took at least one second. - -Reproduce under load first and record the failing assertion, or the stage -that hung if no assertion fired. Then move the tests to a paused clock if -the transport allows it, or assert on events rather than elapsed time, per -the epic's rules. If shutdown itself loses the tail or drains for the wrong -time under load, that is a product bug: fix shutdown. Never widen a timeout -or add a retry. - -Public API: none expected. Wire: none. diff --git a/rs/moq-ffi/Cargo.toml b/rs/moq-ffi/Cargo.toml index cfa9562c3c5..ccf3dbcae80 100644 --- a/rs/moq-ffi/Cargo.toml +++ b/rs/moq-ffi/Cargo.toml @@ -84,4 +84,5 @@ uniffi = { workspace = true, features = ["build"] } [dev-dependencies] # One non-codec test blocks on a future; the main dep is `video`-only. pollster = { workspace = true } +tokio = { workspace = true, features = ["test-util"] } web-transport-trait = { workspace = true } diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index 010db17954d..586e6f588b6 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -820,11 +820,13 @@ impl MoqSession { // (with the close reason, or Ok once the connection loop stops). } - /// Drain finished tracks within one second, returning any delivery error. + /// Drain finished tracks within one second, returning any drain error. /// /// Finish or abort live tracks first. `cancel` stays immediate. The name /// avoids Kotlin's generated `AutoCloseable.close()`, which releases the handle. - /// IETF media streams are not drained yet. + /// Explicit `moq-lite-07-wip` waits for the peer to receive the tail. Older Lite + /// versions, including the default lite-06, wait only for transport ACKs. + /// IETF also waits for transport ACKs. pub async fn shutdown(&self) -> Result<(), MoqError> { let inner = self.inner.clone(); crate::ffi::detached(async move { diff --git a/rs/moq-ffi/src/test.rs b/rs/moq-ffi/src/test.rs index d79c7831706..b771434d4dc 100644 --- a/rs/moq-ffi/src/test.rs +++ b/rs/moq-ffi/src/test.rs @@ -5486,10 +5486,12 @@ async fn data_track_names_cannot_collide() { } /// Real sockets exercise the FFI runtime and both accepted/client session handles. +/// Only lite-07 acknowledges the received tail; default lite-06 closes after transport ACKs. async fn shutdown_pair() -> (Arc, Arc, Arc) { let server = MoqServer::new(MoqServerConfig { bind: Some("127.0.0.1:0".into()), tls: localhost_tls(), + versions: vec!["moq-lite-07-wip".into()], ..Default::default() }) .unwrap(); @@ -5507,6 +5509,7 @@ async fn shutdown_pair() -> (Arc, Arc, Arc) { }); let client = MoqClient::new(MoqClientConfig { tls: insecure_tls(), + versions: vec!["moq-lite-07-wip".into()], bind: Some("127.0.0.1:0".into()), once: true, ..Default::default() @@ -5516,6 +5519,24 @@ async fn shutdown_pair() -> (Arc, Arc, Arc) { (server, connected, accepted.await.unwrap()) } +/// TRACK_INFO holds demand before SUBSCRIBE; receiving a frame proves live delivery started. +async fn shutdown_ready(track: &MoqTrackProducer, reader: &MoqTrackConsumer) { + let group = track.append_group().unwrap(); + group + .write_frame(MoqFrame { + timestamp_us: Some(0), + payload: b"ready".to_vec(), + }) + .unwrap(); + group.finish().unwrap(); + let ready = tokio::time::timeout(TIMEOUT, reader.read_frame()) + .await + .expect("subscription ready") + .expect("priming read") + .expect("priming frame"); + assert_eq!(ready.payload, b"ready"); +} + #[tokio::test] async fn shutdown_delivers_the_finished_track() { for client_publishes in [false, true] { @@ -5532,34 +5553,35 @@ async fn shutdown_delivers_the_finished_track() { .await .expect("subscribe") .unwrap(); + shutdown_ready(&track, &reader).await; let receiving = tokio::spawn(async move { let frame = reader.read_frame().await?; let end = reader.read_frame().await?; Ok::<_, MoqError>((frame, end)) }); - tokio::time::timeout(TIMEOUT, track.demand().unwrap().used()) - .await - .expect("used") - .unwrap(); let closing = publisher.clone(); - crate::ffi::detached(async move { - let group = track.append_group()?; - group.write_frame(MoqFrame { - timestamp_us: Some(0), - payload: b"last".to_vec(), - })?; - group.finish()?; - track.finish()?; - closing.shutdown().await?; - Ok::<(), MoqError>(()) - }) + tokio::time::timeout( + TIMEOUT, + crate::ffi::detached(async move { + let group = track.append_group()?; + group.write_frame(MoqFrame { + timestamp_us: Some(0), + payload: b"last".to_vec(), + })?; + group.finish()?; + track.finish()?; + closing.shutdown().await?; + Ok::<(), MoqError>(()) + }), + ) .await + .expect("shutdown") .unwrap(); let (frame, end) = tokio::time::timeout(TIMEOUT, receiving) .await .expect("read") .unwrap() - .unwrap(); + .unwrap_or_else(|err| panic!("client_publishes={client_publishes}: tail/end: {err:?}")); assert_eq!(frame.unwrap().payload, b"last"); assert!(end.is_none()); client.cancel(0); @@ -5571,7 +5593,7 @@ async fn shutdown_delivers_the_finished_track() { #[tokio::test] async fn shutdown_times_out_on_an_unfinished_track() { for client_publishes in [false, true] { - let (server, client, accepted) = shutdown_pair().await; + let (server, client, accepted) = tokio::time::timeout(TIMEOUT, shutdown_pair()).await.expect("pair"); let (publisher, subscriber) = if client_publishes { (&client, &accepted) } else { @@ -5580,15 +5602,19 @@ async fn shutdown_times_out_on_an_unfinished_track() { let broadcast = create_announced(&publisher.publish(), "live"); let track = broadcast.publish_track("data".into(), None).unwrap(); let remote = await_announced(&subscriber.consume(), "live").await; - let reader = remote.subscribe_track("data".into(), None).await.unwrap(); - let receiving = tokio::spawn(async move { reader.read_frame().await }); - tokio::time::timeout(TIMEOUT, track.demand().unwrap().used()) + let reader = tokio::time::timeout(TIMEOUT, remote.subscribe_track("data".into(), None)) .await - .unwrap() + .expect("subscribe") .unwrap(); + shutdown_ready(&track, &reader).await; + let receiving = tokio::spawn(async move { reader.read_frame().await }); let start = std::time::Instant::now(); - let err = publisher.shutdown().await.expect_err("unfinished track must time out"); - // The documented one second of draining, so an immediate bail still fails here. + let err = tokio::time::timeout(TIMEOUT, publisher.shutdown()) + .await + .expect("shutdown") + .expect_err("unfinished track must time out"); + // The FFI runtime owns real sockets and cannot share a paused test clock. + // A lower bound still rejects an immediate bail without depending on scheduler latency. assert!( start.elapsed() >= Duration::from_secs(1), "gave up draining after {:?}", diff --git a/rs/moq-net/src/session.rs b/rs/moq-net/src/session.rs index 2c7e97dd014..ff7708438f9 100644 --- a/rs/moq-net/src/session.rs +++ b/rs/moq-net/src/session.rs @@ -187,11 +187,13 @@ impl Session { } } - /// Close the session once the data it queued has been delivered. + /// Close the session after draining its queued data. /// /// Waits until every stream still serving the peer (a subscription whose track /// finished, a fetch, a track info reply) has written its data and FIN and the - /// peer acknowledged them, then closes the transport. Returns + /// transport acknowledged them, then closes the transport. Explicit lite-07-wip + /// also waits for the subscriber to receive a subscription's tail. Older Lite + /// versions, including the default lite-06, and IETF wait only for transport ACKs. Returns /// [`Error::Timeout`] if that takes longer than one second, closing anyway, or /// the session's terminal error if it ended some other way first. A track that /// is still live never finishes, so finish or abort tracks before closing. diff --git a/rs/moq-net/tests/session_close.rs b/rs/moq-net/tests/session_close.rs index 19b2bcb189a..92f2c79cf73 100644 --- a/rs/moq-net/tests/session_close.rs +++ b/rs/moq-net/tests/session_close.rs @@ -90,6 +90,29 @@ async fn setup(version: &str) -> Setup { } } +/// TRACK_INFO creates demand before any SUBSCRIBE, so demand alone cannot gate a drain test. +#[moq_net_sim::test] +async fn track_info_interest_precedes_a_subscription() { + for version in ["moq-lite-05", "moq-lite-06", "moq-lite-07-wip"] { + let publisher = produce_origin(1); + let broadcast = publisher.create_broadcast("bcast").unwrap(); + let track = broadcast.create_track("video", timed()).unwrap(); + broadcast.announce(Default::default()).unwrap(); + let subscriber = produce_origin(2); + let mut options = MockConnectOptions::new(version.parse().unwrap()); + options.server_publish = Some(publisher.consume()); + options.client_subscribe = Some(subscriber.clone()); + let _pair = connect_mock(options).await; + let consumer = subscriber.consume(); + consumer.routed("bcast").await.unwrap(); + let remote = consumer.request_broadcast("bcast", None).await.unwrap(); + let copy = remote.track("video").unwrap(); + copy.query().await.expect("TRACK_INFO"); + track.demand().used().await.expect("TRACK_INFO holds demand"); + assert!(track.subscription().is_none(), "{version}: no SUBSCRIBE was requested"); + } +} + /// A finished track's last group and FIN reach the subscriber, even though the /// close is requested before the session wrote them. #[moq_net_sim::test] diff --git a/rs/moq-tokio/src/connection.rs b/rs/moq-tokio/src/connection.rs index a7ac0c4d3b8..6d997ade107 100644 --- a/rs/moq-tokio/src/connection.rs +++ b/rs/moq-tokio/src/connection.rs @@ -753,10 +753,11 @@ impl Connection { } /// Stop the loop for every clone, closing the live session (and any predecessor - /// still finishing after a GOAWAY) once the data it queued has been delivered. + /// still finishing after a GOAWAY) after draining its queued data. /// - /// See [`moq_net::Session::close`]: finished tracks deliver their last groups and - /// FIN and announcements are withdrawn first, bounded by a one second deadline + /// See [`moq_net::Session::close`]: explicit lite-07-wip waits for the subscriber + /// to receive finished tracks' tails; older Lite versions and IETF wait only for + /// transport ACKs. Announcements are withdrawn first, bounded by a one second deadline /// (or a predecessor's remaining handover window, if sooner). Call this before /// [`Client::close`], which closes the transport without waiting. Returns `Ok` /// when nothing was live, and a session's error if it did not drain. diff --git a/swift/Sources/Moq/Client.swift b/swift/Sources/Moq/Client.swift index f65422a28af..acb9266c83d 100644 --- a/swift/Sources/Moq/Client.swift +++ b/swift/Sources/Moq/Client.swift @@ -110,7 +110,10 @@ public final class Session: Sendable { ffi.cancel(code: code) } - /// Drain finished tracks within one second, throwing if delivery times out. + /// Drain finished tracks within one second, throwing on failure. + /// Explicit `moq-lite-07-wip` waits for the peer to receive finished tails; older + /// Lite versions, including the default lite-06, wait only for transport ACKs. + /// IETF also waits for transport ACKs. public func shutdown() async throws { try await ffi.shutdown() }