* telemetry: count failed publishes and subscribes, not only successes
- JoinSession records a publish request before each re-reported track.
- livekit_track_publish_counter gets state="failure" for tracks pending at close.
- A subscribe failure is counted once per attempt; a new attempt restarts its timers.
- livekit_track_subscribe_counter gets a user_error label.
- New livekit_pubsub_outcome_ms: one sample per attempt, failures at the time they fail.
- A connection that never comes up records its session start time at close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: close the gaps in failure samples found in review
- A subscribe that succeeds after a user-error wait starts a new attempt.
- Close records one publish failure sample per pending request, migrated ones included.
- A publish released for an unknown codec counts as a failed publish.
- A session that never reached primary transport connected records its start time at close.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: start the new attempt when a bind lands before subscribe returns
After a user error, a bind that fired inside addSubscriber found the
outcome gate still closed and recorded no success sample. The bind
callback now starts the new attempt too, and the test waits for the
request count instead of reading it once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: serialize the new attempt and record legacy publish time per request
The bind callback and reconcile could both reach the new-attempt helper.
The one that lost the flag swap returned before the timers restarted, so
a later reconcile could fire a false not-bound timeout. A per-subscription
mutex now holds the whole restart.
On a close that is not a cancel, livekit_pubsubtime_ms now records one
publish sample for each pending request, migrated requests included, the
same set the failure counter and livekit_pubsub_outcome_ms cover.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Do not recover FlexFEC from RTX repaired packets
A packet repaired from RTX takes its header from the RTX packet: libwebrtc
adds a MID to retransmissions until the RTX SSRC is acknowledged, and sets
abs-send-time and transport-cc at send time. The stored packet therefore
differs from the media the publisher protected, so using it as a protected
packet recovered the wrong length, failing with "invalid recovered packet
size", or silently corrupted the recovered packet's header extensions when
the length happened to match.
Like libwebrtc's FlexfecReceiver, which skips packets recovered by RTX, mark
RTX repaired sequence numbers and treat them as missing for FEC recovery.
They are still forwarded and update NACK state as before.
With a libwebrtc publisher at 10% upstream loss, every recovery attempt in a
block containing a retransmitted packet failed; with retransmissions excluded
recoveries succeed.
* Move RTX repair tracking into BufferBase
Keep the RTX repaired history, its lookup and the publisher sequence number
extension in BufferBase, so every buffer built on it, such as the relay, can
exclude RTX repaired packets from FlexFEC recovery the same way. The history
is now cleared with the rest of the sequence number state when the stream
restarts.
Buffer only marks repaired packets from writeRTX. Packets recovered by FEC
also enter with isRTX set, but they are exact reconstructions and stay
usable, so marking is explicit rather than tied to that flag.
* Keep RTX-repaired history safe with large packet caches
The RTX repair history had 512 fixed slots. With a larger video packet
cache, e.g. packet_buffer_size_video: 1500, two cached repairs could share
a slot, the earlier mark was lost, and FlexFEC could recover from the
altered retransmission.
- Size the history from the video packet cache, at least 512 slots, and
allocate it on the first repair.
- When a later repair reuses a slot, the earlier packet counts as repaired:
losing a recovery is better than corrupting one.
- Do not mark a retransmission of a packet that is already cached. The
bucket rejects it as a duplicate and keeps the exact packet, which stays
usable for recovery.
- Mark a repair before ingesting it and do not feed RTX repaired packets to
the FEC decoder, as BufferBase now feeds ingested media to the decoder.
* Generate downstream FlexFEC with per-track protection presets
Generate FlexFEC-03 repairs for subscribed video tracks. Subscribers select
none (default), low, medium or high through UpdateTrackSettings.fec; repairs
require rtc.flexfec.downstream_enabled and negotiated flexfec-03 support.
Generate repairs at each frame marker, splitting large frames into blocks of
at most 48 packets, with upstream Q8 repair-count rounding and at least one
repair per block. Reserve measured repair overhead during layer allocation
and charge repair traffic to pacing, bandwidth estimation and metrics.
Carry repair sequence state through the DownTrack GetState/SeedState handoff,
apply subscriber settings from immutable snapshots, and preserve upstream FEC
on shared sendrecv codec lists when downstream generation is disabled.
This squashes the three commits of dc/feature/fec_down (38a67502, d269ac59,
7b02897c) and rebases them onto master. Conflict resolution:
- pacer.Packet keeps master's held-extension scratch next to the FEC field,
and the DownTrack sets FEC on the pacer packet master now creates before
adding extensions
- DownTrackParams and subscriber config keep master's RTXBudget
- configureSenderParams uses master's enableFlexFEC name
- tests follow master: pion/transport v5 packetio, mid-less receivers skipped
when restricting codecs, and settings compared by value since they are
stored as merged snapshots
Requires the UpdateTrackSettings.fec field from livekit/protocol#1794, which
is not in the pinned protocol version yet.
* Add end-to-end tests for downstream FlexFEC
Publish a VP8 track through the SFU to a FlexFEC-capable subscriber,
simulate downstream loss before the subscriber's receive buffer, and recover
the dropped packets from the repairs actually sent, using the same FlexFEC-03
decoder as upstream recovery. RTX is dropped meanwhile so retransmissions
cannot fill the gaps.
The test checks that no repairs are sent before a preset is selected, that
every preset recovers isolated losses bit-exactly, that presets change
without renegotiation, and that a subscriber which declines flexfec-03
receives media but no repairs. Frames alternate between one and five
packets, so repair counts match the Q8 rounding for both block sizes.
The test client gains a subscriber RTP filter to simulate loss and accessors
for the subscriber descriptions. The tests use their own ports so they can
run next to a local server on the default ports.
* Support downstream FEC protection modes
Adopt the FECProtection message from livekit/protocol#1987: subscribers
select a mode (disabled, adaptive, fixed, minimum) and a level (low,
medium, high; unspecified is low) per track. As before, an update that
omits fec keeps the previous setting. Unknown modes disable FEC and
unknown levels are treated as unspecified.
The modes follow libwebrtc's RtpParameters::fec_protection
(webrtc-sdk/webrtc#329):
- adaptive ports VCMNackFecMethod: the kFecRateTable lookup with a 10
second max-window loss filter, key frame boost, ConvertFECRate, NACK
only delta frames below 20ms RTT, and BitRateTooLowForFec. Inputs are
the subscriber's receiver reports, the sent bit and frame rates, and
the forwarded layer's dimensions.
- fixed uses the level for delta and key frames.
- minimum uses the larger of the adaptive rate and the level.
- the adaptive state is updated in every mode, so switching to adaptive
or minimum starts from the current loss history, and a protection
change keeps the group that is accumulating and protects it at the
new rate.
Key frames get their own protection factor, so pacer packets carry a
key frame flag. Repairs are still generated per frame; multi-frame
blocks (max_fec_frames) are not supported.
The end-to-end tests report the simulated loss in receiver reports,
since the test client sends none, and check that adaptive protection
sends no repairs without loss and protects with loss, and that minimum
protection matches its level without loss and rises with loss.
Requires livekit/protocol#1987, which is not in the pinned protocol
version yet.
* Point protocol at livekit/protocol#1987
* Report loss before repair in receiver reports to publishers
Receiver reports counted packets restored by RTX or recovered by FlexFEC
as received, so as long as repairs kept up the reported fraction lost
stayed at zero, even with 20% upstream loss. libwebrtc receivers exclude
recovered packets from their receive statistics, and a publisher's
loss-based protection depends on that: with no reported loss, FlexFEC
backs off to almost no repairs.
Packets that fill a loss through a repair are now counted separately, and
receiver reports include them in the fraction and cumulative loss.
Reordered packets that arrive on their own still cancel the loss. The
fraction is also capped at 255, so a full loss no longer wraps to zero.
With 20% simulated upstream loss from an Android publisher, the reported
fraction lost goes from 0 to about 0.15, the FEC packets received over 30
seconds go from 64 to 204, and the packets recovered by FEC from 11 to 61.
* Protect zeroed abs-send-time and TWCC in downstream FlexFEC
The pacer encoded FEC after it had filled in abs-send-time and the
transport-wide sequence number. libwebrtc generates FEC before its sender
fills them in, and its FlexFEC receiver zeroes both in media packets before
recovery. Packets recovered from SFU repairs therefore got wrong bytes in
those extensions, and in the payload when the header lengths within a group
differed, for example when only the first packet carried abs-capture-time.
Zero both extensions after the media packet is written and before it is
fed to the encoder.
* Aggregate receiver report loss for adaptive FEC protection
Adaptive and minimum protection fed the fraction lost of every reception
report into the max-window loss filter. libwebrtc receivers can send a
report with each NACK, so a report often covers only a few packets and its
fraction lost is very noisy. With 10% random loss, single reports read up
to 70%, and the filter kept the maximum.
Derive loss from the cumulative counters instead and produce a sample only
once it covers at least 20 expected packets, like libwebrtc's
SendSideBandwidthEstimation::UpdatePacketsLost. The end-to-end tests now
report cumulative loss and the extended highest sequence number in their
receiver reports.
* Report loss before repair only to FlexFEC publishers
Counting repaired packets as lost in receiver reports applied to every
publisher, so any publisher whose loss RTX repaired started to see that loss
and its bandwidth estimate could back off sooner. Only FlexFEC protection
needs loss before repair to choose its rate.
Count repairs only for streams that negotiated flexfec-03, which requires
FlexFEC to be enabled on the server. Other publishers keep receiving loss
after repair, as before.
* Keep the newest RTX repair mark of a history slot
A late retransmission of an older packet that has aged out of the cache
overwrote the slot of a newer repair sharing it. The newer repair, which
carries the RTX packet's header, could then be used for FlexFEC recovery and
corrupt the recovered packet.
Keep the highest extended sequence number written to a slot until the stream
restarts. isRTXRepairedLocked already treats an older packet in a slot with a
newer mark as repaired.
* Measure FEC overhead against all media
The allocator scales the whole media bitrate by the measured repair
overhead, but the overhead was measured against protected media only. With
adaptive protection below 20 ms RTT only key frames are protected, so the
ratio of key frame repairs to key frame media was applied to every frame,
and the reservation could make the allocator lower the layer or pause the
track although the bandwidth was sufficient.
Count all non-padding media while any protection is active.
* Keep the loss sample that closes a filter window
The max-window loss filter, ported from libwebrtc, dropped the report that
closes a one-second window when the window already had a maximum, so a loss
spike arriving on the boundary never reached adaptive protection. Store the
larger of the window's maximum and that sample.
* Skip the encoder allocation check under the race detector
CI runs the tests with -race and swaps sync.Mutex for go-deadlock, whose
Lock allocates, so Encode allocated about once per call there. Check
allocations only without the race detector, like the other allocation tests.
* Bump protocol to v1.55.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: reserve measured FEC overhead only on the forwarded layer
The measured repair overhead comes from the spatial layer being
forwarded. On a low layer with one or two packets per frame it can be
60-100%, and applying it to every layer reserved the high layer at
nearly twice its cost, so the allocator could stay on the low layer.
Attribute measurements to the forwarded spatial layer, restarting them
when forwarding starts, resumes or switches layers, and reserve the
configured rate for the other layers.
Also reallocate only when a reserved overhead moves by 5 points or
more, or turns on or off, so that per-second measurements and adaptive
protection do not re-run allocation on every receiver report.
* buffer: gate upstream FlexFEC on an explicit flag
A publisher PC registers flexfec-03 when only downstream FEC is enabled,
because it can also carry subscriptions. Its buffers then got a FEC
payload type, which reported loss before repair to the publisher and
let the decoder start from the observed repair SSRC, although upstream
FEC was disabled.
Buffers now ignore the negotiated FlexFEC payload type unless the buffer
factory enables upstream FlexFEC.
* pacer: protect interceptor-written transport-cc as zeros in FEC
With UseSendSideBWEInterceptor, Pion's TWCC header extension
interceptor writes transport-cc during WriteRTP while the DownTrack
leaves TransportWideExtID at zero. The extension was then protected
with its non-zero value, which the receiver zeroes before recovery, so
recovered packets got wrong bytes there.
Pass the negotiated transport-cc ID to the pacer for FEC and zero it
before encoding as well.
* sfu: skip the FEC encoder while protection is disabled
The encoder was attached whenever flexfec-03 was negotiated, including
in the default disabled mode, so every forwarded packet took the
encoder lock and updated the adaptive state without generating repairs.
Pass the encoder to the pacer only while protection is enabled. Receiver
reports still keep the loss history; adaptive protection measures media
rates again once enabled.
* sfu: account sent FEC repairs in the down track RTP stats
Repairs were counted only in the aggregate Prometheus counter, so the
down track's stats under-counted what the subscriber receives. Record
them in the sender's FEC packet and byte counters, separate from media,
and export the FEC counters in RTPStats for both directions.
* rtc: merge subscriber FEC settings in one place
The subscription merged and normalized settings, and the subscribed
track merged and normalized them again, while the DownTrack mapped
unknown modes and levels a third time.
Merge only in the subscription, store the merged settings in the
subscribed track as is, and leave unknown values to the DownTrack.
* prometheus: resolve fixed-label FEC counters once
RecordFECDownstream runs on the pacer path for every repair batch and
looked up both counter vectors by label each time.
* rtpstats: seed a sender without holding both locks
Seed took the receiving sender's lock and then the source's, so two
senders seeding from each other at the same time could deadlock. Copy
the source's state under its own lock first, then apply the copy under
the receiving sender's lock.
* telemetry: count FlexFEC repairs in traffic totals
Retransmissions and padding count towards node and participant
traffic, but FEC repairs, which are also on the wire, did not. Add
repairs sent and received to the node packet and byte totals, and to
the packets and bytes of TrafficStats.
Analytics streams are unchanged: AnalyticsStream has no FEC field.
* sfu: read the FEC transport-cc ID atomically
setRTPHeaderExtensions runs again when the stream allocator listener is
set, which can happen while media is already forwarded, and WriteRTP
read the ID without synchronization. Store it atomically once the
extensions are processed.
* telemetry: count only FEC repairs sent in node traffic
Media recovered from FEC repairs is counted as received media, so
adding the repairs received to node ingress counted recovered packets
twice. Node traffic feeds room admission against limit.bytes_per_sec,
so ingress must not be inflated. Keep repairs sent in node egress,
where nothing is synthesized, and leave ingress as before.
TrafficStats is derived from RTPStats without a direction, so it cannot
tell repairs sent from repairs received; leave it without FEC.
* rtc: add WebRTCConfig.SetFlexFEC for per-session FlexFEC settings
* rtc: apply a session's upstream FlexFEC to its buffers
SetFlexFEC changed what a session negotiates with its publisher, but the
publisher's buffers still followed the node config: the room's buffer
factory read it once. A session with upstream on and a node with it off
negotiated flexfec-03, so the publisher sent repairs that its buffers
ignored; the reverse turned on upstream recovery and loss reported before
repair for a session that asked for neither.
The session's buffer factory now follows the session's upstream setting,
whichever of SetFlexFEC and SetBufferFactory comes first. Without a
SetFlexFEC call it follows the node config, as before. The setting applies
to buffers the factory creates afterwards, so SetFlexFEC is meant to be
called while the session is set up, before any track is published.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Jules Testard <jules.testard@livekit.io>
Co-authored-by: David Chen <chenosaurus@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Add a new gauge that counts active rooms whose name does not match a
configurable regex. This lets operators keep synthetic rooms (load
tests, health checks) out of autoscaling and dashboards, without
changing livekit_room_total.
Config:
prometheus:
port: 6789
room_exclude_regex: "^(loadtest|healthcheck)-"
Behavior:
- Disabled by default. With an empty room_exclude_regex the metric is
not registered and nothing changes.
- RE2 syntax, unanchored match.
- An invalid regex fails server startup with a clear error.
- Same node_id/node_type labels as livekit_room_total.
- livekit_room_total and the RoomStarted/RoomEnded signatures are
unchanged. The new hooks sit next to the existing calls in
RoomManager.
Tests cover invalid/empty patterns, include/exclude counting, the
existing metric staying unchanged, and safe no-op when disabled.
* service: send queued webhooks before shutdown completes
Start returned, and the process exited, while the room_finished webhooks
of the rooms closed by the shutdown were still queued. Stop the telemetry
service at the end of Start so it flushes its queue and drains the webhook
notifier, waiting up to 5s.
* Bump protocol to pick up the ResourceURLNotifier drain fix
ResourceURLNotifier.Stop(false) now waits for the queued events to be sent (livekit/protocol#1901), which the shutdown change relies on.
* telemetry: keep the analytics of webhooks sent during stop
The notifier's processed hook queues a WEBHOOK analytics event for each webhook it sends, but Stop stopped the jobs queue before draining the notifier, so those events were dropped. Run the queued events with a barrier, drain the notifier, then stop the queue.
* Pass CPU stats options through prometheus.Init
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Add node_stats.host_cpu config to measure whole-host CPU
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Bump protocol to ignore the CPU request with host CPU stats
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: replace forward scheduling delay with processing per subscriber
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: describe processing per subscriber as per write
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* telemetry: name forward processing metrics per write
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Pin protocol with NodeStats forward_processing_per_write
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: report forward scheduling delay next to forwarding latency
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: keep full forwarding transit when packing scheduling delay
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: saturate reported forwarding p90s instead of wrapping
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: cap retransmissions per down track (rtc.rtx config, off by default)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: rtx budget review fixes (sequencer undo, sent bytes, newest first, rtx_budget)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: rtx budget second review (order unchanged when off, keep NACK window, metric in down track)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: rtx budget sorts NACKs newest first by extended sequence number
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: measure subscribe pacing delay in shadow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* prometheus: raise the subscribe pace shadow top bucket to 120 s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: pace video subscribes per node in shadow, record the wait only
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: subscribe pacer doc wording, make the wiring test independent of timing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: sample shadow pacing at arrival, skip one-shot, keep sub-millisecond waits
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: take the shadow pacing token before setup, in arrival order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: build shadow pacing buckets in one pass
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Add upstream FlexFEC recovery support
* Guard short TWCC extensions in FEC packets
* Release completed FlexFEC states
* Validate FlexFEC payload type range
* Invoke FEC callbacks after unlocking
* Reduce FlexFEC protection state allocations
* Avoid allocations for complete FlexFEC packets
* Optimize ordered FlexFEC packet insertion
* Reuse RTP packet storage for FlexFEC recovery
* Limit pending FlexFEC repair packets
* Lower FlexFEC repair window to two seconds
* Harden upstream FlexFEC handling
* Test FlexFEC with E2EE media
* Fix FlexFEC negotiation with libwebrtc publishers
* Enhance payload length validation in decoder
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* remove the ability to configure payload type for FlexFEC
* moved some helpers into protocol
* Handle big gaps in media sequence numbers
Reset buffers when a big gap in media sequence numbers is detected.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* bump protocol & psrpc deps
* Handle FEC packet recovery failure
Increment FEC packets discarded counter and remove packet.
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
* do not NACK on fec recovered packet (#4896)
* do not NACK on fec recovered packet
* fix test race in CI
* Fix FEC write return after merging RTX feedback changes
* PR fixes for FlexFEC implementation (#4898)
* do not NACK on fec recovered packet
* refactor common code into unlockAndInvokeFECRecovery
* add FEC stats to RTPStats
* add log for when fecdecoder unavailable after creation
* rename markAsFECRepair to setFECRepairBufferLimit for clarity
* refactor packet generation for tests into util
* fix test race in CI
* move the unlocks back inline for readability
* update RTPstats
* Fix FEC write return after merging RTX feedback changes
* Use shared RTP packet helper in merged FEC NACK test
* Remove redundant return from FEC write handler
* packet post process (#5020)
* packet post process
* remove redundant writeRTX
* send out RTCP (NACK and RR) from packetPostProcess only
* handle FEC decoder on receiver restart (#5032)
* handle FEC decoder on receiver restart
* move onStreamRestartLocked into BufferBaseParams
---------
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Raja Subramanian <raja.gobi@tutanota.com>
* sfu: report forwarding latency as p90 instead of the mean
The forwarding-latency metric was the mean transit over all forwarded
packets. A mean is dominated by a few slow outliers, so a handful of
packets stalled on the forward path (e.g. goroutine scheduling latency)
inflated the whole node's reported latency even when nearly every packet
was forwarded promptly.
Report p90 instead: p90 rising means roughly a tenth of forwarded packets
are slow, a broad signal of systemic forwarding load rather than a sparse
tail. To read a percentile over the report window, the mergeable
per-interval summary now keeps a small power-of-two-bucket histogram of
transit instead of running moments (sum, sum-of-squares).
Drop the jitter (transit std dev) gauge: nothing consumed it, and any
spread is derivable from the forward-latency histogram. The protobuf
ForwardJitter field is left in place, now unset, to deprecate separately.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: clamp forwarding percentile to the observed [min, max]
Bucket interpolation assumes a uniform fill, so a single 20ms packet (or
uniform traffic) could report a p90 above every observed sample. Clamp the
interpolated value to the summary's already-tracked min/max, so a quantile
never falls outside the data. Exact for single samples and repeated
identical latencies.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: fix stale p50 comment in the percentile test
The reported metric is p90; the test comment still said p50 replaced the
mean. Reword it to reflect that a percentile, not the mean, is reported.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: quarter-octave forwarding-latency buckets for threshold resolution
Octave buckets are too coarse near the overload thresholds: 300us falls in
[256,512), so a p90 clustered at ~265us and one at ~500us interpolate to the
same value and would trip (or not) identically. Split each octave into four
linear sub-buckets so the two land in different buckets, on the correct side
of the threshold. Min/max clamping alone does not fix this once a node has a
high tail, since its max no longer bounds the interpolation.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: interpolate percentiles within each bucket's observed range
Replace the quarter-octave split with plain octave buckets that also carry
the observed [min, max] of their samples, and interpolate a percentile
within that range instead of the bucket's nominal edges. This is exact when
a bucket's samples cluster, so a p90 near an overload threshold that falls
mid-bucket lands on the correct side of it regardless of bucket width -- no
threshold-aware boundaries needed. It subsumes the min/max clamp, since an
estimate can no longer leave the observed samples.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: cover the 500us cluster in the threshold test
Assert milos's full review example exactly: 265us and 500us clusters that
octave-nominal interpolation both read as ~341us now read 265us and 500us.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: make forwardSummary.addSample a pointer receiver
The summary grew from a small moments struct into a per-bucket histogram
(~700 bytes), so the value-receiver addSample copied the whole summary on
every drained sample in the flush loop. Mutate in place instead: ~28ns ->
~2ns per sample in the background fold, no behavior change.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* sfu: eighth-octave buckets for accuracy near thresholds
Split each octave into 8 linear sub-buckets (was plain octaves). With the
per-bucket min/max interpolation this reports a tight p90 cluster exactly
even when it sits mid-octave: 850x265us + 150x410us now reads 410us (above a
400us threshold) instead of 395.5us, and a lognormal p90 lands within ~0.2us
of exact. Per-sample add cost is unchanged (~2ns); cost is ~5KB per summary
and a larger but per-report merge.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Reverts #4816. Since livekit/cloud#4747 a room re-key closes every
participant's stats worker under the old room id and opens a new one
under the new id (LeaveSession/JoinSession, #4917), so RoomIDChanged
and reKeyRoom have nothing left to move, and with them go the sealed
stats batches, SetRoom, ForceClose and the reference hand-over that
only the re-key collision case needed. The worker map goes back to a
flat (room, participant) key.
The guard fixes that landed after #4816 (#4817, #4856, #4860) are kept.
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* agent: release JobTerminate handler when job ends before registration
JobRequest registered the job's JobTerminate handler after AssignJob
returned, so an ended UpdateJobStatus or worker disconnect handled in
between deregistered nothing and the handler leaked. AssignJob also sent
the assignment before recording the job as running, so an immediate
ended update was dropped.
Record the job before sending the assignment, and after registering the
handler recheck under h.mu that the job is still running and its worker
still registered, deregistering otherwise.
Fixes#4901
* replace utils.CloneProto with proto.CloneOf
* agent: wait on worker readiness and poll for released handlers in test
* telemetry: do not recreate a stats worker for a released guard
A ParticipantActive overtaken by the participant's close arrives with a
guard ParticipantLeft already released and replaced the closed worker
with one nothing could release.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* telemetry: handle a released guard independently of map presence
A released guard reaching getOrCreateWorker after the closed worker was
reaped still created a zero-reference worker. Return nil as found
instead, and make SetConnected nil-safe for ParticipantActive.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
* telemetry: add visibility into stats worker reference underflow
Log the paths that can leave a stats worker with no references, so the
`-1` never-closed cases seen in production can be traced to their origin.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
* telemetry: guard StatsWorker.MarshalLogObject against a nil receiver
The new worker-created log passes the existing worker, which is a typed
nil when there is none. Mirror ReferenceGuard.MarshalLogObject.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
getCPUStats has no callers: node CPU load comes from hwstats.CPUStats in
GetNodeStats, and nothing in the tree reads getCPUStats. Only getLoadAvg
is still used.
Remove the function from both the windows and non-windows variants along
with the state it kept. getLoadAvg is untouched, and go-osstat stays a
direct dependency through it.
Co-authored-by: XiaoShao <26596822+xiaoshao9704@users.noreply.github.com>
* telemetry: support roomID change for a participant
A room can get a new id while participants are connected. Key stats
workers as map[roomID]map[participantID] so moving a room is a single
map splice, and add reKeyRoom/RoomIDChanged to do the move.
Stats collected before the change are sealed off with the room they
were collected in so they stay attributed to it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* telemetry: close superseded worker on re-key collision
Only one worker can be keyed at (room, participant). If a re-key lands
on a room that already has a worker for the same participant, keep the
one already filed there and close the superseded one so it drains and
is reaped instead of lingering in the flush list.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
* telemetry: hand references to the successor on force close
A ReferenceGuard records that it activated some worker, not which one,
so a superseded worker cannot just drop its references - the survivor
would be left with references it never sees released and would never
close. Hand them over instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* report a reason on room-ended telemetry
Room.Close already took a ParticipantCloseReason, but OnClose was func()
with no arguments, so the reason was structurally dropped before it could
reach RoomEnded.
Add types.RoomCloseReason and carry it through Close -> OnClose -> RoomEnded,
where it lands on both the analytics event and the room_finished webhook.
Room.Close now takes the room reason and derives the participant reason from
it, so the two can never disagree. ToParticipantCloseReason maps each reason
to exactly what its call site passed before, so no participant-facing
behaviour changes; a table test pins that mapping.
* fix(test): update webhook test for RoomCloseReason
test/ was outside the packages checked before pushing, so this Close call
site was missed. Also assert the reason reaches the room_finished webhook,
which the unit test cannot cover since it runs with a nil notifier.
* Fix publish track count on migration in.
https://github.com/livekit/livekit/pull/4707 addressed the case of
publish tracks overcounting due to synthesised track publish on migrate
in. But, it introduced an issue where published tracks count could go
negative because unpublish subtracted the counter irrespective of the
track actually migrated in or not.
Fix it by keeping track of local publish.
Also, the older code was skipping publisher track count increase if the
synthesised publish was handled first. Address it by checking if the
track is actually new (i. e. fresh local publish) when the track was
already created in the migrate in path.
* fix pub time for tracks published after migration
* test
* prevent multiple track egresses
* pass room proto directly to telemetry events
* Keep telemetry analytics events on a minimal room, gate full room in webhooks
---------
Co-authored-by: Simon Beeli <simon.beeli@gmx.ch>
- Count a publish attempt on a migrating in tarck as there is no
AddTrack for that.
- Add cancel publish only if the participant connection is canceled
- Do not add publish counter for synthetic publish attempts which
happens for migrating in tracks. It will be counted on migrating in
node when the track is actually published, i. e. negotiated/packets
flowing.
* 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
Newer kernels report qdisc stats via TCA_STATS2 (Stats2) while older
kernels only populate the legacy TCA_STATS attribute (Stats). Whichever
is unused is left nil, so unconditionally dereferencing Stats crashed
with a SIGSEGV during telemetry init. Prefer Stats2 and fall back to
Stats, skipping when both are nil.
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Leave out canceled attempts. Should make it easier to do percentages.
Not putting these in node stats yet. Will observe in prom before using
it in node stats.
* Prometheus metric for join latency.
Also including a couple of other failures in the signal connection path
and moving the signal connected to after all that.
Not doing counters for the new signal failure paths. I should not have
done for the other two I added a little while ago also (
validation failure and start participant failure) as those are not
scalable to keep adding to node stats. Will probably remove those two
from node stats later. Can add those counters if they are useful.
* deprecate signal failed counters
* Add prom metrics for peer connectino state.
By direction (PUBLISHER vs SUBSCRIBER) and state ("started" ->
"connected"). This gives a way to track peer connections failing to
finish establishment.
The RTC active count can be useful for primary peer connection, but not
for non-primary. This counter can be used to track any and can generally
be used to understand success/failure rate of peer connection
establishment.
* add a couple of more states
* clean up and avoid duplicate reporting fully established
* staticcheck
* Metrics for participant active, i. e. fully established.
- Egress stub for v2 API
- Fix the participant canceled counter 🤦
- Add active counter -> this is increment when a participant becomes
active, i. e. primary peer connection established. Can be used to
monitor node wise connection establishment issues.
- Add singnalling validation fail counter.
With this, we have
- signalling validation fail
- signalling failed --> this is when the `startSession` fails
- signalling connected -> signalling is succesful and can send back
joinResponse to client
on media connection side
- rtc_init -> start
- rtc_connected -> participant session created (joined)
- rtc_active -> primay peer connection established
- rtc_canceled -> could not proceed with RTC connection due to not being
able to resume.
* signalling counters deps
* revert pion/webrtc to 4.2.12 to get SCTP without interleaving
* go back to pion/webrtc 4.2.11 and sctp 1.9.5
* telemetry: split webhook-processed hook registration out of NewTelemetryService
NewTelemetryService used to register a notifier processed-hook on the inner
*telemetryService directly. That made it impossible for downstream wrappers
(e.g. cloud's TelemetryService that overrides Webhook to fan out to a v3
observability pipeline) to intercept webhook events without double-firing
the legacy emission.
Lift the registration into a new exported helper RegisterWebhookHook, and
have the standalone server's wire provider createTelemetryService call it
right after construction so behavior is unchanged for callers that don't
wrap the service.
* Apply ttl check only when authenticate allocation creating
TTL check could reject allocation/persmission refresh in
security enhancement #4505, cause long-live session disconnect
when turn credential is expired.
Only check ttl on allocation creating to prevent abusing leaked
credential but keep long-live session work.
* Key telemetry stats work using combination of roomID, participantID
With forwarded participant, the same participantID can existing in two
rooms.
NOTE: This does not yet allow a participant session to report its
events/track stats into multiple rooms. That would require regitering
multiple listeners (from rooms a participant is forwarded to).
* missed file
* data channel stats
* PR comments + pass in room name so that telemetry events have proper room name also
Published counter was bumped up only when not migrating in, but it was
decremented when a migrating participant leaves without expectation to
resume. That could have resulted in negative counts.
Always change counters irrespective of migration or expected to resume
on leave. Control events send based on migration/resume.