Skip to content

Data streams v2 (2/5): read incoming data streams through FFI readers - #330

Draft
1egoman wants to merge 4 commits into
ds/1-test-harnessfrom
ds/2-receive-fix
Draft

1egoman wants to merge 4 commits into
ds/1-test-harnessfrom
ds/2-receive-fix

Conversation

@1egoman

@1egoman 1egoman commented Nov 30, 2026 •

Copy link
Copy Markdown

Part 2 of 5 of the data streams v2 stack. Merge in order; each part is mergeable on its own.

  1. Data streams v2 (1/5): conformance test harness #329: Conformance test harness
  2. Data streams v2 (2/5): read incoming data streams through FFI readers #330: Read incoming data streams through FFI readers (fixes receiving from other SDKs) 👈 this PR
  3. Data streams v2 (3/5): add sendText / sendBytes / sendFile #331: Add sendText / sendBytes / sendFile
  4. Data streams v2 (4/5): add ByteStreamReader::writeToFile and a receive size limit #332: Add ByteStreamReader::writeToFile and a receive size limit
  5. Data streams v2 (5/5): move writers to FFI writer handles; add streamText / streamBytes #333: Move writers to FFI writer handles; add streamText / streamBytes

This stack replaces #321, #322 and #325 (same code, reordered so each step stands on its own).

Fixes receiving data streams from every other LiveKit SDK. This changes no public API beyond small additions: DataStreamError, reader->close(), and ByteStreamReader::readAll().

The bug

Since livekit-ffi 0.15.0, every FFI client advertises data streams v2. So Python, Node, JS, Rust and Swift send C++ participants single-packet ("inline") and deflate-compressed streams. The C++ SDK rebuilt incoming streams from the low-level stream_header/chunk/trailer events, and that path:

  • never delivered inline streams (readAll() hung);
  • handed compressed chunks to the app as raw deflate bytes;
  • appended duplicate chunks;
  • never reported length, gap or close-reason errors;
  • left streams open forever when a participant disconnected.

The FFI also handed C++ an owned reader handle for every incoming stream, which C++ ignored. So each stream's content stayed buffered in the FFI for the life of the process.

The fix

  • Room consumes text/byte_stream_opened:
    • an unhandled topic drops the reader handle;
    • a handled topic starts read_incremental and routes the *_stream_reader_events to the reader.
  • The low-level packet events are ignored. The Rust core now does reassembly, decompression and validation.
  • Readers throw DataStreamError when a stream ends abnormally, after returning the chunks already received. DataStreamError derives from std::runtime_error. Abnormal ends include a close reason, a length mismatch, a missed chunk, the size limit, or a disconnect.
  • Room shutdown wakes blocked readers with "Disconnected while receiving".
  • Readers gain close(), and log a warning if they would block on the FFI callback thread.
  • ByteStreamReader gains readAll() to match TextStreamReader.
  • *StreamOpenedEvent::reader_handle was never filled in (it was always 0). It is now documented as deprecated.

Behaviour change: a stream that ends abnormally used to look complete, handing back silently truncated data. It now throws.

Nothing gets more broken: writers are unchanged and still send v1 packets, which the FFI readers accept, so C++-to-C++ streams keep working.

Tests

On the parent branch (and main), 22 of the 27 receive conformance tests fail:

  • the other 12 of the 17 v1 tests;
  • all 10 v2 tests.

With this PR, all pass.

File Added here
test_data_stream_conformance_receive_v1.cpp 12 v1 tests: too few/many bytes, duplicate chunk, missed chunk, close reason, orphan packets, remote writers with a reason or the wrong length, sender/receiver disconnects
test_data_stream_conformance_receive_v2.cpp 10 v2 tests: inline (compressed and not, empty, large), multi-packet compressed text and bytes, UTF-8 reframing, attachments
test_data_stream_conformance_receive_api.cpp 4 reader->close() tests
test_data_streams.cpp trailer attributes, abnormal close, receiver disconnect, close() waking a read, reader handles released
test_data_stream.cpp (unit) reader state machine and info conversion
Rust incoming/manager.rs tests covered here
Rust test C++ test
v1_text_stream_round_trips DataStreamReceiveV1Test.V1TextStreamRoundTrips (part 1)
v1_byte_stream_round_trips DataStreamReceiveV1Test.V1ByteStreamRoundTrips (part 1)
v1_merges_trailer_attributes DataStreamReceiveV1Test.V1TrailerAttributesMergedAfterClose, .RemoteTextWriterRoundTripsWithTrailerAttributes (part 1)
v1_trailer_attributes_merged_after_close DataStreamReceiveV1Test.V1TrailerAttributesMergedAfterClose (part 1)
empty_chunks_are_ignored DataStreamReceiveV1Test.EmptyChunksAreIgnored (part 1)
v1_errors_when_too_few_bytes DataStreamReceiveV1Test.V1ErrorsWhenTooFewBytes, .RemoteWriterTooFewBytesErrors
v1_errors_when_too_many_bytes DataStreamReceiveV1Test.V1ErrorsWhenTooManyBytes, .RemoteWriterTooManyBytesErrors
v1_duplicate_chunk_dropped DataStreamReceiveV1Test.V1DuplicateChunkDropped
error_close_emits_stream_closed DataStreamReceiveV1Test.V1MissedChunkErrors
trailer_with_reason_errors_abnormal_end DataStreamReceiveV1Test.V1TrailerWithReasonErrorsAbnormalEnd, .RemoteWriterCloseWithReasonErrorsAbnormalEnd
trailer_for_unopened_stream_emits_no_stream_closed DataStreamReceiveV1Test.OrphanChunkAndTrailerAreIgnored
chunk_for_an_unopened_stream_reports_no_topic DataStreamReceiveV1Test.OrphanChunkAndTrailerAreIgnored
errors_open_streams_on_sender_disconnect DataStreamReceiveV1Test.SenderDisconnectErrorsOpenStreams
abort_emits_stream_closed DataStreamReceiveV1Test.SenderDisconnectErrorsOpenStreams
abort_only_affects_matching_sender DataStreamReceiveV1Test.SenderDisconnectOnlyAffectsItsOwnStreams (needs LIVEKIT_TOKEN_C)
shutdown_errors_open_streams DataStreamReceiveV1Test.ReceiverDisconnectErrorsOpenStreams
dropping_all_inputs_errors_open_streams DataStreamReceiveV1Test.ReceiverDisconnectErrorsOpenStreams (closest C++ equivalent)
v2_inline_uncompressed_text / _byte DataStreamReceiveV2Test.V2InlineUncompressedText / Byte
v2_inline_compressed_text / _byte DataStreamReceiveV2Test.V2InlineCompressedText / Byte
v2_inline_zero_length_text DataStreamReceiveV2Test.V2InlineZeroLengthText
v2_multipacket_compressed_text DataStreamReceiveV2Test.V2MultipacketCompressedText
v2_multipacket_compressed_byte_stream DataStreamReceiveV2Test.V2MultipacketCompressedByteStream
v2_compressed_text_reframes_multibyte_utf8 DataStreamReceiveV2Test.V2CompressedTextReframesMultibyteUtf8
text_stream_with_attachments_round_trips DataStreamReceiveV2Test.TextStreamWithAttachmentsRoundTrips
closer_ends_an_open_stream_once DataStreamReceiveApiCloseTest.CloseEndsAnOpenStreamOnce
closer_discards_packets_still_queued DataStreamReceiveApiCloseTest.CloseDiscardsQueuedChunks
closer_spares_a_later_stream_with_the_same_id DataStreamReceiveApiCloseTest.CloseSparesALaterStreamWithTheSameId
closer_after_shutdown_does_nothing DataStreamReceiveApiCloseTest.CloseAfterDisconnectIsHarmless

Not portable end to end; the Rust crate's own tests cover these:

  • Malformed v2 packets: the FFI can only hand-build v1 packets. This covers v2 gaps, compressed duplicates, too few / too many bytes on compressed streams, unknown compression, and inline length mismatches.
  • Per-packet encryption mismatches.
  • Progress: there is no FFI progress API.
  • Manager internals: open-stream counts, StreamClosed events, and internal-topic filtering.

The size-limit tests come in part 4.

Verification (local, macOS arm64, livekit-server --dev)

  • Unit tests: 376/376.
  • Full integration suite: 106 pass, 3 fail (see below), 1 skip. All 39 data stream tests pass.
  • Python livekit 1.3.0 → C++: a short and a 50 KB send_text arrived intact in 3/3 runs. On main, 0/3: neither stream arrives.
  • clang-tidy (local 23): one warning not on main, bugprone-exception-escape on ~Room. The tool traces a possible std::length_error through the LK_LOG_ERROR in its catch block. ~Room itself is unchanged, the check is not error-level, and the same code passed CI's clang-tidy 19 on Data streams: receive via FFI readers; add sendText / sendBytes / sendFile #321.
  • Every commit builds and passes the unit tests.
  • Formatting: clang-format is clean on all changed files. Docs build OK. The release symbol leak check is OK.
  • The 3 failing integration tests are the DataTrackE2ETest schema tests (DefineAndGetSchema, DefineAndGetCustomSchemaEncoding, DefineDuplicateSchemaFails). They fail on main on this machine too, and the 1 skip is the token-server test.
  • Windows and Linux are covered only by CI.

🤖 Generated with Claude Code

1egoman and others added 4 commits November 30, 2026 20:41
Incoming data streams were rebuilt from the low-level stream_header/chunk/
trailer events. Since livekit-ffi 0.15.0 always advertises data streams v2,
other SDKs send C++ participants single-packet and deflate-compressed
streams, which that path can't read: inline streams hang readAll() forever
and compressed chunks arrive as raw deflate bytes. It also appended
duplicate chunks, never reported length, gap or close-reason errors, and
left streams open when a participant disconnected. The FFI also handed C++
an owned reader handle for every incoming stream, which C++ ignored, so
every stream's content stayed buffered in the FFI for the life of the
process.

- Room consumes text/byte_stream_opened: unhandled topics drop the reader
  handle; handled topics start read_incremental and route the resulting
  *_stream_reader_events (keyed by reader handle) to the reader. The
  low-level stream_*_received events are now ignored.
- Readers surface abnormal ends (sender close reason, length mismatch,
  missed chunk, size limit, disconnect) as DataStreamError, which derives
  from std::runtime_error, after draining buffered chunks. They merge
  end-of-stream attributes into info() on the reading thread and gain
  close(); ByteStreamReader gains readAll() to match TextStreamReader.
- Room shutdown wakes blocked readers with a "Disconnected while
  receiving" error.
- Readers warn when they would block on the FFI callback thread.

TextStreamOpenedEvent / ByteStreamOpenedEvent::reader_handle was never
populated and stays 0; it is now documented as deprecated. Writers are
unchanged: the FFI readers still accept the v1 packets they send.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports the rest of the Rust incoming-manager tests a v1 (multi-packet,
uncompressed) sender can reproduce: too few / too many bytes against
total_length, duplicate chunks, chunk gaps, trailer reasons, orphan
packets, remote writers that close with a reason or the wrong length,
and sender or receiver disconnects mid-stream.

All 12 fail without the previous commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports the Rust incoming-manager tests for data streams v2 as other SDKs
send them: inline streams (compressed and uncompressed, empty, large but
highly compressible), multi-packet compressed text and byte streams,
UTF-8 reframing of decompressed text, and text streams with attachments.

All 10 fail without the FFI reader port: inline streams are never
delivered and compressed chunks arrive as raw deflate bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ports the Rust incoming-manager closer tests through
TextStreamReader::close(): closing ends an open stream once, discards
queued chunks, spares a later stream that reuses the id, and is harmless
after disconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@1egoman

1egoman commented Nov 30, 2026

Copy link
Copy Markdown
Author

CI for this branch (manually dispatched, since ci.yml only runs on PRs into main): https://github.com/livekit/client-sdk-cpp/actions/runs/46380667544

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.

1 participant