Record subscribe stream start time in prometheus. (#4704)

* Record subscribe stream start time in prometheus.

Adjust for mutes, i. e. take the last unmute time as the start point and
calculate time till the first byte is sent.

* close the tiny window of race

* Prevent long tail sample when publisher glitches.

Thanks to @milos-lk for this.

Publisher restarting would have reset the layer and would have caused a
sample with very high stream start time. We only need to capture when we
do a dummy start or when the state is seeded to a different node upon
migration.

* reduce a diff

* test

* changed the wrong thing, thank you Devin
This commit is contained in:
Raja Subramanian
2026-07-27 20:37:44 +05:30
committed by GitHub
parent f1e2eee2fe
commit 0aa296e126
11 changed files with 152 additions and 34 deletions
+1 -1
View File
@@ -2056,7 +2056,7 @@ func (l participantTelemetryListener) OnTrackSubscribeFailed(pID livekit.Partici
l.room.telemetry.TrackSubscribeFailed(context.Background(), l.room.ID(), l.room.Name(), pID, trackID, err, isUserError)
}
func (l participantTelemetryListener) OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo) {
func (l participantTelemetryListener) OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo, elapsed time.Duration) {
}
func (l participantTelemetryListener) OnTrackMuted(pID livekit.ParticipantID, ti *livekit.TrackInfo) {
+11 -3
View File
@@ -74,7 +74,8 @@ type SubscribedTrack struct {
bound bool
onBindCallbacks []func(error)
onClose atomic.Value // func(bool)
onSubscribeStreamStarted atomic.Value //func(time.Duration)
onClose atomic.Value // func(bool)
debouncer func(func())
@@ -242,6 +243,10 @@ func (t *SubscribedTrack) Close(isExpectedToResume bool) {
}
}
func (t *SubscribedTrack) OnSubscribeStreamStarted(f func(time.Duration)) {
t.onSubscribeStreamStarted.Store(f)
}
func (t *SubscribedTrack) OnClose(f func(bool)) {
t.onClose.Store(f)
}
@@ -492,6 +497,9 @@ func (t *SubscribedTrack) OnDownTrackClose(isExpectedToResume bool) {
t.Close(isExpectedToResume)
}
func (t *SubscribedTrack) OnStreamStarted() {
t.params.TelemetryListener.OnTrackSubscribeStreamStarted(t.params.Subscriber.ID(), t.params.MediaTrack.ToProto())
func (t *SubscribedTrack) OnStreamStarted(elapsed time.Duration) {
t.params.TelemetryListener.OnTrackSubscribeStreamStarted(t.params.Subscriber.ID(), t.params.MediaTrack.ToProto(), elapsed)
if onSubscribeStreamStarted := t.onSubscribeStreamStarted.Load(); onSubscribeStreamStarted != nil {
onSubscribeStreamStarted.(func(time.Duration))(elapsed)
}
}
+23
View File
@@ -852,6 +852,7 @@ func (m *SubscriptionManager) addSubscriber(sub *mediaTrackSubscription, track t
)
}
if err == nil && subTrack != nil { // subTrack could be nil if already subscribed
subTrack.OnSubscribeStreamStarted(sub.recordStreamStartLatency)
subTrack.OnClose(func(isExpectedToResume bool) {
m.handleSubscribedTrackClose(sub, isExpectedToResume)
@@ -1532,6 +1533,28 @@ func (s *mediaTrackSubscription) maybeRecordSuccess(tl types.ParticipantTelemetr
tl.OnTrackSubscribed(s.subscriberID, mediaTrack.ToProto(), pi, !eventSent)
}
func (s *mediaTrackSubscription) recordStreamStartLatency(elapsed time.Duration) {
subTrack := s.getSubscribedTrack()
if subTrack == nil {
return
}
mediaTrack := subTrack.MediaTrack()
if mediaTrack == nil {
return
}
s.logger.Debugw("track subscribe stream started", "cost", elapsed.Microseconds())
subscriber := subTrack.Subscriber()
prometheus.RecordSubscribeStreamStartTime(
subscriber.GetCountry(),
mediaTrack.Source(),
mediaTrack.Kind(),
elapsed,
subscriber.GetClientInfo().GetSdk(),
subscriber.Kind(),
)
}
func (s *mediaTrackSubscription) isCanceled() bool {
return !s.eventSent.Load() && s.isDesired()
}
+3 -2
View File
@@ -687,7 +687,7 @@ type ParticipantTelemetryListener interface {
OnTrackSubscribed(pID livekit.ParticipantID, ti *livekit.TrackInfo, publisherInfo *livekit.ParticipantInfo, shouldSendEvent bool)
OnTrackUnsubscribed(pID livekit.ParticipantID, ti *livekit.TrackInfo, shouldSendEvent bool)
OnTrackSubscribeFailed(pID livekit.ParticipantID, trackID livekit.TrackID, err error, isUserError bool)
OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo)
OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo, elapsed time.Duration)
OnTrackMuted(pID livekit.ParticipantID, ti *livekit.TrackInfo)
OnTrackUnmuted(pID livekit.ParticipantID, ti *livekit.TrackInfo)
OnTrackPublishedUpdate(pID livekit.ParticipantID, ti *livekit.TrackInfo)
@@ -716,7 +716,7 @@ func (NullParticipantTelemetryListener) OnTrackUnsubscribed(pID livekit.Particip
}
func (NullParticipantTelemetryListener) OnTrackSubscribeFailed(pID livekit.ParticipantID, trackID livekit.TrackID, err error, isUserError bool) {
}
func (NullParticipantTelemetryListener) OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo) {
func (NullParticipantTelemetryListener) OnTrackSubscribeStreamStarted(pID livekit.ParticipantID, ti *livekit.TrackInfo, elapsed time.Duration) {
}
func (NullParticipantTelemetryListener) OnTrackMuted(pID livekit.ParticipantID, ti *livekit.TrackInfo) {
}
@@ -880,6 +880,7 @@ type DataTrackTransport interface {
type SubscribedTrack interface {
AddOnBind(f func(error))
IsBound() bool
OnSubscribeStreamStarted(f func(elapsed time.Duration))
Close(isExpectedToResume bool)
OnClose(f func(isExpectedToResume bool))
ID() livekit.TrackID
@@ -3,6 +3,7 @@ package typesfakes
import (
"sync"
"time"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/telemetry"
@@ -83,11 +84,12 @@ type FakeParticipantTelemetryListener struct {
arg1 livekit.ParticipantID
arg2 *livekit.TrackInfo
}
OnTrackSubscribeStreamStartedStub func(livekit.ParticipantID, *livekit.TrackInfo)
OnTrackSubscribeStreamStartedStub func(livekit.ParticipantID, *livekit.TrackInfo, time.Duration)
onTrackSubscribeStreamStartedMutex sync.RWMutex
onTrackSubscribeStreamStartedArgsForCall []struct {
arg1 livekit.ParticipantID
arg2 *livekit.TrackInfo
arg3 time.Duration
}
OnTrackSubscribedStub func(livekit.ParticipantID, *livekit.TrackInfo, *livekit.ParticipantInfo, bool)
onTrackSubscribedMutex sync.RWMutex
@@ -464,17 +466,18 @@ func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeRequestedArgsForCa
return argsForCall.arg1, argsForCall.arg2
}
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStarted(arg1 livekit.ParticipantID, arg2 *livekit.TrackInfo) {
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStarted(arg1 livekit.ParticipantID, arg2 *livekit.TrackInfo, arg3 time.Duration) {
fake.onTrackSubscribeStreamStartedMutex.Lock()
fake.onTrackSubscribeStreamStartedArgsForCall = append(fake.onTrackSubscribeStreamStartedArgsForCall, struct {
arg1 livekit.ParticipantID
arg2 *livekit.TrackInfo
}{arg1, arg2})
arg3 time.Duration
}{arg1, arg2, arg3})
stub := fake.OnTrackSubscribeStreamStartedStub
fake.recordInvocation("OnTrackSubscribeStreamStarted", []interface{}{arg1, arg2})
fake.recordInvocation("OnTrackSubscribeStreamStarted", []interface{}{arg1, arg2, arg3})
fake.onTrackSubscribeStreamStartedMutex.Unlock()
if stub != nil {
fake.OnTrackSubscribeStreamStartedStub(arg1, arg2)
fake.OnTrackSubscribeStreamStartedStub(arg1, arg2, arg3)
}
}
@@ -484,17 +487,17 @@ func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStartedCallC
return len(fake.onTrackSubscribeStreamStartedArgsForCall)
}
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStartedCalls(stub func(livekit.ParticipantID, *livekit.TrackInfo)) {
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStartedCalls(stub func(livekit.ParticipantID, *livekit.TrackInfo, time.Duration)) {
fake.onTrackSubscribeStreamStartedMutex.Lock()
defer fake.onTrackSubscribeStreamStartedMutex.Unlock()
fake.OnTrackSubscribeStreamStartedStub = stub
}
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStartedArgsForCall(i int) (livekit.ParticipantID, *livekit.TrackInfo) {
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribeStreamStartedArgsForCall(i int) (livekit.ParticipantID, *livekit.TrackInfo, time.Duration) {
fake.onTrackSubscribeStreamStartedMutex.RLock()
defer fake.onTrackSubscribeStreamStartedMutex.RUnlock()
argsForCall := fake.onTrackSubscribeStreamStartedArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}
func (fake *FakeParticipantTelemetryListener) OnTrackSubscribed(arg1 livekit.ParticipantID, arg2 *livekit.TrackInfo, arg3 *livekit.ParticipantInfo, arg4 bool) {
@@ -3,6 +3,7 @@ package typesfakes
import (
"sync"
"time"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/sfu"
@@ -86,6 +87,11 @@ type FakeSubscribedTrack struct {
onCloseArgsForCall []struct {
arg1 func(isExpectedToResume bool)
}
OnSubscribeStreamStartedStub func(func(elapsed time.Duration))
onSubscribeStreamStartedMutex sync.RWMutex
onSubscribeStreamStartedArgsForCall []struct {
arg1 func(elapsed time.Duration)
}
PublisherIDStub func() livekit.ParticipantID
publisherIDMutex sync.RWMutex
publisherIDArgsForCall []struct {
@@ -589,6 +595,38 @@ func (fake *FakeSubscribedTrack) OnCloseArgsForCall(i int) func(isExpectedToResu
return argsForCall.arg1
}
func (fake *FakeSubscribedTrack) OnSubscribeStreamStarted(arg1 func(elapsed time.Duration)) {
fake.onSubscribeStreamStartedMutex.Lock()
fake.onSubscribeStreamStartedArgsForCall = append(fake.onSubscribeStreamStartedArgsForCall, struct {
arg1 func(elapsed time.Duration)
}{arg1})
stub := fake.OnSubscribeStreamStartedStub
fake.recordInvocation("OnSubscribeStreamStarted", []interface{}{arg1})
fake.onSubscribeStreamStartedMutex.Unlock()
if stub != nil {
fake.OnSubscribeStreamStartedStub(arg1)
}
}
func (fake *FakeSubscribedTrack) OnSubscribeStreamStartedCallCount() int {
fake.onSubscribeStreamStartedMutex.RLock()
defer fake.onSubscribeStreamStartedMutex.RUnlock()
return len(fake.onSubscribeStreamStartedArgsForCall)
}
func (fake *FakeSubscribedTrack) OnSubscribeStreamStartedCalls(stub func(func(elapsed time.Duration))) {
fake.onSubscribeStreamStartedMutex.Lock()
defer fake.onSubscribeStreamStartedMutex.Unlock()
fake.OnSubscribeStreamStartedStub = stub
}
func (fake *FakeSubscribedTrack) OnSubscribeStreamStartedArgsForCall(i int) func(elapsed time.Duration) {
fake.onSubscribeStreamStartedMutex.RLock()
defer fake.onSubscribeStreamStartedMutex.RUnlock()
argsForCall := fake.onSubscribeStreamStartedArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeSubscribedTrack) PublisherID() livekit.ParticipantID {
fake.publisherIDMutex.Lock()
ret, specificReturn := fake.publisherIDReturnsOnCall[len(fake.publisherIDArgsForCall)]
+24 -4
View File
@@ -299,6 +299,7 @@ type DownTrack struct {
connected atomic.Bool
bindAndConnectedOnce atomic.Bool
writable atomic.Bool
writableAt atomic.Time
writeStopped atomic.Bool
isReceiverReady bool
@@ -335,7 +336,8 @@ type DownTrack struct {
keyFrameRequesterCh chan struct{}
keyFrameRequesterChClosed bool
createdAt int64
createdAt int64
lastUnmutedAt atomic.Time
}
// NewDownTrack returns a DownTrack.
@@ -364,6 +366,8 @@ func NewDownTrack(params DownTrackParams) (*DownTrack, error) {
createdAt: time.Now().UnixNano(),
receiver: params.Receiver,
}
d.lastUnmutedAt.Store(time.Now())
d.codec.Store(codec)
d.bindState.Store(bindStateUnbound)
d.params.Logger = params.Logger.WithValues(
@@ -1157,7 +1161,14 @@ func (d *DownTrack) WriteRTP(extPkt *buffer.ExtPacket, layer int32) int32 {
}
if tp.isStarting {
d.params.Listener.OnStreamStarted()
writableAt := d.writableAt.Load()
lastUnmutedAt := d.lastUnmutedAt.Load()
if !writableAt.IsZero() && !lastUnmutedAt.IsZero() {
if writableAt.After(lastUnmutedAt) {
lastUnmutedAt = writableAt
}
d.params.Listener.OnStreamStarted(time.Since(lastUnmutedAt))
}
}
return 1
}
@@ -1302,6 +1313,11 @@ func (d *DownTrack) handleMute(muted bool, changed bool) {
}
d.connectionStats.UpdateMute(d.forwarder.IsAnyMuted())
if muted {
d.lastUnmutedAt.Store(time.Time{})
} else {
d.lastUnmutedAt.Store(time.Now())
}
//
// Subscriber mute changes trigger a max layer notification.
@@ -2483,8 +2499,12 @@ func (d *DownTrack) onBindAndConnectedChange() {
if d.writeStopped.Load() {
return
}
d.writable.Store(d.connected.Load() && d.bindState.Load() == bindStateBound)
if d.connected.Load() && d.bindState.Load() == bindStateBound && !d.bindAndConnectedOnce.Swap(true) {
writable := d.connected.Load() && d.bindState.Load() == bindStateBound
if writable {
d.writableAt.Store(time.Now())
}
d.writable.Store(writable)
if writable && !d.bindAndConnectedOnce.Swap(true) {
go d.params.Listener.OnBindAndConnected()
if d.activePaddingOnMuteUpTrack.Load() {
+7 -1
View File
@@ -240,6 +240,7 @@ type Forwarder struct {
started bool
preStartTime time.Time
startPending bool
acquireDeadline int64 // mono nanos; initial-acquisition grace deadline, 0 = inactive
extFirstTS uint64
lastSSRC uint32
@@ -508,6 +509,7 @@ func (f *Forwarder) SeedState(state *livekit.RTPForwarderState) {
f.referenceLayerSpatial = state.ReferenceLayerSpatial
if state.PreStartTime != 0 {
f.preStartTime = time.Unix(0, state.PreStartTime)
f.startPending = true
}
f.extFirstTS = state.ExtFirstTimestamp
f.dummyStartTSOffset = state.DummyStartTimestampOffset
@@ -1858,7 +1860,10 @@ func (f *Forwarder) processSourceSwitch(extPkt *buffer.ExtPacket, layer int32) (
"referenceLayerSpatial", f.referenceLayerSpatial,
)
starting = true
if f.startPending {
f.startPending = false
starting = true
}
}
logTransition := func(message string, extExpectedTS, extRefTS, extLastTS uint64, diffSeconds float64) {
@@ -2230,6 +2235,7 @@ func (f *Forwarder) maybeStart() {
f.started = true
f.preStartTime = time.Now()
f.startPending = true
sequenceNumber := uint16(rand.Intn(1<<14)) + uint16(1<<15) // a random number in third quartile of sequence number space
timestamp := uint32(rand.Intn(1<<30)) + uint32(1<<31) // a random number in third quartile of timestamp space
+3 -1
View File
@@ -15,6 +15,8 @@
package sfu
import (
"time"
"github.com/pion/rtcp"
"github.com/pion/webrtc/v4"
@@ -181,7 +183,7 @@ type DownTrackListener interface {
OnRttUpdate(rtt uint32)
OnCodecNegotiated(webrtc.RTPCodecCapability)
OnDownTrackClose(isExpectedToResume bool)
OnStreamStarted()
OnStreamStarted(elapsed time.Duration)
}
// -------------------------------------------------------------------
+16 -6
View File
@@ -3,6 +3,7 @@ package sfufakes
import (
"sync"
"time"
"github.com/livekit/livekit-server/pkg/sfu"
"github.com/livekit/protocol/livekit"
@@ -39,9 +40,10 @@ type FakeDownTrackListener struct {
onStatsUpdateArgsForCall []struct {
arg1 *livekit.AnalyticsStat
}
OnStreamStartedStub func()
OnStreamStartedStub func(time.Duration)
onStreamStartedMutex sync.RWMutex
onStreamStartedArgsForCall []struct {
arg1 time.Duration
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
@@ -231,15 +233,16 @@ func (fake *FakeDownTrackListener) OnStatsUpdateArgsForCall(i int) *livekit.Anal
return argsForCall.arg1
}
func (fake *FakeDownTrackListener) OnStreamStarted() {
func (fake *FakeDownTrackListener) OnStreamStarted(arg1 time.Duration) {
fake.onStreamStartedMutex.Lock()
fake.onStreamStartedArgsForCall = append(fake.onStreamStartedArgsForCall, struct {
}{})
arg1 time.Duration
}{arg1})
stub := fake.OnStreamStartedStub
fake.recordInvocation("OnStreamStarted", []interface{}{})
fake.recordInvocation("OnStreamStarted", []interface{}{arg1})
fake.onStreamStartedMutex.Unlock()
if stub != nil {
fake.OnStreamStartedStub()
fake.OnStreamStartedStub(arg1)
}
}
@@ -249,12 +252,19 @@ func (fake *FakeDownTrackListener) OnStreamStartedCallCount() int {
return len(fake.onStreamStartedArgsForCall)
}
func (fake *FakeDownTrackListener) OnStreamStartedCalls(stub func()) {
func (fake *FakeDownTrackListener) OnStreamStartedCalls(stub func(time.Duration)) {
fake.onStreamStartedMutex.Lock()
defer fake.onStreamStartedMutex.Unlock()
fake.OnStreamStartedStub = stub
}
func (fake *FakeDownTrackListener) OnStreamStartedArgsForCall(i int) time.Duration {
fake.onStreamStartedMutex.RLock()
defer fake.onStreamStartedMutex.RUnlock()
argsForCall := fake.onStreamStartedArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeDownTrackListener) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
+15 -8
View File
@@ -205,7 +205,7 @@ func RecordPublishTime(
sdk livekit.ClientInfo_SDK,
kind livekit.ParticipantInfo_Kind,
) {
recordPubSubTime(true, country, source, trackType, d, sdk, kind, 1)
recordPubSubStreamStartTime("publish", country, source, trackType, d, sdk, kind, 1)
}
func RecordSubscribeTime(
@@ -217,11 +217,22 @@ func RecordSubscribeTime(
kind livekit.ParticipantInfo_Kind,
count int,
) {
recordPubSubTime(false, country, source, trackType, d, sdk, kind, count)
recordPubSubStreamStartTime("subscribe", country, source, trackType, d, sdk, kind, count)
}
func recordPubSubTime(
isPublish bool,
func RecordSubscribeStreamStartTime(
country string,
source livekit.TrackSource,
trackType livekit.TrackType,
d time.Duration,
sdk livekit.ClientInfo_SDK,
kind livekit.ParticipantInfo_Kind,
) {
recordPubSubStreamStartTime("subscribe-stream-start", country, source, trackType, d, sdk, kind, 1)
}
func recordPubSubStreamStartTime(
direction string,
country string,
source livekit.TrackSource,
trackType livekit.TrackType,
@@ -230,10 +241,6 @@ func recordPubSubTime(
kind livekit.ParticipantInfo_Kind,
count int,
) {
direction := "subscribe"
if isPublish {
direction = "publish"
}
promPubSubTime.WithLabelValues(
direction,
source.String(),