Skip to content

Data streams: trailer attributes, progress, reader close, and declared text length over the FFI - #1558

Merged
pblazej merged 45 commits into
mainfrom
blaze/dsv2-ffi-gaps
Oct 28, 2026
Merged

pblazej merged 45 commits into
mainfrom
blaze/dsv2-ffi-gaps

Conversation

@pblazej

@pblazej pblazej commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds six data stream features to the FFI for the Swift and Android SDKs, plus two API changes from review. Each change has a test that fails without it.

Changes

Change Motivation
Readers show trailer attributes in info() after the last read. JS parity. The FFI read the stream info only once, so trailer attributes were lost.
The writer close method takes optional trailer attributes. Parity with the Rust and Python SDKs, which can already send them.
Readers get next_progress(). One-shot sends take an on_progress callback: in the core through SendTextOptions and SendByteOptions, in the FFI through an optional progress field on the option records. JS parity. JS reports progress for sends and for reads.
Incremental text streams can declare a total length with StreamTextOptions.total_length. JS and Flutter parity (totalSize). The receiver can show progress and detect a short stream.
Readers get close(), which stops the native read and ends only that stream. Dropping a reader does the same. Each stream has its own cancellation token for this. Task cancellation in Swift and Kotlin. Before, a cancelled read kept running and kept its buffered data.
The core fails an inline stream whose length does not match its header. Hardening. A short or long inline stream was accepted without an error. JS also fails a short one.
The outgoing options are split by call: SendTextOptions and SendByteOptions for one-shot sends, StreamTextOptions and StreamByteOptions for incremental streams. All four are #[non_exhaustive]. Review feedback. Builder-only construction lets us add fields later without a break, and each struct holds only the fields its call uses.
InputEvent and OutputEvent are #[non_exhaustive]. Review feedback. New events can be added later without a break.

Compatibility

  • The public Rust API has breaking changes, so the changesets are major for livekit-data-stream, livekit, and livekit-rpc.
  • To migrate, build every options value with new_with_topic and the with_* setters, use the Send* option type at send_text, send_bytes, and send_file calls, and add a wildcard arm to exhaustive matches on InputEvent and OutputEvent.
  • The FFI surface stays additive. New FFI parameters and fields have default values, so existing Swift and Kotlin calls compile without change.
  • The first commit fixes existing clippy warnings, so that clippy can run with -D warnings.

Testing

  • cargo test passes: 124 livekit-data-stream tests, 24 livekit-ffi core-module tests, 26 livekit-rpc tests, and 71 livekit tests.
  • The e2e data_stream_test and rpc_test suites pass against a local server.
  • The Swift, Kotlin, and Dart bindings build, and the generated code is unchanged by the API split.

After the next LiveKitFFI release, a follow-up to livekit/client-sdk-swift#1075 (merged) adopts these features in Swift.

pblazej and others added 22 commits October 22, 2026 09:28
`cargo clippy -- -D warnings` failed on both crates before any data stream
change. Mechanical fixes only, with no change in behavior: redundant
closures and conversions, a needless return, a no-op struct update, and a
type alias for a complex test type. `DataPacket::kind` is deprecated but
still set, so its three uses allow the lint. `InputEvent` keeps its large
variant, because boxing it changes a public type.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The FFI readers converted the stream info once, when they were created,
so attributes that the sender put in the trailer never reached a binding.
The readers now keep the core info, whose attribute map the incoming
manager updates, and convert it on each `info()` call.

The core merges trailer attributes before it ends the stream, so the
final attributes are visible when `next()` returns `None` or `readAll()`
returns. This matches JS, where the trailer updates `reader.info` before
the stream closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The core writers can send attributes in the stream trailer, but the FFI
writers exported only `close()` and `close_with_reason()`. Both writers
now export `close_with_options(reason, attributes)`, a thin wrapper over
the core method.

`attributes` is a plain map rather than an optional one: the trailer
carries an empty map either way, so `None` and an empty map would be two
spellings of the same packet. The name does not collide with the
`close()` that UniFFI generates for Kotlin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
Incoming: each FFI reader exports `next_progress()`, an async method that
returns the current progress on the first call and then waits for the
next change. It returns `None` once the stream ends. It wraps the core
progress stream, so it counts bytes as they arrive, after decompression,
and updates between two calls merge into the latest one. An async method
rather than a callback keeps it usable from Dart, which cannot take a
callback from a tokio thread (see `polled.rs`).

For the FFI to hold that stream next to the reader, the core
`StreamReader::progress()` now returns `impl Stream + Send + 'static`.
The watch stream behind it already was; the old signature only tied it
to `&self`.

Outgoing: a new `StreamProgressDelegate` callback trait and three new
methods, `send_text_with_progress`, `send_bytes_with_progress` and
`send_file_with_progress`. The callback runs inside the send future, on
the thread that polls it, like `RemoteParticipantRegistryDelegate`.

- A file reports after each chunk is sent, counting file bytes before
  compression, through the new core `send_file_with_progress`. An empty
  file reports `0 / 0` once, so the last report always covers the file.
- One-shot text and byte sends go to the transport as one request, so
  they report once, when the send completes.

This follows JS, which counts pre-compression bytes and always fires a
final 100% event. JS reports a 0..1 fraction; the FFI reports byte counts
with an optional total, like the core `StreamProgress`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`StreamTextOptions` had no total length, and `stream_text` passed `None`
to `build_text_header`, so a sender that knew the final length of its
text could not put it in the header. The core options and the FFI record
now carry an optional `total_length`, which `stream_text` puts in the
header. The receiver already checks a declared length (`Incomplete`,
`LengthExceeded`) and reports progress against it.

`send_text` ignores the field, because it sets the length from the text
it sends. The room-apis protobuf options have no such field, so their
conversion passes `None`.

The FFI field goes last with `default = None`, so existing Swift and
Kotlin call sites that build the record keep compiling. JS and Flutter
call the same option `totalSize`; the FFI keeps the core name, which the
byte options already use.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A binding had no way to stop one reader: cancelling a pending `next()`
or `readAll()` on the foreign side left the native read running, and the
reader kept its receiver and buffered chunks until the stream ended or
the room disconnected. A Rust caller avoids this by dropping the reader.

Both readers now export a synchronous `close()`:

- It cancels a per-reader token. A pending `next()` or `readAll()` wakes
  and fails with `DataStreamError::AlreadyClosed`, as does every later
  read, and `next_progress()` returns `None`.
- The core reader is dropped, which frees its buffered chunks and closes
  its channel. The incoming manager then drops the stream at its next
  packet and reports it closed. Other streams are not affected.
- `close()` never blocks, so a Swift `onCancel` handler can call it. A
  read in progress holds the reader lock until it sees the cancellation,
  so `close()` drops the reader from a short task that takes the lock
  after that read.

There is no `Cancelled` error variant, and adding one would break
exhaustive Kotlin `when` expressions over `DataStreamException`, so the
read fails with the existing `AlreadyClosed`. JS errors the read with the
abort reason; Python ends it like end-of-stream.

Kotlin gets `closeStream()`, like the writers, because UniFFI already
generates a non-suspend `close()` for `AutoCloseable`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
For a stream that arrives in one packet, the incoming manager checked the
payload against the receive size limit but not against `total_length` in
the header. A header that declared five bytes with three inline bytes
ended with success. The chunked path already fails that stream at its
trailer.

The inline branch now compares the decoded byte count, after
decompression for a compressed payload, with `total_length` when the
header has one. A short payload fails with `StreamError::Incomplete` and
a long one with `StreamError::LengthExceeded`, so no new error variant is
needed. A header without a length is not checked, and matching payloads,
compressed or not, read as before.

JS rejects a short inline stream with `Incomplete` too. Unlike JS, a
declared length of 0 is held to the payload, as the chunked path here
already does. Every sender that inlines sets the real length, so this
rejects no stream that a conforming sender produces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`cb688a63` changed the public trait method to return
`impl Stream + Send + 'static`, so that the FFI could hold the progress
stream next to the reader. That is a stricter contract on a public trait.
The trait method is back to `impl Stream<Item = StreamProgress>`.

The concrete readers get an inherent `progress_stream()` instead, which
returns a `Send + Unpin + 'static` stream that does not borrow the
reader. The trait implementations call it. The FFI readers use it.

With the trait unchanged, the core part of the progress changeset is
additive, so `livekit-data-stream` goes from `minor` to `patch` there.
`livekit-ffi` stays `minor`.

The `next_progress()` docs now say that progress counts the bytes
received from the sender, not the bytes the app has read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`close()` on an FFI reader cancelled its reads and dropped the core
reader, but the incoming manager learned about it only when a later
chunk failed to deliver. If the sender sent nothing more, the stream's
descriptor, decompressor and attributes stayed registered, and
`on_stream_closed` never fired, which can block ordered handlers.

`close()` now enqueues a targeted event:

- Each reader the manager creates carries a `StreamCloser`: a weak
  handle to the manager's input, the stream id, and an instance number
  that the manager assigns per opened stream. `closer()` on the concrete
  core readers returns it.
- `StreamCloser::close()` sends `InputEvent::CloseStream`. The manager
  removes the descriptor and emits `StreamClosed` only when the open
  stream with that id has the same instance number. So a repeated or
  late close, or a close that loses a race with the trailer, does
  nothing, and a later stream that reuses the id is never touched.
- The stream ends with `StreamError::AlreadyClosed` in its chunk
  channel, so a Rust reader that is still reading fails instead of
  ending as if the stream were complete.
- The FFI reader takes its closer when it is created, so `close()`
  enqueues synchronously even while a read holds the reader lock.

The handle is weak, so a closer does not keep the manager running.

Tests: closing with no further packets drops the open count and fires
one close event while another stream keeps working, for text and byte
readers. A repeated close fires one event. Close racing the final chunk
and the trailer, in each order, fires one event. A late close spares a
later stream with the same id. The FFI tests poll the read to `Pending`
before closing instead of sleeping, and count close events against an
inline marker stream, which closes last.

The new `InputEvent` variant breaks exhaustive matches on the enum, and
`livekit` re-exports the crate, so the changeset marks both `minor`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
- `incoming_progress_merges_updates_between_calls`: two chunks that
  arrive between two `next_progress()` calls yield only the latest value.
- `incoming_progress_ends_when_the_stream_fails`: a stream that exceeds
  its declared length ends its progress with `None`, and the read fails
  with `LengthExceeded`.
- `incoming_trailer_attributes_replace_header_attributes`: a trailer key
  replaces the header's value for the same key, and other header keys
  stay.
- `v2_inline_non_empty_payload_with_declared_zero_length_fails`: the core
  holds a declared length of 0 to an inline payload, compressed or not.
  JS skips the check for 0. No sender inlines a non-empty payload with a
  length of 0, so this documents a deliberate difference from JS.

These tests pin down behavior that the earlier commits already have.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The new public `total_length` field breaks struct-literal construction
of the core `StreamTextOptions`, which is not `#[non_exhaustive]`.
`livekit` re-exports the type, and the public `RpcTransport::send_text`
in `livekit-rpc` takes it, so both go from `patch` to `minor` in that
changeset. `livekit-capture` exposes neither and stays `patch`.

The writer changeset now says that the new data stream methods add
requirements to the generated Swift protocols and Kotlin interfaces, so
a hand-written conformer must implement them, which is why `livekit-ffi`
takes a minor bump in every changeset that adds methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
Two regression tests for a closer used after the incoming manager's run
loop stopped. Each test owns the run loop, waits for it to stop, and
then calls `close()` twice.

- `closer_after_shutdown_with_input_dropped_does_nothing`: the last
  `ManagerInput` is dropped, so the closer's weak handle cannot upgrade.
- `closer_after_shutdown_with_input_retained_does_nothing`: the input is
  kept and the manager stops on `InputEvent::Shutdown`, so the send goes
  to a channel that nobody receives from.

In both, `close()` returns without a panic, the only close event is the
one from the shutdown abort, and the reader fails with `AbnormalEnd`.
`close()` is synchronous, so returning shows that it does not block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`20523607` added a public `total_length` field to the core
`StreamTextOptions`. All its fields are public and it is not
`#[non_exhaustive]`, so the field broke exhaustive struct literals, and
`livekit` re-exports the type and `livekit-rpc` takes it in
`RpcTransport::send_text`.

The core `StreamTextOptions` is now exactly as on `524123ee`, and so is
the room-apis conversion that filled the field. The declared length goes
through a new method instead, which is purely additive:

    Manager::stream_text_with_total_length(options, total_length)

`stream_text(options)` calls it with `None`. The `core-modules`
`StreamTextOptions` record keeps its trailing `total_length = None`
field, which is additive for Swift and Kotlin callers, and the FFI
`stream_text` passes that field to the new method. `send_text` still
uses the length of the text it sends.

The changeset now lists `livekit-rpc` as `patch`, since nothing it
exposes changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`f367f24c` added a public `InputEvent::CloseStream` variant. `InputEvent`
is public and not `#[non_exhaustive]`, so the variant broke exhaustive
matches, and `livekit` re-exports the crate.

`InputEvent` is now as on `524123ee`, apart from the clippy `allow` from
`d8343986`. The manager's input queue carries a crate-private
`ManagerMessage` instead: `Event(InputEvent)` or
`CloseStream(StreamCloser)`. `ManagerInput::send` keeps its signature and
wraps the event, and so does the drop guard. `StreamCloser` holds a weak
handle to the same queue.

Using one queue keeps a close in order with the packets of its stream,
which a second channel that the run loop selects on would not. The
instance-number check, the weak handle, the synchronous `close()`, the
single close event and the shutdown behavior do not change, and the
existing tests pass unchanged.

`ManagerMessage` allows `clippy::large_enum_variant` like `InputEvent`,
because boxing the event would allocate for every inbound packet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The branch no longer breaks public Rust API, so no changeset needs a
breaking level. In this repo's knope setup, `major` on a 0.x crate bumps
the middle number and is the breaking level: `livekit-ffi` 0.12.83 went
to 0.13.0 on a `major` changeset. `minor` bumps only the last number:
`livekit-ffi` 0.12.82 went to 0.12.83 and `livekit-data-stream` 0.1.0
went to 0.1.1 on `minor` changesets. Recent additive features (capture
sources, frame metadata user data, data streams v2 for
`livekit-data-stream`) use `minor`, and fixes and dependents use `patch`.

So each changeset now uses:

- `minor` for a crate that gains public API: `livekit-data-stream`,
  `livekit-ffi`, and `livekit`, whose root re-exports the data stream
  `api` module and whose `data_stream` module re-exports the crate.
- `patch` for a fix (reader trailer attributes, the inline length check)
  and for a crate that only depends on the change (`livekit-capture`,
  `livekit-rpc`).

The progress changeset moves `livekit-data-stream` and `livekit` to
`minor` for that reason. The writer changeset keeps its sentence about
new methods adding requirements to the generated Swift protocols and
Kotlin interfaces, without tying it to a bump level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`livekit-ffi` is not published, so its Rust API may change, and UniFFI
0.31 renders argument defaults in every binding the repo generates.
The FFI therefore extends existing methods instead of adding siblings:

- `send_text`, `send_bytes` and `send_file` take a trailing
  `progress: Option<Arc<dyn StreamProgressDelegate>>`, with
  `#[uniffi::method(default(progress = None))]`. This replaces
  `send_text_with_progress`, `send_bytes_with_progress` and
  `send_file_with_progress`. The behavior is the same: one completion
  report for the one-shot sends, a report per chunk for files.
- Both writers' `close` takes `reason: Option<String>` and
  `attributes: HashMap<String, String>`, with
  `default(reason = None, attributes)`. `default(attributes)` uses the
  type's default, an empty map: `[:]` in Swift, `mapOf()` in Kotlin and
  `const {}` in Dart. This replaces `close_with_options`. With no
  arguments it sends the same trailer as before. `close_with_reason`
  stays as on the base.

Generated Swift, Kotlin and Dart keep the old call forms working:
`sendText(text:options:)`, `close()`, `closeStream()` in Kotlin.
`stream_text` still reads `total_length` from the record field, which
already defaults to `None`. The reader `close()` and `next_progress()`
stay new methods, because there is nothing to default.

The core keeps its additive methods, since Rust has no default
arguments. The FFI tests pass `None` or an empty map where Rust needs
the full argument list. The progress and writer changesets describe
the parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A compressed `send_file_with_progress` reported after every chunk with
the bytes read so far. When one read released several chunks, the value
repeated, and when the last read released a chunk, the whole file was
reported before the tail was sent. A 50 KB random file reported
`[32768, 40960, 50000, 50000]`, and still reported 50000 when the last
chunk failed.

The compressed branch now reports once after each drain of the encoder,
and only while the bytes read are below the file size. It sends the
tail with `write_chunk` and reports the whole file once, after the last
chunk was sent. The same file now reports `[32768, 40960, 50000]`. The
uncompressed path does not change.

Two new tests record what the transport and the callback saw, in order.
One checks that the values rise strictly and that the total comes after
the last chunk. The other fails the request that carries the last chunk
and checks that the total is never reported. The existing compressed
progress test expected one report per chunk, so it now asks for at
least two strictly rising reports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A host that released a reader without calling `close()` left the stream
registered in the incoming manager until a later packet failed to
deliver, so with no further packets `on_stream_closed` never fired.

Both FFI readers now implement `Drop`, which sends the same targeted
close as `close()` unless `close()` already ran. The closer only sends
on a channel, so this works on any thread, such as a Swift `deinit` or
a Kotlin cleaner. After a normal end the manager ignores it, because no
open stream has that instance number.

The new test drops an unread reader with no further packets and sees
the open count drop and one close event. Dropping a reader whose stream
already ended adds no event. The FFI tests passed 30 of 30 repeated
runs, including the older tests whose delegates drop readers at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A second `close()` on an FFI reader sent another close message to the
incoming manager and spawned another task to drop the core reader, both
of which did nothing. `close_reader` now returns at once when the
reader is already closed, and it sends the manager message itself, so
both readers share the check. The repeated-close test still sees one
close event.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`on_progress` returns no error, so UniFFI turns an exception from a
Kotlin or Dart implementation into a Rust panic, and the release
profile, which sets `panic = "abort"`, ends the process. The docstring
now says so; it reaches the generated Swift, Kotlin and Dart.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A test inside `incoming.rs`, where the private `inner` field is visible.
It starts a read on a stream with no data, waits until that read holds
the lock on the core reader, calls `close()`, and then waits, with a
timeout, until `inner` is `None`. The read ends with `AlreadyClosed`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
#1536 made every chunk and trailer carry the stream's destination
identities. This branch adds three send paths: closing a writer with
trailer attributes, compressed progress reporting in `write_file`, and
the FFI writer `close(reason, attributes)`. All three build packets
through `RawStream::write_chunk` or `RawStream::close`, which stamp the
destinations. These tests pin that down next to the #1536 tests:

- `writers_closed_with_trailer_attributes_target_every_packet`: a text
  writer to two recipients closed with attributes, and a byte writer
  closed with a reason and attributes.
- `writer_dropped_without_close_targets_its_trailer`: the trailer that a
  dropped writer sends from its spawned task.
- `compressed_send_file_with_progress_targets_every_packet`: a 50 KB
  compressed file, whose chunks go out both during the read and in the
  tail.
- The FFI `outgoing_writers_send_trailer_attributes` now targets "bob",
  and checks that all five header, chunk and trailer packets carry it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Changeset ✓

This PR includes a changeset covering all affected packages:

Package Bump
livekit major
livekit-capture patch
livekit-data-stream major
livekit-ffi minor
livekit-rpc major

pblazej and others added 5 commits October 22, 2026 12:35
- Remove `incoming_inline_stream_shorter_than_declared_errors_reader`:
  the core inline length test proves the check, and
  `outgoing_text_stream_declares_total_length` proves the FFI mapping.
- Remove `incoming_reader_info_shows_trailer_attributes`:
  `incoming_trailer_attributes_replace_header_attributes` covers it.
- Remove `incoming_reader_closed_twice_reports_one_close`, and close the
  byte reader twice in `incoming_byte_reader_close_ends_its_stream`.
- Remove the close-racing and id-reuse tests; the core `closer` tests
  own those cases.
- Remove `incoming_progress_merges_updates_between_calls`, which tested
  the tokio watch channel.
- Replace the `poll_once` helper with `FutureExt::now_or_never`.

`incoming_progress_ends_when_the_stream_fails` stays: a progress
consumer must not hang when its stream fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`next_chunk` returns straight from its biased `select!` arms. It no
longer drops the core reader itself when it sees the close; the task
that `close_reader` spawns does that once the read releases the lock,
which the test below proves.

The test in `incoming.rs` now reuses `manager_with_events`,
`open_text_stream` and `TIMEOUT` from the data stream tests, which
become `pub(super)`. It polls the read once with `now_or_never()` to
reach the pending state, instead of a hand-built header, a separate
delegate, and a spawned read with a `try_lock` spin. It still waits
until `inner` is `None`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
- The four inline length tests become one loop over compression that
  keeps every assertion: short is `Incomplete`, long and a declared 0
  are `LengthExceeded`, and a matching or undeclared length reads.
- The two shutdown tests become `closer_after_shutdown_does_nothing`,
  which covers both weak-handle branches in one manager: the send fails
  while the input is kept after `Shutdown`, and the upgrade fails after
  the input is dropped. `wait_for_stop`, `count_closes` and the open
  helper are inlined.
- Remove `send_file_reports_progress_before_compression`. Its "at least
  two reports" assertion moves into
  `compressed_send_file_reports_rising_progress_and_the_total_last`.
- Remove `writers_closed_with_trailer_attributes_target_every_packet`,
  since the FFI `outgoing_writers_send_trailer_attributes` covers the
  new close path, and `writer_dropped_without_close_targets_its_trailer`,
  which tested code this branch does not touch.

`compressed_send_file_with_progress_targets_every_packet` stays: it is
the only destination check on the rewritten compressed path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`StreamCloser::new` only assigned three fields. The manager and
`detached()` now use struct literals, and `input` is `pub(crate)` like
the other two fields. The public type and `close()` do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`write_file_chunk` had two callers, both in the uncompressed branch of
`write_file`, which now call `write_chunk` and report progress inline.
The empty-file report moves into that branch, so the compressed branch
no longer returns early. The reported values do not change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
@pblazej
pblazej marked this pull request as ready for review October 22, 2026 10:58
@pblazej
pblazej requested a review from ladvoc as a code owner October 22, 2026 10:58
@pblazej
pblazej requested a review from changt October 22, 2026 11:17
pblazej and others added 4 commits October 22, 2026 16:10
The send_file docstrings said that progress is reported after each
chunk. That is true only for an uncompressed file. A compressed file
reports after each encoder drain. In both modes, the whole file is
reported only after its last chunk was sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The closer test now also closes a stream before its final chunk, and
between the final chunk and the trailer. In both orders, the manager
reports one close, the read fails with AlreadyClosed and no other
error, and the stream ends. The FFI test that covered these orders was
removed in an earlier trim, so this test is now their only coverage.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
trailer_with_reason_errors_abnormal_end now declares 10 bytes and sends
5, so it also checks that the trailer's reason wins over the short
length. It fails with the old check order, so the separate
trailer_reason_wins_over_a_short_declared_length test is deleted. Its
compressed case tested no other branch, because handle_trailer has no
compression path.

The closer test now names its "trailer" step, and an unknown step
panics, so a typo in the step table cannot pass as a trailer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The crate-private write_file doc repeated the progress rules of
Manager::send_file_with_progress. It now links to that method and keeps
only the two facts that the method does not state: the values rise
strictly, and an empty uncompressed file reports once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
@pblazej
pblazej requested a review from lukasIO October 23, 2026 11:04
Comment on lines +152 to +162
/// What the manager's input queue carries. A close from a [`StreamCloser`] shares the queue with
/// the [`InputEvent`]s, so it stays in order with the packets of its stream, without being a
/// public [`InputEvent`] variant.
#[allow(clippy::large_enum_variant)] // Boxing the event would allocate for every inbound packet.
pub(crate) enum ManagerMessage {
Event(InputEvent),
/// End one open stream on behalf of its reader. Ignored unless that exact stream, not a later
/// one that reuses its id, is still open.
CloseStream(StreamCloser),
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Instead of wrapping InputEvent in a higher level ManagerInput enum, is there a reason why InputEvent::CloseStream couldn't be introduced instead?

Or, another idea - it might make sense to follow the pattern that alan has been working on in the background in the data tracks manager where a separate out of band CancellationToken is used for cancelation that is decoupled from the event streams. So more concretely, there would be one cancellation token per stream I think?

In the data tracks implementation this is important because data tracks uses bounded channels. While today data streams use unbounded channels, I think the goal would be to move data streams to use bounded channels so aiming for these two interfaces to be consistent IMO would be a good idea.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

InputEvent is public and exhaustive (no #[non_exhaustive]), so a CloseStream variant fails cargo semver-checks with enum_variant_added; that is why the close went through a private wrapper. I switched to your second idea in 746ef09: one CancellationToken per stream, which the manager watches out of band through a FuturesUnordered. That removes the wrapper enum, the weak sender and the instance counter, and all existing tests pass unchanged, plus a new one for a close that races queued packets. Manager shutdown stays in band for now; when data streams move to bounded channels, the shutdown token and the cancellation-aware sends can follow Alan's branch in the same change.

@1egoman 1egoman Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, InputEvent should have been made #[non_exhaustive], that was an oversight. IMO it's worth adding to both InputEvent (and OutputEvent) even if it's a breaking change as otherwise we'll never be able to add more input events 😞

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 6a39827: InputEvent and OutputEvent are #[non_exhaustive] now. The two exhaustive matches in the workspace (livekit room event forwarding and the FFI incoming module) got wildcard arms that log unknown events, and the livekit-data-stream and livekit changesets are major. There are no public event enums on the outgoing side, so nothing else needed the attribute.

Comment on lines +304 to +315
/// Like [`Self::send_file`], and calls `on_progress` as the file goes out.
///
/// Progress counts file bytes before compression, against the file size. An uncompressed file
/// reports after each chunk is sent. A compressed file reports after each encoder drain, so it
/// counts the input the encoder consumed, which can run ahead of the chunks sent. Either way,
/// the whole file is reported only after its last chunk was sent.
pub async fn send_file_with_progress(
&self,
path: impl AsRef<Path>,
options: StreamByteOptions,
remote_participant_registry: &dyn RemoteParticipantRegistry,
mut on_progress: impl FnMut(StreamProgress) + Send,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: Is there a reason that on_progress couldn't be added to StreamByteOptions as an optional field? It looks like StreamByteOptions has a builder interface so this could be done without introducing breaking struct changes.

Just generally, I worry about introducing too many different variants like send_file_with_progress because if we continue down this path, then quickly you need methods to handle all possible combinations like send_file_with_x_with_progress.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The builder does not make this non-breaking: every field of StreamByteOptions and StreamTextOptions is pub and the structs are not #[non_exhaustive], so a new field fails cargo semver-checks with constructible_struct_adds_field (I tried both on_progress and total_length). I agree with the direction. At the next breaking release we should make both option structs #[non_exhaustive], add on_progress and total_length there, split one-shot send options from incremental stream options as JS does, and delete the two _with_ methods. Until then these two are the only _with_ methods, and the FFI surface already uses defaulted parameters instead.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In general in the rust sdk, due to some decisions made earlier on in the project we're working to undo, there's been more of a tolerance for breaking changes to the public api interface. Because of this I am of the opinion this should also be a breaking change. All further struct construction should be through the builders (this is what the docs recommend) and we're trying to aim that way going forward to reduce the frequency of breaking changes like this.

cc @ladvoc just as a sanity check, do you agree with me here? Rephrased - do the suggestion in blaze's comment now, even though it's technically a breaking change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, done in 34b7150: every outgoing options struct is #[non_exhaustive] now, so construction goes through the builders. One-shot sends take new types, send_text takes SendTextOptions and send_bytes/send_file take SendByteOptions, both with compress and an on_progress callback; stream_text/stream_bytes keep StreamTextOptions/StreamByteOptions with total_length and without the compress field they ignored. The two _with_ methods are gone. The FFI records and the generated Swift and Kotlin surface do not change. Changesets are major for livekit-data-stream, livekit and livekit-rpc (the RpcTransport::send_text parameter type).

Comment on lines +258 to 271
/// Waits for the next progress update, or returns `None` once the stream has ended.
///
/// Progress counts the bytes received from the sender, after decompression, not the bytes
/// the app has read: a chunk counts as soon as it arrives, before `next()` returns it. The
/// first call returns the current progress at once. Updates that arrive between two calls are
/// merged into the latest one.
pub async fn next_progress(&self) -> Option<StreamProgress> {
next_progress(&self.progress, &self.closed).await
}

/// Returns the next chunk, or `None` once the stream has closed.
pub async fn next(&self) -> Result<Option<String>, DataStreamError> {
Ok(self.inner.lock().await.next().await.transpose()?)
next_chunk(&mut *self.inner.lock().await, &self.closed).await
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Could you abstract this into one function that both use instead of next_progress / next_chunk?

I added a very similar utility into livekit-rpc recently, maybe this could get moved to livekit-common and used in both spots?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in af82f1c: next_chunk and next_progress now share one private close-biased helper in this file. Your wait_with_disconnect_grace has the opposite priority (the reply wins over the disconnect) plus a deadline and a grace period, so the shared part is only a biased select!. Moving it to livekit-common would also add tokio to that crate, so I left it where it is.

pblazej and others added 6 commits October 26, 2026 10:20
next_chunk and next_progress each had their own biased select between
the reader's close token and the next item. Both now use one private
helper, unless_closed, which returns None once the close token is
cancelled and lets the close win a tie. The behavior does not change:
a pending next() still fails with AlreadyClosed on close, and
next_progress() still returns None.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
A StreamCloser now holds only its stream's CancellationToken, and
close() cancels it. The incoming manager keeps one future per open
stream that yields the stream id once the token is cancelled, and its
run loop polls those futures before the input queue. The descriptor
holds a DropGuard for the token, so any removal of the stream also
cancels it and its future ends. A close for an id that a later stream
reuses does nothing, because the later stream has its own token.

This removes the ManagerMessage wrapper, the weak input sender in each
closer and the per-stream instance counter. ManagerInput carries plain
InputEvents again, as on main. InputEvent::Shutdown stays the way to
stop the manager.

A close is no longer ordered with the packets still in the input queue.
Those packets are discarded, so a queued trailer does not merge its
attributes. Chunks that the manager already handed to the reader are
still read before the AlreadyClosed error.

livekit-data-stream now depends on tokio-util 0.7.19, the first
version with DropGuard::token, and on the tokio macros feature for
select!.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The test hands the first chunk to the reader, queues a second chunk,
and then closes the stream. The reader gets the first chunk, then
AlreadyClosed, then the end of the stream, and never the second chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
livekit-data-stream asked for tokio-util 0.7.19 and livekit-ffi for
0.7.18. Both now use a shared workspace entry at 0.7.19, the first
version with DropGuard::token. The lockfile already has 0.7.19, so it
does not change.

The incoming manager had its own private DropGuard struct, which sends
InputEvent::Shutdown when the last ManagerInput is dropped. It is now
ShutdownOnDrop, so tokio-util's DropGuard can be imported by its name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
The AnyStreamReader::from doc said that the StreamCloser sends
something. It now says that the reader keeps the closer to cancel the
stream.

The docs for the manager's close futures said there is one per open
stream. A future ends when its descriptor is dropped and leaves the set
on the next loop pass, so the docs now say that, and that shutdown
drops the set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
`incoming::InputEvent` and `incoming::OutputEvent` in
livekit-data-stream are now #[non_exhaustive], so later versions can add
events without another breaking change. A match on either enum outside
the crate needs a wildcard arm.

The two matches on OutputEvent outside the crate, the room's incoming
data stream task in livekit and the FFI delegate forwarder, now log an
unknown event at debug level and drop it. Known events behave as
before.

cargo semver-checks reports enum_marked_non_exhaustive for both enums,
so the reader-close changeset now uses the breaking level for
livekit-data-stream and for livekit, which re-exports the crate as
livekit::data_stream.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: omnigent <noreply@omnigent.ai>
devin-ai-integration[bot]

This comment was marked as resolved.

pblazej and others added 3 commits October 27, 2026 08:52
Co-authored-by: omnigent <noreply@omnigent.ai>
Co-authored-by: omnigent <noreply@omnigent.ai>
Comment on lines 1005 to 1009
pub async fn send_bytes(
&self,
data: impl AsRef<[u8]>,
options: StreamByteOptions,
options: SendByteOptions,
) -> StreamResult<ByteStreamInfo> {

@1egoman 1egoman Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thought: I think this is my biggest worry with these updates. I hadn't realized when I made the breaking field change comment you would take it this far - ie, break the Stream*Options out into Send*Options / Stream*Options. I had only been proposing in my comment that the progress field be folded in.

That being said, I think at some point we really do need to do this though, so maybe now is the time. Not having these two distinct types has made it impossible to properly disambiguate between options that send needs and options that stream needs, which is not great.

However, it's a bigger breaking change as somebody using data streams as the docs recommend today would have to swap StreamByteOptions for SendByteOptions all over the place.

@ladvoc Thoughts on this from a rust perspective, do you think it's worth making this breaking change now?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am all for making available options contextual—I have seen users confused by this. I think we can accept the breaking change in Rust, but is it feasible to update JS and other clients now?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked the other SDKs: JS (SendTextOptions / SendBytesOptions / SendFileOptions vs StreamTextOptions / StreamBytesOptions), Flutter (four separate classes) and Python (keyword-only parameters that already differ per method: compress only on sends, total_size only on streams) already have this shape, so nothing changes there. Swift and Android (#997) still pass Stream*Options to the sends; both can add Send* types and keep the current overloads as deprecated forwarders, so no source break, and #997 can change before it merges. The FFI records stay shared for now (progress moves into them per the other thread); mirroring the split there fits the room-api uniffi work.

@1egoman 1egoman Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

^ Yes, most other SDKs use distinctly different options - I didn't realize that swift and android still pass Stream*Options though, that is unfortunate and also should be mgirated at some point IMO

Comment on lines +237 to +241
let mut stream = Self::new_with_topic(options.topic);
stream.attributes = options.attributes;
stream.destination_identities = identities(options.destination_identities);
stream.id = options.id;
stream.sender_identity = options.sender_identity.map(Into::into);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Is it worth abstracting this identities function like this when it's just .into_iter().map(Into::into).collect()? It's basically equivalent to the sender_identity case, IMO just inline it both here and in the StreamByteOptions / SendTextOptions / StreamByteOptions ones below.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 318d87d: the helper is gone and each conversion is the inline .into_iter().map(Into::into).collect().

Comment on lines +184 to +190
pub async fn send_file(
&self,
path: String,
options: StreamByteOptions,
progress: Option<Arc<dyn StreamProgressDelegate>>,
) -> Result<ByteStreamInfo, DataStreamError> {
Ok(self.manager.send_file(path, options.into(), &*self.registry).await?.into())
let mut options: ds_api::SendByteOptions = options.into();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: I think it would be good if possible to merge progress into options: StreamByteOptions (and also with the other corresponding versions), since StreamByteOptions is defined locally and not shadowed from livekit I think this should be fairly possible.

The reason why I think this could be a fairly good idea to do now is because likely as part of the livekit-ffi -> uniffi migration, the data streams interface that is exposed will be mirrored in the room-api uniffi interface. So IMO it would be good to make sure it is as clean as possible so that we can aim to mirror it with this upcoming work, ideally factor out bits that both interfaces can consume, and not have to further refine the interface in another round of breaking changes later.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 7d0b8d9: progress is now an optional field (default null) on the FFI StreamTextOptions / StreamByteOptions records, and the three send methods lost the extra parameter; stream_text / stream_bytes ignore it, which the field doc says. Kept the records shared for now, so the Swift and Kotlin call sites only change in the record initializer; splitting them into Send* / Stream* to mirror the core would fit the room-api uniffi work. One side effect: the generated Swift records lose Equatable/Hashable because of the callback field.

pblazej and others added 3 commits October 28, 2026 10:20
Co-authored-by: omnigent <noreply@omnigent.ai>
Co-authored-by: omnigent <noreply@omnigent.ai>
Co-authored-by: omnigent <noreply@omnigent.ai>
@pblazej
pblazej merged commit f1a6ce9 into main Oct 28, 2026
33 checks passed
@pblazej
pblazej deleted the blaze/dsv2-ffi-gaps branch October 28, 2026 10:07
MaxHeimbrock added a commit that referenced this pull request Oct 29, 2026
An agent registered without a name is dispatched automatically into every
new room, so a token without roomConfig.agents can still bring an agent
in. Gating the timeout on the token's explicit dispatch left a session
with no agent stuck in Connecting forever. Arm it unconditionally; a late
agent still replaces Failed(Timeout).

Also update two e2e tests to pass SendTextOptions to send_text, whose
signature changed in #1558.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxHeimbrock added a commit that referenced this pull request Oct 29, 2026
An agent registered without a name is dispatched automatically into every
new room, so a token without roomConfig.agents can still bring an agent
in. Gating the timeout on the token's explicit dispatch left a session
with no agent stuck in Connecting forever. Arm it unconditionally; a late
agent still replaces Failed(Timeout).

Also update two e2e tests to pass SendTextOptions to send_text, whose
signature changed in #1558.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxHeimbrock added a commit that referenced this pull request Nov 2, 2026
An agent registered without a name is dispatched automatically into every
new room, so a token without roomConfig.agents can still bring an agent
in. Gating the timeout on the token's explicit dispatch left a session
with no agent stuck in Connecting forever. Arm it unconditionally; a late
agent still replaces Failed(Timeout).

Also update two e2e tests to pass SendTextOptions to send_text, whose
signature changed in #1558.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxHeimbrock added a commit that referenced this pull request Nov 3, 2026
An agent registered without a name is dispatched automatically into every
new room, so a token without roomConfig.agents can still bring an agent
in. Gating the timeout on the token's explicit dispatch left a session
with no agent stuck in Connecting forever. Arm it unconditionally; a late
agent still replaces Failed(Timeout).

Also update two e2e tests to pass SendTextOptions to send_text, whose
signature changed in #1558.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants