Skip to content

Fix data stream sender counting book keeping logic - #2236

Open
1egoman wants to merge 6 commits into
mainfrom
fix/data-stream-sender-accounting
Open

1egoman wants to merge 6 commits into
mainfrom
fix/data-stream-sender-accounting

Conversation

@1egoman

@1egoman 1egoman commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Overview of problem

I've recently made a bunch of data stream updates to further restrict data stream validation in #2215 and #2230.

Both of these were conceptually good changes, but they inadvertently broke data streams being sent on behalf of other users, which is heavily used in agent transcriptions. Because of this, I have reverted #2230 and this PR is effectively a do-over of that one which doesn't suffer from these transcription issues.

#2215 - Participant identity validation \wouldn't always pass

  • In this PR I checked directly that streamController.sendingParticipantIdentity !== participantIdentity, where participantIdentity is the identity from the actual sender of the SFU packet.

#2230 - Keying by participant identity won't work when the participant identity can differ across the stream lifecycle

  • In this PR I switched to storing a two level map (Map<string /* participant id */, Map<string /* stream id */, StreamController>>), indexing by participant id THEN stream id.
  • In normal use, a data stream would be looked up by the sending participant first, then the stream id
  • However, because of the previously mentioned inconsitient participant identity rewriting behavior, the lookup always fails for chunks and trailers that were sent on behalf of another participant

Solution

  • Unlike before where streamController.sendingParticipantIdentity was set immediately, now when receiving a text header which the SFU marked generated, no packet sender is set at first. The first chunk or trailer from a participant allowed to send on others' behalf (an agent, via Participant.isAgent) sets this instead and "claims" the stream.
  • The sender check still protects these streams. After an agent claims a stream, packets from anyone else, including a second agent, are dropped. Agent packets are still rejected on streams whose header isn't marked generated, and non-agents can never claim one.
  • When either the participant the data stream is attributed to OR the agent sending it disconnects, the stream is closed.
  • As part of this I'm reintroducing the changes from fix(data-streams): key open incoming streams by sender, then stream id #2230, but via the method that shijing had originally suggested (seperate Map<string /* participant id */, number /* open stream count */> state). The double level Map that fix(data-streams): key open incoming streams by sender, then stream id #2230 introduced is no longer part of this.
  • Also as part of this, I'm reintroducing the "too many streams open for aparticipant" error log throttling from fix(data-streams): key open incoming streams by sender, then stream id #2230. It logs the first drop and then every 100th, with a running total, instead of one error per dropped header.

…te map

Rebuilds the intent of #2230 without keying streams by the identity on each packet. Checking the
per-participant limit no longer scans every open stream: a map from sender identity to open stream
count sits next to the controller maps, so the check is a single lookup. Every insertion and
removal goes through addStream and removeStream, which keep the counts in step, and a sender's
entry is removed once its count reaches zero. The count is keyed by the identity the stream was
registered under, never by the identity on the packet that ends it.

Dropped headers over the limit are logged on the first drop and then every 100th, with the running
number dropped, so a participant flooding headers at the cap cannot flood the logs too.

Tests cover every path that ends a stream (clean and abnormal trailers, encryption mismatch on a
chunk or trailer, the reader aborting, the sender disconnecting, the room disconnecting), that byte
and text streams share one limit, that inline streams are not counted, and the log throttle.
…icipant

When an agent publishes a text stream under another participant's identity (for example a
user's speech-to-text on lk.transcription), the SFU keeps the claimed identity on the header and
marks it generated, but stamps the chunks and trailer with the agent's own identity. The sender
check added in #2215 compared every chunk and trailer to the header's identity, so it dropped all
of them and these streams never completed.

The controller maps now hold a Descriptor per stream id, like IncomingDataTrackManager does,
replacing the StreamController type. Alongside the controller, a Descriptor records the identity
whose packets the stream accepts (packetSenderIdentity) separately from the identity it is
attributed to (sendingParticipantIdentity). The two are the same for every stream except a
generated text header, which starts with no accepted sender: the first chunk or trailer from a
participant allowed to send on others' behalf claims the stream, and only that participant's
packets are accepted after that. Chunk and trailer identities are asserted by the SFU, and only
such a participant may claim, so a participant that saw the header still cannot write into the
stream. The manager takes that permission as a canSendStreamOnOthersBehalf constructor callback,
which the dataStreams extension wires to Participant.isAgent, since the SFU only lets agents
publish under another identity.

The stream still counts against the participant it is attributed to, and a participant
disconnecting now also errors the streams it was sending on someone else's behalf.
Rather than replacing StreamController with a manager-local Descriptor type,
add packetSenderIdentity to the existing StreamController and go back to the
byteStreamControllers / textStreamControllers maps. startTime is set again and
endTime kept, so the type's shape only grows.
…Count

Add an @internal getOpenStreamCount(identity) and use it for every count
lookup, in the manager and in the tests, instead of reaching into the private
openStreamCounts map.
It had a single caller and is now a one-line comparison against
getOpenStreamCount.
@changeset-bot

changeset-bot Bot commented Nov 6, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4156b80

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
livekit-client Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@devin-ai-integration devin-ai-integration Bot left a comment

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.

Devin Review found 1 potential issue.

1 flag not posted on this PR by your GitHub settings — view it in Devin Review. (Configure)

Devin Review

Comment on lines +538 to +543
if (
streamController.packetSenderIdentity === undefined &&
this.canSendStreamOnOthersBehalf(participantIdentity)
) {
streamController.packetSenderIdentity = participantIdentity;
}

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.

🟥 First agent hijacks generated text streams

After seeing a generated header, another agent can send the first chunk or trailer and claim packetSenderIdentity. The intended agent's packets are then dropped, allowing forged or truncated transcriptions.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

@1egoman 1egoman Nov 6, 2026 •

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.

Yes, this is a known issue, but I'm not sure there's really a way to address this issue given the inconsistent way the SFU rewrites participant identities today.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
dist/livekit-client.esm.mjs 116.74 KB (+0.23% 🔺)
dist/livekit-client.umd.js 126.16 KB (+0.27% 🔺)
dist/core/core.mjs 78.96 KB (0%)

Comment on lines +2092 to +2108
describe('Open stream accounting', () => {
it("frees the sender's slot when the stream's trailer arrives", async () => {
// Allow a single open stream per sender, so a slot that is never freed would keep alice's
// next header out.
const manager = new IncomingDataStreamManager({ maxOpenStreamsPerParticipant: 1 });
manager.setConnected(true);
const readers: Array<TextStreamReader> = [];
manager.registerTextStreamHandler('my-topic', (reader) => readers.push(reader));

// Alice opens a stream, which takes her only slot.
manager.handleDataStreamPacket(headerPacket('s1', 'textHeader'), Encryption_Type.NONE);
expect(manager.getOpenStreamCount('alice')).toEqual(1);

// The trailer ends the stream cleanly.
manager.handleDataStreamPacket(trailerPacket('s1'), Encryption_Type.NONE);
expect(await readers[0].readAll()).toEqual('');

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.

Note to reviewers: It is worth scanning through these tests. They should be very readable (broken down into bite size chunks with comments above each) and make it easy to understand some of the situations that previously were breaking.

Comment thread src/room/types.ts
Comment on lines 141 to 164
export interface StreamController<T extends DataStream_Chunk> {
info: BaseStreamInfo;
/** Controller of the `ReadableStream` the stream's reader consumes. */
controller: ReadableStreamDefaultController<T>;
startTime: number;
endTime?: number;
/**
* The identity on the stream's header: who the stream is attributed to, and whose open-stream
* count it occupies.
*/
sendingParticipantIdentity: string;
/**
* The identity whose chunks and trailer the stream accepts.
*
* The same as `sendingParticipantIdentity` for every stream except one sent on behalf of
* another participant, such as an agent publishing a user's speech-to-text on
* `lk.transcription`. The SFU keeps the claimed identity on such a text header, and marks it
* `generated`, but stamps the chunks and trailer with the real sender's identity. The real sender
* is not named anywhere in the header, so this starts out unset and the first chunk or trailer
* from a participant allowed to send on others' behalf claims the stream; see
* `IncomingDataStreamManager.validateStreamPacket`.
*/
packetSenderIdentity: string | undefined;
}

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.

Note to reviewers: This would be good context to have before reading the rest of this code. The breakdown between sendingParticipantIdentity and packetSenderIdentity is important to understand.

@1egoman 1egoman mentioned this pull request Nov 6, 2026

@lukasIO lukasIO left a comment

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.

How about simply allowing a mismatch between header pid and chunk/trailer pid for generated ones?

const incoming = new IncomingDataStreamManager(
streamOptions ?? room.options.dataStream,
// The SFU only lets an agent send a stream under another participant's identity.
(identity) => room.remoteParticipants.get(identity)?.isAgent ?? false,

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.

there might be a race hiding here where data messages are received before the remote participant entry is populated

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.

also this would then apply to all streams of an agent (which is fine, I think) but the SFU's case is a lot narrower.

@mdepinet

This comment was marked as off-topic.

@1egoman

This comment was marked as off-topic.

@mdepinet

This comment was marked as off-topic.

This branch has not been deployed

No deployments
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