Skip to content

rtc: keep subscription observers until teardown - #5250

Merged
boks1971 merged 7 commits into
livekit:masterfrom
perfloop-oss:perfloop-pr-open-9jy05cr57p
Nov 27, 2026
Merged

boks1971 merged 7 commits into
livekit:masterfrom
perfloop-oss:perfloop-pr-open-9jy05cr57p

Conversation

@perfloop-agent

@perfloop-agent perfloop-agent commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A subscriber can lose track-change and source-removal notifications after permission is revoked through RevokeDisallowedSubscribers and granted again, or after a subscribed track closes while still desired. Asynchronous cleanup can delete observers registered by the replacement subscription.

Fast subscription toggles also lose observers: unsubscribe clears them immediately, but subscribing again before reconciliation keeps the established subscription without restoring its observers.

Effects

  • A permission grant or a track becoming available is picked up only by the 3 s reconcile ticker instead of its notification.
  • After an unpublish, the subscription retries ErrTrackNotFound until the 1 min notFoundTimeout; media clients get a spurious SE_TRACK_NOTFOUND.

Fix

Retire both observers synchronously, before exposing an empty downtrack slot for resubscription. Keep observers through desired-state changes and remove them when the subscription actually closes or is cleaned up. Full participant teardown still removes observers, including subscriptions that never acquired a track. Only cleanup that still owns observers takes the write lock; established subscriptions and retained settings keep the read-only check. The notifier interface is unchanged; there is no registration handle or additional per-registration allocation. A nil downtrack can still have AddSubscriber in flight, after observer registration, so it is not enough to decide that observers can be retired in setDesired.

Test

pkg/rtc/subscription_notifier_test.go covers both notification kinds for data and media tracks: close while desired, unsubscribe followed by subscribe, and back-to-back toggles. All 12 cases reproduce notification loss without the production changes. Internal-state snapshots are now locked, and lifecycle checkpoints with require.Eventually replace the fixed scheduling delay. pkg/rtc/subscriptionmanager_test.go also checks that failed media and data subscriptions release both observers when cleaned up.

Go race tests for pkg/rtc and pkg/utils passed, including the mutex-checking build: go test -race -p=2 -count=1 ./pkg/rtc/ ./pkg/utils/. The full build, vet and golangci-lint on the touched packages passed.

Estimate: track closure has the broadest built-in exposure, including screen-share stop/start and unpublish/republish. Unpublishing a watched screen share closes its subscribed track for each remote participant still subscribed to it, taking those subscriptions through this cleanup path. Stopping screen share unpublishes the track, whereas ordinary mute and ICE resume do not themselves close it. Rapid toggles require explicit application subscription changes, and publisher allowlists are opt-in with allow-all the default. App-driven toggles and allowlist changes therefore have narrower triggering conditions than track closure.

Case and evidence


Made by Perfloop. Human sponsor: Tomás Senart.

@perfloop-agent
perfloop-agent requested a review from a team as a code owner November 20, 2026 19:39

@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: No Issues Found

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

Devin Review

@perfloop-agent

Copy link
Copy Markdown
Contributor Author

@boks1971: PTAL

s.numAttempts.Store(0)
} else {
s.setChangedNotifierLocked(nil)
s.setRemovedNotifierLocked(nil)

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.

Can we still clear this here when there is no subscribed track?

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.

Not safely from a nil-track check alone: AddSubscriber can still be in flight after observer registration and before the track is stored. An unsubscribe/subscribe in that window would clear observers without restoring them when installation finishes, so the no-track case remains cleaned up by reconciliation rather than setDesired.

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.

My bad. Yeah, I forgot this could be in any goroutine. Sorry.

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.

One more from an agent review

Agreed, clearing in `setDesired` races an in-flight subscribe. The reconcile cleanup does not have that race, because `reconcileSubscription` and `subscribe` run on the same worker.

There is still a gap: `cleanup()` only drops the observers when `needsCleanupLocked` is true, and that includes `!isKeptLocked()`. An entry held by `keepForSubscribe` keeps its observers for up to `notFoundTimeout`, so `HasObservers` reports interest in a track nobody wants for up to a minute.

Could the observers go as soon as the entry is not desired and has no track, with the delete still waiting for the hold? Something like:

    // cleanup is called with the manager lock held, before removing this subscription.
    func (s *mediaTrackSubscription) cleanup() bool {
        s.lock.Lock()
        defer s.lock.Unlock()
        if s.desired || s.subscribedTrack != nil {
            return false
        }
        s.setChangedNotifierLocked(nil)
        s.setRemovedNotifierLocked(nil)
        return !s.isKeptLocked()
    }

The data track version is the same with `s.dataDownTrack`. This also removes the need for `cleanupObservers` and the read-lock pre-check, because the setters already return early when the notifier is nil.

Nothing is lost: notifications do nothing for an entry that is not desired. If it becomes desired again, `subscribe` resolves the track again and adds the observers back. A test could unsubscribe a subscription that has no track, send a settings update, and check that `HasObservers` is false before `notFoundTimeout`.

Comment thread pkg/rtc/subscription_notifier_test.go Outdated
sm := newTestSubscriptionManager()
// Drive the same worker reconciliation steps explicitly so periodic retries
// cannot hide a lost notification.
close(sm.closeCh)

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.

lock on this?

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. Closing the worker channel now holds the manager lock, and the test waits for the worker to exit before resetting the channel.

Comment thread pkg/rtc/subscription_notifier_test.go Outdated
// cannot hide a lost notification.
close(sm.closeCh)
<-sm.doneCh
sm.closeCh = make(chan 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.

same here

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.

The channel reset now holds the manager lock too, after the old worker has exited.

Comment thread pkg/rtc/subscription_notifier_test.go Outdated
}
return nil
}
isSubscribed = func() bool { return sm.dataTrackSubscriptions[trackID].getDataDownTrack() != nil }

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.

This is reading internal fields without a lock.

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.

Both data and media cases now take the manager read lock for the subscription-map lookup and track-state snapshot.

case <-replaced:
case <-time.After(100 * time.Millisecond):
// Retirement may have to complete before teardown can return.
}

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.

can the fixed wait be replaced with require.Eventually?

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. The fixed scheduling delay is gone, and the channel waits use require.Eventually. Retirement and downtrack-detachment checkpoints determine whether replacement can finish while cleanup is paused, so the test does not wait for a replacement that synchronous retirement is intentionally blocking.

})
}
}
}

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.

Quite a heavy test. Were all these failing before the changes?

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—all twelve cases reach a lost-notification assertion without the production fix. They share one helper; each subtest builds its own room to cover both track types, both notifier kinds, and the three teardown/toggle histories; the description now states that comparison.

Comment thread pkg/rtc/subscriptionmanager.go Outdated
}

// cleanup is called with the manager lock held, before removing this subscription.
func (s *mediaTrackSubscription) cleanup() bool {

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.

And a :nit: from the same agent

Nit: `cleanup()` takes the read lock to check `needsCleanupLocked`, then `cleanupObservers` takes the write lock and checks it again. The read-lock pass only saves a write lock on this subscription's mutex, and only for entries that already need cleanup, which is rare. The setters already return early when the notifier is nil, so clearing twice is harmless.

Both `cleanup()` methods could go, and the two call sites could use the shared helper directly:

    if m.subscriptions[s.trackID] == s && s.cleanupObservers(s.needsCleanupLocked) {

    cleanedUp := m.dataTrackSubscriptions[s.trackID] == s && s.cleanupObservers(s.needsCleanupLocked)

That is one lock and one check, and no per-type duplicate.

@tsenart

tsenart commented Nov 26, 2026

Copy link
Copy Markdown

@boks1971 sorry for the slow reply. Both points make sense: dropping the observers once an entry is no longer desired and has no track, and using the shared helper in place of the two cleanup() methods. I'll fold both into the next update, together with a rebase.

@perfloop-agent
perfloop-agent force-pushed the perfloop-pr-open-9jy05cr57p branch from 97ed7af to 3c51f6b Compare November 26, 2026 23:08

@boks1971 boks1971 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.

Thank you 🙏

@boks1971
boks1971 merged commit b80b659 into livekit:master Nov 27, 2026
3 of 4 checks passed
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