Skip to content

fix: release reader lock and clear receivedChunks in stream iterators#640

Open
LautaroPetaccio wants to merge 2 commits intolivekit:mainfrom
LautaroPetaccio:fix/stream-reader-lock-release
Open

fix: release reader lock and clear receivedChunks in stream iterators#640
LautaroPetaccio wants to merge 2 commits intolivekit:mainfrom
LautaroPetaccio:fix/stream-reader-lock-release

Conversation

@LautaroPetaccio
Copy link
Copy Markdown

Why

Reader lock not released (FD leak)

Both ByteStreamReader and TextStreamReader async iterators only released the reader lock in the explicit return() method. If the stream completed normally (done: true) or an error was caught in next(), the lock stayed held. Consumers that don't call return() (e.g. for-await loops that break on a condition, or readAll() which runs to completion) would leave the underlying ReadableStream locked and unable to be garbage-collected.

receivedChunks never cleared (memory leak)

The TextStreamReader.receivedChunks Map stores every chunk received during the stream's lifetime for version-based deduplication and progress tracking. It is never cleared — not when the stream is fully consumed, not on error, and not when the consumer breaks out of iteration. For large or frequent text streams, this keeps all chunk data in memory for the lifetime of the reader object.

How

Reader lock fix

Add reader.releaseLock() in both the done and catch paths of next() for both ByteStreamReader and TextStreamReader iterators. This ensures the lock is released regardless of how the iteration ends.

receivedChunks fix

Capture the receivedChunks reference into a local variable at the top of the async iterator (since return() is a regular function where this refers to the iterator object, not the class instance). Then call receivedChunks.clear() in all three termination paths: done, catch, and return().

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Apr 1, 2026

🦋 Changeset detected

Latest commit: 96c4cbf

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

This PR includes changesets to release 1 package
Name Type
@livekit/rtc-node 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

Copy link
Copy Markdown

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

Choose a reason for hiding this comment

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

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no potential bugs to report.

View in Devin Review to see 2 additional findings.

Open in Devin Review

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