Skip to content

rtc: send connection quality to participants that subscribe after their first update - #4838

Merged
boks1971 merged 2 commits into
livekit:masterfrom
pabloFuente:patch-2
Sep 4, 2026
Merged

boks1971 merged 2 commits into
livekit:masterfrom
pabloFuente:patch-2

Conversation

@pabloFuente

@pabloFuente pabloFuente commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Bug description

connectionQualityWorker only sends ConnectionQualityUpdate when:

  1. A participant is new.
  2. Some participant's quality level changed (Send connection quality updates only if there is a change #767).

Each update contains a participant's own quality plus the quality of the participants it is subscribed to at that tick of the connectionQualityWorker.

If a participant's subscriptions are established after the tick that announce it as a new entrant, the worker never sends it the quality of the participants it subscribed to until one of them changes level. On a stable network that can be never, and the client keeps reporting those remote participants as ConnectionQuality.UNKNOWN.

Fix

Remember, per participant, which participants' quality it was last sent, and also trigger an update when a participant is subscribed to someone it has not been told about yet. The existing send path is reused, so the cost is just one full update per late subscription. Entries of participants that left are dropped every tick.

Proof of the bug

Below is a simple Go file that uses the LiveKit Go SDK to join a publisher and a subscriber participant to the same Room and using autoSubscribe: false forces the wrong behavior.

Run livekit-server:

livekit-server --dev 

Create a temporal folder, initialize a go project and install the LiveKit Go SDK:

mkdir cqproof && cd cqproof 
go mod init cqproof
go get github.com/livekit/server-sdk-go/v2@latest github.com/go-logr/logr@latest

Now store this main.go file in that same folder cqproof:

// Proves that a participant subscribing to another one AFTER its first
// ConnectionQualityUpdate never receives that participant's connection quality
// (the remote participant stays at ConnectionQuality UNKNOWN on the client).

package main
import (
	"fmt"
	"os"
	"time"

	"github.com/go-logr/logr"
	"github.com/pion/webrtc/v4"

	"github.com/livekit/protocol/livekit"
	protoLogger "github.com/livekit/protocol/logger"
	lksdk "github.com/livekit/server-sdk-go/v2"
)

func main() {
	lksdk.SetLogger(protoLogger.LogRLogger(logr.Discard())) // hide SDK/pion logs
	url := "ws://localhost:7880"
	if len(os.Args) > 1 {
		url = os.Args[1]
	}
	info := func(identity string) lksdk.ConnectInfo {
		return lksdk.ConnectInfo{APIKey: "devkey", APISecret: "secret", RoomName: "cq-proof", ParticipantIdentity: identity}
	}

	// 1) "publisher" joins and publishes an audio track (silence at 32 kbps).
	publisher, err := lksdk.ConnectToRoom(url, info("publisher"), &lksdk.RoomCallback{})
	must(err)
	defer publisher.Disconnect()
	track, err := lksdk.NewLocalSampleTrack(webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus, ClockRate: 48000, Channels: 2})
	must(err)
	_, err = publisher.LocalParticipant.PublishTrack(track, &lksdk.TrackPublicationOptions{Name: "audio"})
	must(err)
	must(track.StartWrite(lksdk.NewNullSampleProvider(32000), nil))
	fmt.Println("publisher connected and publishing")

	// 2) "subscriber" joins WITHOUT auto-subscribe and waits for its first
	//    ConnectionQualityUpdate (which can only contain itself).
	ownQuality := make(chan struct{}, 1)
	publisherQuality := make(chan struct{}, 1)
	subscribed := make(chan struct{}, 1)
	cb := &lksdk.RoomCallback{ParticipantCallback: lksdk.ParticipantCallback{
		OnConnectionQualityChanged: func(update *livekit.ConnectionQualityInfo, p lksdk.Participant) {
			fmt.Printf("%s subscriber got connection quality of %q: %s\n", time.Now().Format("15:04:05.000"), p.Identity(), update.Quality)
			switch p.Identity() {
			case "subscriber":
				select {
				case ownQuality <- struct{}{}:
				default:
				}
			case "publisher":
				select {
				case publisherQuality <- struct{}{}:
				default:
				}
			}
		},
		OnTrackSubscribed: func(_ *webrtc.TrackRemote, _ *lksdk.RemoteTrackPublication, rp *lksdk.RemoteParticipant) {
			fmt.Printf("%s subscriber is now subscribed to %q's track\n", time.Now().Format("15:04:05.000"), rp.Identity())
			select {
			case subscribed <- struct{}{}:
			default:
			}
		},
	}}
	subscriber, err := lksdk.ConnectToRoom(url, info("subscriber"), cb, lksdk.WithAutoSubscribe(false))
	must(err)
	defer subscriber.Disconnect()
	fmt.Println("subscriber connected (autoSubscribe=false), waiting for its first connection quality update")
	waitFor(ownQuality, 15*time.Second, "subscriber never received its own connection quality")

	// 3) Only now subscribe to the publisher's track.
	for _, rp := range subscriber.GetRemoteParticipants() {
		for _, pub := range rp.TrackPublications() {
			must(pub.(*lksdk.RemoteTrackPublication).SetSubscribed(true))
		}
	}
	waitFor(subscribed, 15*time.Second, "subscriber never got subscribed to the publisher's track")

	// 4) The server sends ConnectionQualityUpdate only on a new participant or a
	//    quality LEVEL change. Nothing changes here, so on an unfixed server the
	//    subscriber never learns the publisher's quality (the client-side remote
	//    participant stays UNKNOWN). A fixed server sends it on the next 5 s tick.
	start := time.Now()
	select {
	case <-publisherQuality:
		fmt.Printf("OK: publisher's connection quality reached the subscriber %.1fs after subscribing\n", time.Since(start).Seconds())
	case <-time.After(30 * time.Second):
		fmt.Println("BUG: 30s after subscribing, the subscriber still has no connection quality for the publisher")
		os.Exit(1)
	}
}

func waitFor(ch chan struct{}, timeout time.Duration, errMsg string) {
	select {
	case <-ch:
	case <-time.After(timeout):
		fmt.Println("ERROR:", errMsg)
		os.Exit(2)
	}
}

func must(err error) {
	if err != nil {
		fmt.Println("ERROR:", err)
		os.Exit(2)
	}
}

Then just run the go file and wait for the output:

go mod tidy && go run .

The livekit-server in main will output something like:

user@ubuntu:~/Documents/cqproof$ go mod tidy && go run .
publisher connected and publishing
subscriber connected (autoSubscribe=false), waiting for its first connection quality update
19:43:53.086 subscriber got connection quality of "subscriber": EXCELLENT
19:43:53.113 subscriber is now subscribed to "publisher"'s track
BUG: 30s after subscribing, the subscriber still has no connection quality for the publisher
exit status 1

A livekit-server with this PR merged outputs:

19:40:14.138 subscriber got connection quality of "subscriber": EXCELLENT
19:40:14.173 subscriber is now subscribed to "publisher"'s track
19:40:19.137 subscriber got connection quality of "subscriber": EXCELLENT
19:40:19.137 subscriber got connection quality of "publisher": EXCELLENT
OK: publisher's connection quality reached the subscriber 5.0s after subscribing

…ir first update

Added tracking for participants' connection quality updates to ensure all subscribed participants receive necessary updates, even if they were added after the last quality announcement
@pabloFuente
pabloFuente requested a review from a team as a code owner September 4, 2026 17:52
devin-ai-integration[bot]

This comment was marked as resolved.

A failed SendConnectionQualityUpdate must not mark the participant as informed, otherwise the update is never retried while qualities stay stable. Also simplify the untold-subscription check.

@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 new potential issue.

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

Devin Review

Comment thread pkg/rtc/room.go
Comment on lines +1783 to 1789

// remember which participants' quality this participant has been sent,
// only after a successful send so that a failed one is retried on next tick
told := make(map[livekit.ParticipantID]struct{}, len(update.Updates))
for _, info := range update.Updates {
told[livekit.ParticipantID(info.ParticipantSid)] = struct{}{}
}

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.

🟡 Dropped updates suppress later retries

When SendConnectionQualityUpdate drops an update during a signaling outage, toldQualityOf records it as delivered. The new subscription stays unknown until quality changes.

Prompt for agents
The connection-quality worker treats a nil return from ParticipantImpl.SendConnectionQualityUpdate as proof of delivery. However, pkg/rtc/signalling/signallerasync.go WriteMessage returns nil when the participant is disconnected, the handshake is pending, no response sink exists, or the channel has closed. If an untold subscription is processed during that interval, toldQualityOf suppresses all later retries. Change the delivery bookkeeping so dropped signal messages do not mark these participant IDs as informed. Consider exposing actual enqueue/delivery status to this worker or resetting its bookkeeping when a signal connection reopens. Add coverage for a subscription established during a signaling outage followed by resume with stable quality.
Devin Review

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

@boks1971

boks1971 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

thank you @pabloFuente for catching this.

@boks1971
boks1971 merged commit 407fe3f into livekit:master Sep 4, 2026
3 of 7 checks passed
pabloFuente added a commit to pabloFuente/livekit that referenced this pull request Sep 4, 2026
Since livekit#4136 (v1.10.0) nothing registers SubscriptionManager.OnSubscribeStatusChanged, so Room.onSubscribeStatusChanged is never invoked. A participant that subscribes to another one after its first ConnectionQualityUpdate therefore never receives that participant's quality until a level changes (the client shows UNKNOWN indefinitely), and the speaker state a new subscriber used to receive is not sent either.

Deterministic with autoSubscribe: false; a race for auto-subscribe when the 5s quality tick lands between the participant becoming ACTIVE and its subscriptions being registered.

Fix: register the callback again in setupSubscriptionManager, forwarding to the participant listener, which is I think where livekit#4136 intended to do.
@boks1971

boks1971 commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

@pabloFuente I might end up reverting this. Realised that we have a callback for that here -

livekit/pkg/rtc/room.go

Lines 1317 to 1350 in 407fe3f

func (r *Room) onSubscribeStatusChanged(participant types.LocalParticipant, publisherID livekit.ParticipantID, subscribed bool) {
if subscribed {
pub := r.GetParticipantByID(publisherID)
if pub != nil && pub.State() == livekit.ParticipantInfo_ACTIVE {
// when a participant subscribes to another participant,
// send speaker update if the subscribed to participant is active.
level, active := pub.GetAudioLevel()
if active {
_ = participant.SendSpeakerUpdate([]*livekit.SpeakerInfo{
{
Sid: string(pub.ID()),
Level: float32(level),
Active: active,
},
}, false)
}
if cq := pub.GetConnectionQuality(); cq != nil {
update := &livekit.ConnectionQualityUpdate{}
update.Updates = append(update.Updates, cq)
_ = participant.SendConnectionQualityUpdate(update)
}
}
} else {
// no longer subscribed to the publisher, clear speaker status
_ = participant.SendSpeakerUpdate([]*livekit.SpeakerInfo{
{
Sid: string(publisherID),
Level: 0,
Active: false,
},
}, true)
}
}
. I just messed it up I think when converting those callbacks to interface implementation. Will look at it. Sorry about the inconvenience.

boks1971 pushed a commit that referenced this pull request Sep 4, 2026
pabloFuente added a commit to OpenVidu/openvidu-livekit that referenced this pull request Sep 4, 2026
…ir first update (livekit#4838)

* rtc: send connection quality to participants that subscribe after their first update

Added tracking for participants' connection quality updates to ensure all subscribed participants receive necessary updates, even if they were added after the last quality announcement

* rtc: record sent connection quality only after a successful send

A failed SendConnectionQualityUpdate must not mark the participant as informed, otherwise the update is never retried while qualities stay stable. Also simplify the untold-subscription check.

(cherry picked from commit 407fe3f)
pabloFuente added a commit to OpenVidu/openvidu-livekit that referenced this pull request Sep 4, 2026
@boks1971 boks1971 mentioned this pull request Sep 14, 2026
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.

2 participants