Skip to content

Revert PR #4838 in favor of a better solution - #4840

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

boks1971 merged 2 commits into
livekit:masterfrom
pabloFuente:master

Conversation

@pabloFuente

Copy link
Copy Markdown
Contributor

ATTENTION: this PR reverts a previous one (#4838), as a better solution has been found.

Since #4136 (v1.10.0) nothing registers SubscriptionManager.OnSubscribeStatusChanged, so Room.onSubscribeStatusChanged is never invoked. That event handler (https://github.com/livekit/livekit/blob/407fe3fe26f7aad72f1307f01020d9a7671de6d8/pkg/rtc/room.go#L1317C16-L1317C40) took care of precisely sending network quality updates, as well as speaker state updates.

If you perform a string search with Match Case and Whole Word of OnSubscribeStatusChanged in repository livekit/livekit, you can see that it is dead code. Not called a single time anywhere in the code.

Fix: register the callback again in participant.go, method setupSubscriptionManager, forwarding to the participant listener (which is where #4136 intended it to go). The addition of this simple listener allows removing all the previous, more complex logic of room.go, fixing in the process the sending of speaker state events as well.

Bug proof

The code snippet to proof the bug and this solution remains valid as in PR #4838:

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

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.
@pabloFuente
pabloFuente requested a review from a team as a code owner September 4, 2026 19:16
devin-ai-integration[bot]

This comment was marked as resolved.

Matches the subscribe notification, so a quick track close + resubscribe cannot deliver a stale `false` after the following `true`.
Drops the test comment describing the old goroutine delivery.
Restores the trailing newline in room.go.
@boks1971
boks1971 merged commit a8ce398 into livekit:master Sep 4, 2026
2 of 5 checks passed
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