Chrome 149+ offers the post-quantum hybrid group X25519MLKEM768 (DTLS 1.3)
with a key share. As DTLS server, pion picks the first curve in its own
list that the client supports, so X25519MLKEM768 leads there. As DTLS
client, X25519 stays first to keep the ClientHello unfragmented, since
some DTLS servers (e.g. older mbedTLS on ESP32) reject a fragmented one.
Enabled by default in the OSS server; EnableDTLSPQC lets embedders such
as Cloud gate it.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat(secure-input): add a data packet receive hook and sip method stubs
* refactor(secure-input): bump protocol for sensitivity class names
* fix(secure-input): normalize data packets before caching them for joiners
* refactor(sensitive-input): rename secure input to sensitive input and bump protocol
When a WHIP PATCH carries an If-Match that no longer matches the
publisher's ICE session, the RTC node returns psrpc.FailedPrecondition,
but iceTrickle had no case for that code and answered 500. RFC 9725
section 4.3.1 requires 412 Precondition Failed, which is also what
psrpc's own ErrorCode.ToHTTP maps FailedPrecondition to.
Also pass the error instead of nil to handleError in the non-psrpc
branches of iceTrickle and iceRestart. handleError calls err.Error(),
so a nil error would panic. The psrpc client wraps all of its own
failures today, so this is hardening.
Add a unit test for the PATCH status mapping and an integration test
that drives a real WHIP session through trickle and ICE restart.
UpdateEgress indexes an ended egress in the ended_egress hash as
"<room>|<endedAt>". parseEgressEnded split the value on every "|" and
required exactly two parts, so an egress from a room whose name
contains "|" could not be parsed. Room names have no character
restrictions, so such rooms can exist.
CleanEndedEgress returns on the first parse error. The entry is
therefore never removed: its egress record, ended_egress entry and
egress:room:<room> member stay in Redis, and every node logs
"could not clean egress info" every 30 minutes. Entries after it in
the hash's iteration order are also skipped for that sweep.
Split at the last "|" instead, since the timestamp cannot contain it.
The stored format is unchanged, so entries already stuck before this
change are cleaned on the next sweep.
* rtc: hold the disconnect cleanup while a participant migrates out
The disconnect cleanup closes a participant as a leave 5 s after a
transport failure. A participant that is migrating to another node at
that moment is reported as gone while its session continues there.
LocalParticipantHelper.IsMigratingOut reports whether another node is
taking over the participant. While it is true, the cleanup checks again
every 5 s, for at most 75 s. The room manager here returns false.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* rtc: a disconnect cleanup cleared during its migration check does not close
The cleanup checked that its timer was still set before a reset, but not
before a close. A check that was in flight when the timer was cleared
could still close the participant.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* rtc: clarify the disconnect cleanup comments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
CreateIngress and UpdateIngress stored a room name, participant identity, name or metadata over the configured limits. The ingress then joins with a token holding those values and CheckConnectLimits rejects the join, so the ingress was created but could never connect. Run the same check in the API, as CreateRoom and UpdateParticipant do.
* Replay missed disconnects on resume from the client's last pong time
A resuming client can send the timestamp of the last Pong it processed.
The server replays the participant disconnects newer than the earlier of
that time minus 1 s and the last signal receive time minus 3 s. Requests
buffered by an offline client move the last signal receive time to just
before the resume, the last Pong time does not move.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Take the test pong time from the cached disconnect time
The simulated pong time came from time.Now(), so a pause of more than
1 s after the disconnect was cached moved the disconnect out of the
look back.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Exercise the pong look back in the replay test
A pong time equal to the disconnect time is replayed without the 1 s
look back too. Use a pong time 500 ms after the disconnect.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
* service: answer StopEgress for an ended egress without waiting
A stop for an egress that already ended finds no server subscribed to its
topic. On NATS psrpc reports that at once, but its retry interceptor then
waits out the request timeout before each retry, so the API answered 412
only after about 8 s.
StopEgress now sends the stop without psrpc's no-subscriber retry and asks
the IO service for the egress instead. An ended egress gets 412 and an
unknown one 404 at once. A starting or active egress that nothing is
subscribed for yet is retried every second for up to 3 seconds.
DeleteIngress and UpdateIngress only log a failed RPC to the ingress, so
they send it without the no-subscriber retry too.
Bumps psrpc for middleware.WithoutNoSubscriberRetry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* deps: bump psrpc to claim queue rpcs on non-NATS buses
psrpc after v0.8.2 stopped claiming queue rpcs, so on the local and Redis
buses a queue rpc with no subscriber timed out instead of failing with
ErrNoResponse after the selection timeout. That broke
TestJobTerminateReleasesJob. The new pseudo-version claims queue rpcs again
on buses that do not report unsubscribed requests.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* service: retry an active ingress the way StopEgress retries a live egress
UpdateIngress and DeleteIngress send their RPC only when the stored state
says the ingress is buffering or publishing. When no ingress is subscribed,
they now reload the ingress and retry every second for up to 3 seconds
while it is still active, as StopEgress does for a live egress. A stale
state that is no longer active returns at once. The RPC error is still only
logged.
The retry timing is shared by egress and ingress, so it is renamed from
stopEgressRetry* to noSubscriberRetry*.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
* deps: pin psrpc to the merged livekit/psrpc#177
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uq3jhDWWfeXi18uQ1wMJv6
---------
Co-authored-by: Claude <noreply@anthropic.com>
* Apply a fallback learned on resume to the same resume
A short failed connection reported on resume can learn a TCP or TLS
fallback. The room manager resolved the resume ICE config before that
check ran, so the reconnect response, its ICE servers and the ICE
restart used the old config, and the fallback applied only on the next
attempt.
ResumeParticipant now runs the short-connection check after the signal
is valid again, then asks the caller to resolve the ICE config and
servers. HandleReconnectAndSendResponse no longer runs the check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep a pending fallback and skip ICE/TCP without a listener
A short failure of a UDP pair cleared a TCP or TLS preference that was
set after the pair connected. A client report of the same failure on
resume then removed the fallback the server had just chosen.
A UDP failure also chose ICE/TCP on a node with no ICE/TCP listener.
TCP mode drops UDP candidates, so the restart had no usable candidates.
It now chooses TURN/TLS when that is on, else it keeps UDP.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Test the resume ICE resolver in the room manager
The resume test in pkg/rtc supplies its own resolver, so it did not
run the room manager code that picks the ICE config and the ICE
servers. Move that code to resumeICE and test that a learned TLS
fallback gives the TLS config and drops the non-TLS TURN servers.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Skip the client failure check when a fallback is pending
The selector change that kept a preference on a UDP failure could trap
a participant in TCP mode. When the subscriber restarted in TCP mode and
never connected while the publisher still had its UDP pair, the
selector kept TCP and the next resume tried TCP only again.
Restore the selector. The client report on resume no longer clears the
guard, so it does nothing when the server already chose a fallback for
that failure, and the fallback stays for the ICE restart.
Add resume cases for a UDP failure that the client reports on a node
with no ICE/TCP listener.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
* Pick the fallback from the transport that failed
The selector used one connection type for both transports, so it could
not tell an old UDP pair from a transport that restarted with a
preference and did not connect.
It now gets the connection type of the transport that failed.
- A UDP pair that fails with a preference set keeps the preference. The
pair is older than the preference, and the ICE restart applies it.
- A transport that did not connect in TCP mode moves to TURN/TLS. It
went back to no preference before, so a client could alternate
between UDP and TCP and never reach TURN/TLS.
- A transport that did not connect with a preference counts as a short
failure. A TURN/TLS preference that cannot connect then goes back to
no preference on the first failure.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* Let clients set a preferred ICE candidate protocol on join
The v1 JoinRequest ConnectionSettings.candidate_protocol and the v0
candidate_protocol query parameter let a client ask for TCP or TLS
from the start. The SFU applies the stronger of the client preference
and the learned room fallback, and keeps the join preference on resume.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Require the candidate protocol on every connect, check ICE/TCP
Resume uses the preference from the resume request, the same as join,
so the participant no longer stores the join value. TCP mode drops UDP
candidates, so a TCP preference applies only when ICE/TCP is enabled,
and TLS without TURN/TLS falls back to TCP only under the same check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Keep the client preference apart from the learned fallback
The room cache now holds only fallbacks the transport learned after a
failure. The participant stores the client preference from join, and
resume applies the stronger of it and the resume request before the
resume response, so the response carries the matching ForceRelay.
TLS mode lists only TLS relays, also from external TURN servers.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Let a resume preference replace the join preference
A resume that sends TCP or TLS uses that value, and only a resume
without a value inherits the preference from join.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* Ignore an unsupported preference on resume
A resume preference for a transport the server does not offer no
longer replaces the join preference. Each preference is lowered to a
supported transport before the resume picks between them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* feat: add token revocation
* token revocation: match LiveKit Cloud API, make it optional
- add token_revocation config section (enabled: false by default, ttl)
- RemoveParticipant: cutoff defaults to now, revoke_token_ts must be within
60s and is stored with the validation leeway, revoke absent participants,
keep not found unless revoke_token_ts is given
- UpdateParticipant revokes older tokens on permission updates and the
participant gets a refreshed token
- share the RoomService logic with Cloud through RevokeTokenClient
- revocations merge to the later cutoff and expiry
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: clean up expired revocations lazily
Drop the cleanup goroutine of LocalStore. Revocations are kept in a queue
ordered by expiry, and expired ones are removed from its front when
revoking or checking, at most once per minute.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: request context for redis, own lock for LocalStore
- RedisStore revocation calls use the request context
- LocalStore revocations use their own lock instead of the store lock
- remove TestRTCValidateRoomlessTokenAfterRevocation, which passes without revocation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: length checks before auth, test all auth chains
Check lengths before the admin permission check, as LiveKit Cloud does, and
test that the API, agent endpoint and WebTransport chains reject revoked tokens.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* token revocation: do not return store errors to clients
Log the error of a failed revocation lookup and respond with a fixed message,
as the store error may contain internal addresses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: cnderrauber <zengjie9004@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
lk.rtc.joinRequestTime was set only for standard participants. SIP,
agent, egress and other participants now get it too, so the time a
participant reached the signal node is known for every kind.
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.
* config: count lk. participant attributes against their own size limit
LiveKit services set participant attributes with the lk. prefix. These
attributes now count against a new max_lk_attributes_size limit
(default 1024 bytes), so they do not use up the customer's
max_attributes_size budget. All attribute size checks enforce both
limits and keep the existing error types.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* rtc: check attribute limits against the merged participant attributes
UpdateMetadata checked only the attributes in the update, but
SetAttributes merges them into the stored attributes. Sequential
updates could each pass and leave the participant above either limit.
The check now runs on the attributes that the update would store.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: return invalid argument when merged attributes exceed a limit
The admin API checks only the attributes in the request. The participant
checks them merged with the attributes it already has, so a request can
pass the first check and fail the second. That error reached the caller
as unknown. Return InvalidArgument for it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Unity WebGL runs livekit-client in the browser. Parse its user agent for
browser/OS info, and apply the iOS WebKit limitations to it like JS.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* agent dispatch: carry thread_id from dispatches to jobs
* agent dispatch: validate thread_id as an AT_ agent thread id on the API
* agent dispatch: validate thread_id with protocol agent.ValidateThreadID
* agent dispatch: report an invalid thread_id as a Twirp InvalidArgument on thread_id
When an Allocate has no REQUESTED-ADDRESS-FAMILY, as from browsers,
pion picks the relay family from the address the client reached. The
default bind address 0.0.0.0 is a dual-stack listener, so a client that
connects over IPv6 gets a udp6 relay, which the IPv4 bind address
cannot open. Every allocation fails with 508 Insufficient Capacity and
the client gets no relay candidate.
Set StrictAddressFamily, which keeps the RFC 8656 default of an IPv4
relay, when no bind address is IPv6. Those nodes could never open an
IPv6 relay, so no allocation that succeeded before changes. With an
IPv6 bind address, pion's default is kept.
Fixes#5131
Inbound trunk numbers are compared to the user part of the called URI,
so a sip:, sips: or tel: URI never matches a call. Reject new URI
entries on create and update. Entries already stored on a trunk stay
allowed, so existing trunks can still be updated.
whipService.Create waits for every track listed in
SubscribedParticipantTracks. The errgroup context was discarded and each
goroutine only exited once its track was subscribed, so a track that
never appears (a wrong name, a publisher that left) kept the request and
a polling goroutine per track running forever, long after the caller
had timed out.
Move the wait into waitForSubscribedTracks and have it return when the
request context is done or the participant has closed.
Fixes#5152
Stores that filter trunks by exact number, such as the Cloud database,
only normalize the called number, so a stored 15550001002 never matches
a call to +15550001002. Normalize numbers on create and update, including
the stored list and the Remove values, so that old rows are fixed on edit.
* agent: stamp the accept and assignment times of a job attempt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* deps: pin protocol with the job accept and assignment times
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: stamp a new user's join request time as an attribute
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: use the lk.rtc.joinRequestTime name
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* deps: pin protocol with the join request time attribute
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* deps: pin protocol main, keep turn and srtp on pion/transport v4
The warp forks of webrtc, dtls and ice are still on pion/transport v4.
Protocol main requires turn 5.1 and srtp 3.1, which moved to v5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* deps: pin protocol v1.53.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* test: expect the join request time among a participant's attributes
The server now stamps lk.rtc.joinRequestTime on a new standard participant, so
other participants see it beside the token's attributes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: ignore a nil publisher sender report in the forwarder
A stream restart replaces the receiver stats between the sender report
callback and its read, so the report can be nil. SetRefSenderReport now
keeps the previous report instead of reading the nil one.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* dynacast: skip a codec regression when the target codec has no quality
HandleCodecRegression looked up the target codec after it released the
lock. If the manager closed in between, or the target mime type was
unknown, the lookup returned nil and RegressTo called Restart or Replace on
it. The target is now looked up with the source, and a missing one stops
the regression.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: create the internal record for a stored room that has none
RedisStore.LoadRoom returns a nil RoomInternal without an error when the
room exists but its internal field does not, for example after a delete
races a store. CreateRoom then wrote egress, agent, playout delay or sync
settings into the nil record. It now starts from an empty record, which
the store call writes back.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: drop a dependency descriptor whose chains do not match the structure
The parser takes a new structure from any packet, but DDForwarder keeps
the structure of the last packet it forwarded. When the publisher attached
a structure with fewer chains to a packet this downtrack dropped, the next
descriptor had fewer chain diffs than the forwarder's structure, and the
writer indexed past them. The forwarder now drops such a packet, and the
writer returns an error instead of indexing past the chain diffs.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* deps: bump mediatransportutil for the empty VP9 payload fix
A VP9 packet without a dependency descriptor and with a 1-byte payload such
as 0x08 parses to an empty VP9 payload, and IsVP9KeyFrame read its first
byte. mediatransportutil#106 returns false for an empty payload. This pins
the transport-v4 commit that carries it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* sfu: keep the template test comment with its test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* dynacast: create the target quality only for a valid regression
A target quality starts a timer that notifies the publisher. Look it up
only after the source codec is found, so a rejected regression creates
nothing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: restore the internal defaults for a room that lost them
A stored room without an internal record now gets the configured playout
delay and sync streams defaults. Its own settings, such as the empty
timeout and codecs, stay as stored.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* 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.
GetClientIP returned the whole X-Forwarded-For header, so a request that
passed through more than one proxy set ClientInfo.Address to a list like
"198.51.100.2, 10.0.0.5" instead of an IP. Each proxy appends to the
header, so the client is the first entry.
Refresh tokens were signed with the first configured key pair, which is
an arbitrary map entry when several keys are configured. Keep the join
token's API key on the participant and sign with it when its secret is
still configured, falling back to the first key pair otherwise.
The test mutates info2 (room "another-egress-test") to COMPLETE with an
EndedAt 24h in the past, then persists `info` instead of `info2`. So info2
stays STARTING forever, CleanEndedEgress never removes it, and the record
leaks into whatever Redis the suite ran against.
The leak is invisible because the final assertion only lists the primary
room. It surfaces on the NEXT run: utils_test.go:49 prefers a reachable
localhost:6379 over an ephemeral dockertest container, so against a
persistent Redis the list-all assertion grows by one record per run and
TestEgressStore starts failing with "should have 2 item(s), but has 3".
With info2 persisted, CleanEndedEgress removes both records and the test
cleans up after itself. Verified: 3 consecutive runs green, zero keys left.
With auto_create on, CreateDispatch creates the room through router.CreateRoom without checking limits.max_room_name_length, so it could create a room that CreateRoom and the join paths reject.
- pkg/service/redisstore.go: after the retry loop, return an error wrapping redis.TxFailedErr instead of nil. CreateIngress now fails instead of returning an ingress that was never written, StoreIngress stops before creating the orphan state key, and a dropped UpdateIngressState reaches the caller's existing error log.
- pkg/service/ingress.go: the Fix nil pointer dereference in IOInfoService.UpdateIngressState on concurrent DeleteIngress #4806 guard applied to the two Twirp handlers, treating a nil State as empty. UpdateIngress then applies and stores the request; DeleteIngress deletes without calling the ingress service.
- pkg/service/redisstore.go: UpdateIngress now fails with ErrIngressNotFound when the ingress no longer exists, checked inside the WATCH on the ingress hash so a later delete fails the EXEC. Without it an update racing a DeleteIngress recreated the deleted ingress and its stream key; this was possible before this PR whenever the delete landed after LoadIngress, and the guard in 2 widened the window to the gap between its two reads.
The guard stays at the call sites to match #4806 and keep API responses unchanged.
Servers that embed pkg/service and run their own join paths need the
same join limit check. Rename checkConnectLimits to CheckConnectLimits.
No behavior change.
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* service: enforce participant name length on join
StartSession checked the token's metadata and attributes against the configured limits but not its name, so a participant could join with a name longer than limits.max_participant_name_length, which UpdateParticipant and the signal UpdateMetadata path reject.
* service: consolidate join grant-limit checks on the validate path
Extract checkGrantLimits and run it from ValidateConnectRequest and
WHIPService.validateCreate so the /rtc/validate endpoint and the WHIP
ingest path reject over-limit name, metadata and attributes the same way
a real join does. StartSession keeps its own checks as the backstop.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
* service: run the full join limit check in StartSession
StartSession now calls checkConnectLimits, so the RTC node checks
identity, room name, participant name, metadata and attributes itself.
ValidateConnectRequest runs the check after the publish suffix, so it
measures the same identity StartSession sees. checkConnectLimits returns
a plain error, and the HTTP callers map it to 400. The name-only
StartSession test is dropped for TestConnectLimits, which gains a
publish-suffix case.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* service: test the StartSession limit check directly
TestStartSessionConnectLimits runs the same over-limit cases as
TestConnectLimits through StartSession on the RTC node. The cases move
into an exported ConnectLimitCases table so both test packages share it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: ANDROIDHASSAN <84630851+ANDROIDHASSAN@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
The WHIP create handler never called ValidateCreateRoom, so with room.auto_create: false a publisher token without roomCreate could create any room over WHIP, while the same join over /rtc gets 404.
Thread the issuing API key from the /rtc join path to the media node via
StartSession, and include it in the "starting RTC session" log and the
twirp API-request log, so participant activity can be correlated with the
key. Logs the key id only, never the secret.
Co-authored-by: Claude Opus 4.8 <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>
An unnamed deployment was addressed as "default" and that spelling leaked
into scope keys, so embedders keyed endpoints differently from job dispatch.
Map "_" back to "" at the URL boundary, as the agent name already does,
and drop NormalizeDeployment.
LoadIngress reads the ingress info and its state from two separate Redis
keys non-atomically, while DeleteIngress removes both keys in a single
transaction. If the delete lands between the two reads, LoadIngress
returns an IngressInfo with a nil State and no error, and
UpdateIngressState panics dereferencing info.State.Status — taking down
the whole server with every room it hosts.
The race fires in practice when an ingress session is being torn down by
DeleteIngress and the ingress service reports the session state change
concurrently: with short-lived per-room WHIP ingresses this crashed
production servers within minutes (observed on v1.13.5 and v1.13.6,
SIGSEGV at ioservice_ingress.go:82, addr=0x8).
Guard the nil State by treating it as an empty state, matching how the
store's UpdateIngressState already tolerates a missing state key.
* turn: refuse TCP relays and limit relays to this host to media ports
Embedded TURN let any participant relay to arbitrary peers (#4924):
- RFC 6062 TCP relays, accepted since pion/turn v5, let a client open TCP
connections to any permitted address, e.g. SSH on the node itself.
WebRTC clients never request them, so they are now refused for both
embedded and standalone TURN.
- Relays to the host's own addresses are delivered locally and bypass any
firewall in front of the host. Embedded TURN now only relays to this
host's RTC media UDP ports.
- Carrier-grade NAT, NAT64 and a few other special-purpose ranges are
added to the restricted peer ranges.
The issue also suggested allowing relays only to the media node's IPs.
That is not done here because, with the changes above, the remaining
relays do not form a security concern: they are UDP only, to public
addresses outside the restricted ranges, and reach a peer exactly as the
client could from its own address (no amplification, no spoofed source).
This is standard TURN behavior. Limiting destinations to media nodes would
also require TURN server to know media node all endpoints, for little benefit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* solve comment
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* bump protocol to get unlock on no key fix
* update warp pointer
* update protocol and psrpc deps
* update protocol dep
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* agent: HTTP endpoints data plane
Serve worker-declared FastAPI routes at /agents/{deployment}/{path} without
any worker-side listener: workers dial a fixed pool of wires speaking
AgentHttp.Frame, the server opens multiplexed streams carrying one opaque
HTTP/1.1 exchange each (two-level credit flow control, prioritized write
scheduler, attach epoch fencing). The front does starlette-exact manifest
matching with per-endpoint public access, typed 401/404/405, a retry table,
and SSE/WebSocket passthrough; a pluggable fallback hook lets multi-node
deployments resolve misses elsewhere. Includes a conformance client, a
manual sidecar, and the acceptance suite.
The auth middleware now reads access_token from the query string only:
FormValue consumed the bodies of proxied url-encoded POSTs.
* agent: attach adopter hook for wires landing on foreign nodes
Behind a load balancer a data wire may reach a node other than the one
holding the worker's registration; the adopter lets that layer (cloud)
install a local satellite registration before the attach is retried locally.
* agent: distinguish wrong-epoch attach so a multi-node adopter can refresh
A wire whose worker is registered but under a different epoch now returns
ErrWrongEpoch (not ErrAttachRejected); pool-full/closed stay ErrAttachRejected.
The attach adopter runs on unknown-worker OR wrong-epoch, so a satellite left
behind by a reconnected worker is refreshed by re-validating against the
registration holder instead of shadowing the new epoch until it is swept.
* agent/endpoint: Manifest.Version() digest for skew detection
Order-independent fnv64a of the route set so a multi-node layer can tell
whether the nodes serving a deployment agree on the manifest (safe to route
without inspecting the path) or are mid rolling-deploy (fall back to a
path-aware resolve).
* agent/endpoint: carry raw endpoints on the registration
A multi-node layer can now replicate a node's route set and match request
paths against it locally, instead of a manifest digest. Drops the digest
helper added for that (superseded).
* agent/endpoint: canonical route matcher (typed tokens + pruned walk)
Shape-matches a request path against a set of route templates via canonical
typed-wildcard tokens and a left-to-right pruned walk: linear in path depth
(no 2^segments), type-aware (int/float/uuid/str/path), glob catch-alls, and a
PrefixIndex interface so the same walk runs over an exact map (local) or a
compact replicated backing (multi-node). Worker stays authoritative for the
exact convertor/method match.
* agent/endpoint: fix glob matching and enforce route depth
- a path convertor anywhere in a template (non-terminal, or mixed with literal
text in a segment) now canonicalizes to a terminal glob that spans slashes,
instead of being dropped or narrowed to a single-segment str - the old
behavior silently failed to match such routes (a false negative -> misroute).
- enforce MaxRouteDepth at ParseManifest (wires up RouteDepth), bounding the
replicated filter's prefix count and the matcher's walk.
* agent endpoints: P2C worker balancing, routing-miss sentinel, api-key-scoped attach
- worker selection uses power-of-two-choices over live in-flight streams
(InflightStreams / SpareStreams) instead of weighted-random over a
reported load; the conn pick stays least-loaded. In-flight is observed
locally so it is correct for adopted wires, and the reported Load hook is
dropped from the endpoint path.
- the front tags its own routing misses (X-Livekit-Endpoint-Miss) so a relay
caller can distinguish them from a worker app's own 404/405 and retry past
them across the remaining candidates.
- a data-wire attach is bound to the connecting grant's api key, so a leaked
attach token cannot bind a conn to another project's worker.
- remove the dead scope-hook machinery (it only fed the removed bus resolve)
and rename the request identity from "scope" to apiKey.
* agent endpoints: drop the sidecar cmd, make the conformance client test infra
- remove cmd/agent-endpoint-client: the Python SDK has landed, so the manual
sidecar for non-SDK workers is no longer needed.
- move pkg/agent/endpoint/client to pkg/agent/endpoint/conformance (package
conformance) so it reads as the test harness it is, not a product client
SDK; only the acceptance suite drives it.
* agent endpoints: pool the per-request bridge buffers
- reuse the 32KiB response-copy buffer and the response-head reader from
sync.Pools; ~27% fewer bytes allocated per small request.
- reuse a per-conn marshal buffer in WriteFrame instead of allocating one per
frame; ~19% fewer bytes on a 1MiB upload. Safe because stream.Write copies
the payload and gorilla WriteMessage does not retain it.
* agent endpoints: reuse the read buffer and bound the data wire
- ReadFrame reads each frame into a reused per-conn buffer via NextReader
instead of letting ReadMessage allocate one per frame; ~41% fewer bytes on a
1MiB download. Safe: proto.Unmarshal copies the payload out and readLoop is
the sole reader.
- the data wire's websocket read is bounded by its own max message size (a full
frame + framing overhead), independent of the signalling message limit, so a
peer cannot OOM the server with an oversized frame even when signalling limits
are disabled. Drops the old coupling that clamped MaxFrameSize under the
signalling limit.
* agent endpoints: frame large uploads at MaxFrameSize and pool the buffers
Stream now implements io.ReaderFrom, so http.Request.Write's bufio.Writer
delegates the body to it and a large upload flows in MaxFrameSize frames instead
of ~4KiB ones - 16x fewer frames, marshals, scheduler cycles and websocket
messages. Large frame buffers (>= 16KiB) are drawn from a per-conn sync.Pool and
recycled by the scheduler after each write, so a big upload stops allocating a
buffer per frame; small/webhook bodies stay below the threshold and use a
right-sized make, so the average request is unaffected.
Measured on a 1MiB upload: -82% allocations, -66% latency, -17% bytes; a small
GET/POST is unchanged.
* agent endpoints: drop client WebSocket route support, repin protocol
* agent endpoints: repin protocol for the enum renumber
* agent endpoints: WebTransport data plane
Replace the capsule mux / credit / attach-pool machinery with one WebTransport
(QUIC) session per worker: a control stream carries registration and status,
and each HTTP exchange rides its own QUIC stream (native mux, per-stream flow
control, half-close, and reset). Encode the HTTP method into the cross-node
route filter so candidate selection is method-aware. Keep the legacy WebSocket
control transport for backward compatibility.
* agent endpoints: tidy front helpers and constants
Use endpoint.CurrentProtocol and a named SessionCloseOK instead of bare
literals, factor the repeated 503 and header-copy blocks into helpers, and drop
a few restating test comments and a redundant assertion. No behavior change.
* agent endpoints: assert deployment scoping in the registry test
* agent endpoints: drop file-narration header comments
* agent endpoints: normalize trailing slashes during routing instead of 307
A slash mismatch (e.g. /hook/ for a route registered as /hook) is now rewritten
to the registered form and served directly, rather than 307-redirected. Webhook
clients often don't follow redirects, and a redirect from the final routing hop
resends the body and pays the whole routing path twice. Exact form is matched
first, so a route registered with a trailing slash is served as-is.
* agent endpoints: route at deployment granularity, drop the route filter
Route presence like a reverse proxy keyed on (project, agent_name, deployment):
any of a deployment's workers is a candidate and the worker's own router returns
the real status (a 404 for a path it doesn't serve during a rolling deploy is
returned, not re-relayed). This removes the whole per-node route-advertisement
path: the cuckoo route filter and matcher (routematch.go), the miss-tagging /
retry-past-miss machinery, and the route-depth cap that only existed to bound
the filter. Text routing is now the same shape as voice job dispatch.
* agent endpoints: audit cleanups (drop dead Registration.Endpoints, test the fallback flow)
Remove the write-only Registration.Endpoints field (matching goes through
Manifest; the multi-node layer no longer replicates the raw route set). Add
Front-level fallback tests (fires with the resolved identity, declined -> 404
with a local worker or 503 without), and fix two stale comments.
* agent endpoints: byte-transparent HTTP/1.1 exchange
Replace the protobuf frame layer on exchange streams with a length-prefixed
StreamPreamble followed by opaque HTTP/1.1 bytes. QUIC already provides the
multiplexing and per-stream flow control, so the frame layer only re-encoded a
message both peers can already parse, and every SDK had to re-materialize HTTP
from it.
The front serializes a canonical request head from its own parsed
*http.Request and never forwards the client's bytes, which is what keeps
request smuggling out of the worker. Responses are read with
http.ReadResponse, so informational heads need no httptrace hook and the
conformance worker loses its HTTP reconstruction entirely.
Completion splits by outcome: a body ends by its own framing, a failure after
bytes have flowed travels in x-lk-completion / x-lk-error trailers, and a
failure before any byte resets the stream with an HttpStreamResetCode. REFUSED
stays distinct as the retry-safety signal, and the retry/idempotence rules are
unchanged.
The x-lk- prefix is reserved for this signalling: it is stripped from
client-supplied request headers so a caller cannot forge an outcome, and from
responses so it never reaches the end client. Exchange-stream targets are
split from the escaped path so a percent-encoded '?' or '/' cannot change
which resource the worker routes to.
Per-request state moves to attempt.go so the Front and attempt lifecycles stop
interleaving; the remaining files are grouped type-first with free helpers
last. Those moves are ordering only.
* go.mod: pin protocol with the agent endpoints preamble
Picks up livekit/protocol 134fb913, which replaces the HTTP framing messages
with StreamPreamble and renumbers HttpStreamResetCode. The previous pin
predates AgentHttp entirely, so the endpoint packages only built through the
local go.work.
* agent endpoints: require a scoped grant for non-public routes
The front gated non-public routes on a bool that was true for any valid token
in the project, so a roomJoin token minted for an end user reached every
non-public endpoint the project's agents expose.
Replace the resolver's (apiKey, authenticated) pair with an Access value and
give it the agent and deployment from the URL, so the scope rules stay with
the grant in protocol/auth and this package consumes only the verdict.
Credentialed now separates a caller with no credential from one whose
credential lacks the grant: the first is challenged with 401, the second gets
403 and no WWW-Authenticate, since a retry cannot succeed.
A denied request still reaches the fallback. Another node's worker may declare
the same path public, and that node is the authority.
* go.mod: pin protocol with the agent endpoint grant
* agent endpoints: accept any agent name, keep request escaping intact
The name is percent-encoded into its URL path segment, so it needs no charset.
Only "_", "." and ".." are refused, and only for workers declaring endpoints:
all three are unreserved, so no encoded form addresses them distinctly. "_"
now addresses a worker registered with an empty agent name, which the
implicit-dispatch default leaves unset.
Two escaping fixes the escaped-path split depends on:
- the trailing-slash alternate treated a decoded slash as literal, so
/known%2F normalized onto route /known and the worker was handed a path it
does not serve.
- RemoveDoubleSlashes trimmed URL.Path and left RawPath, which makes
EscapedPath() re-encode from Path and lose every escape in the request.
Request logs now carry the encoded path, since a decoded %0A forges a log line.
* agent endpoints: return the abort from bridge rather than panicking inside it
A committed response that cannot be completed is torn down with
panic(http.ErrAbortHandler): the head is on the wire, so no status can report
the failure, and this is the only teardown net/http offers. HTTP/1.1 closes
without the final chunk and HTTP/2 sends RST_STREAM, so a short body cannot
read as whole.
bridge raised it from inside the response copy loop, through a helper whose
doc had to note that it does not return. It now reports a bridgeOutcome and
ServeHTTP performs the teardown at the handler boundary, where the constraint
that nothing may recover the sentinel is visible to a reader. The outcome
replaces the (done, retryable) pair, whose four combinations only ever carried
three states.
No behavior change.
* agent endpoints: serve the front on its own middleware chain
The front was mounted on the API mux and served through the API middleware
chain, which is shaped for handlers that buffer a request and write one
response. Four consequences.
negroni.NewRecovery() recovers every panic with no http.ErrAbortHandler
exemption, and NewRecovery sets PrintStack. On an abort it wrote "PANIC: ..."
and a goroutine stack into the already-committed body, then returned normally,
so net/http terminated the chunked stream cleanly. A truncated response
reached the client as complete, with a stack trace appended. Detection was
already correct; delivery was not, and the x-lk- trailers that would otherwise
signal it are stripped before the response leaves. A Content-Length response
still failed safe, since net/http enforces the declared length itself, so the
gap was the chunked and trailer paths.
Endpoints.Disabled documents that it turns the front off, but only
registrations were refused; the mount was unconditional.
The CORS method list omits PUT, which a manifest may declare.
The API body limiter capped request bodies at MaxAPIRequestBodySize, though
the front streams a body through a pooled buffer and never holds one.
NewHTTPHandler now routes the prefix to a chain carrying AgentRecovery, a CORS
list matching the methods a manifest may declare, and the api-key auth
middleware the front resolves a caller's access from. The mount is built only
when endpoints are enabled, so the prefix otherwise falls through and 404s.
RemoveDoubleSlashes moves above the split, so routing and both chains see one
path form.
Taking the front off the mux also stops ServeMux rewriting the paths it is
handed: "//x", "/../" and interior "//" were answered with a redirect rather
than proxied, which a byte-transparent exchange cannot do.
The endpoint stack tests now build the production handler, so they run on the
chain the node serves on.
* agent endpoints: build the front and registration from params
Front is an http.Handler, so fallback, identity and singleKeyFallback were read
on every request with no synchronization while WithFallback, WithIdentity and
WithSingleKeyFallback wrote them on the live object. Each returned the same
pointer, so the chain read as though it built a value. Every call site happens
to run before the handler is mounted, so nothing races today, but nothing in
the type prevents it, and WithSingleKeyFallback took no argument and could only
be turned on. NewFront now takes FrontParams and configuration is fixed at
construction.
NewWorkerRegisterer takes its EndpointSettingsFunc directly, and
HandshakeAgentWorker takes one in place of a variadic of raw closures that
existed only to reach the setter it replaced.
Registration gains NewRegistration and RegistrationParams, moving the Draining
callback off an exported mutable field and folding SetSession into
construction. IsDraining absorbs the nil check at both call sites.
Access carried a three-state ladder as two bools, with "granted implies
credentialed" documented but unenforced. It is now an ordered AccessLevel, so
callers compare a rank rather than combining flags and the invariant holds by
construction.
Registry.Register returned an error that was always nil, with a dead branch at
each call site. Both registry maps and the per-registration session are
read-heavy, so they take RWMutex.
CopyBody returned two errors to separate a source failure from a destination
one. It returns one, wrapping a source failure in *SourceError, which is what
the caller discriminates on.
NewWebTransportServer took a callback to break the handler/server init cycle;
the caller assigns wt.H3.Handler after construction instead. StartWebTransport
reads Development off the service rather than taking a bool, and returns a nil
stop function where it starts no listener.
Smaller: slices.Sort for sort.Strings, for range for an unused counter, a nil
slice for regs[:0:0], p2c generic over its slice so the call site passes a
method expression rather than allocating a closure per request, and streamCode
deduplicated into wire.StreamCode so both peers map reset codes in one place.
Comments on the touched declarations drop remote behavior, migration narration
and contrastive framing, keeping the constraints and invariants.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: serve webtransport from the node's server set
StartWebTransport built the node's only HTTP/3 listener from inside AgentService:
it minted the TLS config, bound the UDP socket, assembled an h3 mux and returned
a stop closure LivekitServer held in agentWTStop. Every other listener is
constructed in NewLivekitServer and delegates to a service, and agents are the
first consumer of HTTP/3 rather than the last.
webtransport.go now carries the transport with no agent references:
WebTransportTLS, NewWebTransportServer, NewWebTransportHandler,
ListenWebTransport, and WithWebTransportServer/GetWebTransportServer, which put
the serving server in the request context so a route that upgrades is a
conventional http.Handler instead of a closure over the server. The listener is
built in NewLivekitServer beside the prometheus and debug servers, bound in Start
with the other listeners, and stopped once doneChan unblocks, so no stop closure
is held on LivekitServer. /agent is a route on its mux, as it is on the API mux.
UpgradeWebTransport unwraps the ResponseWriter before upgrading. webtransport-go
type-asserts it to http3.Settingser and http3.HTTPStreamer without checking and
negroni wraps the writer on every chain, so the h3 listener could not carry a
middleware chain at all. It now runs the same recovery, api-key auth and path
normalization as the TCP chain.
AgentService splits into AgentWSService and AgentWTService over the shared
AgentHandler, and the endpoint front becomes AgentEndpointService. wire builds
all four and threads one endpoint.Registry into the handler and the front.
NewAgentHandler takes the config and builds its own ServerInfo, so endpointsConfig
and singleAPIKey are set at construction and the psrpc server is registered
against a fully formed handler; it previously bound one whose embedded
*AgentHandler was still nil.
The listener's port and certificate move to a top-level webtransport config
block. The listener no longer reads agents.endpoints.disabled, which continues to
refuse endpoint registrations. ListenWebTransport binds one socket per bind
address, where the h3 listener ignored bind_addresses that every TCP listener
honoured.
NewWorkerRegisterer takes a variadic WorkerRegisterHandler, each handler reading
the request and filling its part of the response and the registration, replacing
the single EndpointSettingsFunc threaded through HandleRegister.
EndpointRegisterHandler is the endpoint declaration's turn, and
endpoint.NegotiateSettings holds the protocol negotiation the OSS and cloud
handshakes each carried a copy of.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: accept webtransport connections rather than racing Serve with Close
ListenWebTransport ran wt.Serve on a goroutine per socket and returned a stop
func calling wt.Close. Serve takes a reference on the server's refCount
WaitGroup and Close waits on it, so the pair breaks the WaitGroup's own rule
that an Add starting from zero must happen before a Wait. The race detector
models that rule as a read of wg.sema in Add against a write in Wait, and
reports it whenever Wait observes a non-zero counter: a listener stopped
before its serve goroutine has run at all, which is every test that builds a
stack and tears it down without a worker connecting. sync is compiled without
instrumentation, so the report names the two ListenWebTransport call sites
with no frame in between. webtransport-go v0.13.0 carries the same code.
The accept loop moves here. quic.ListenEarly builds the listener Serve would
have built, with the datagram and partial-delivery options the session layer
requires, and each connection goes to Server.ServeQUICConn, which touches no
part of that WaitGroup. The stop func keeps the order Close established:
Close first, so every CONNECTION_CLOSE frame is transmitted while the sockets
are still open, then the accept loops are cancelled and drained, then the
listeners and sockets close.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: sequence the endpoint tests on the registry
handleConnection writes the register response from inside HandshakeAgentWorker
and installs the worker's routes after it returns, so a worker learns it is
registered a moment before the node can route to it. The conformance worker's
WaitRegistered unblocks on that response and startWorker returned straight
into the first request, which on a loaded runner arrived while the registry
was still empty and came back 503. TestAgentEndpointsStatusMapping saw that as
503 for the first few mapped statuses, TestAgentEndpointsHOL as an unexpected
EOF, reading 1024 bytes out of a short error body.
The stack keeps the registry it builds and startNamedWorker waits for the
worker's registration to appear in it, which is the condition the requests
actually depend on. TestAgentEndpointsRetrySafety builds its unreachable
worker by hand and waits the same way. The HOL test asserts its status before
reading the body, so a 503 there reports as a status mismatch rather than a
truncated read.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: log the deployment with worker registration
Workers are keyed by deployment alongside agent name, namespace and job type.
The registered and last-deregistered lines named every part of that key except
the deployment.
* agent endpoints: add a path router that matches in declaration order
Manifest matching runs a compiled regex per route over a linear scan, once per
candidate registration, on the serving path. At the 256-route cap that is up to
256 RE2 executions per replica per request.
The router compiles a manifest into a compressed trie instead. Starlette
selects the first route declared that matches, so the trie cannot resolve
static before wildcard the way net/http's does: every node carries the lowest
route index in its subtree, the walk tracks the lowest full match found and
prunes any subtree that cannot improve on it, and inserting in declaration
order leaves edges and leaves sorted by that index with no sort pass.
Params are not segment-aligned - starlette allows /f/{name}.{ext}, a {p:path}
anywhere, and a float whose fraction backtracks - so the walk must search. An
edge is single when nothing below it can start with a byte its own convertor
could have consumed, which is a property of the target node and so is settled
at build time; a single edge takes its greedy run and descends once. Templates
whose params are segment-aligned are entirely single and never search. What
remains is bounded by a step budget, and exhausting it returns ResultOverBudget
rather than a route the cut-short search cannot vouch for.
Templates parse without regexp. Scanning the grammar by hand keeps a brace that
opens nothing well-formed as an ordinary literal, which is what starlette's
finditer does. Anchoring is `\n?$` rather than `$`: python's '$' matches before
one trailing newline where Go's does not, and [^/] accepts a newline where .
refuses one, so the two convertors diverge in opposite directions on a decoded
%0A.
The regex implementation moves into the tests as an oracle, carrying its own
parser so it references the hand-rolled scanner as well as the trie.
FuzzMatchAgainstOracle generates a table and a request and asserts the two
agree on both the winning template and the result. Matching allocates nothing,
asserted by AllocsPerRun on hit, 405, miss and on the searching path.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: route manifests through the path router
ParseManifest builds a router.Router rather than a slice of compiled templates,
Manifest aliases it, and Route keeps the template and the public flag the front
reads. Declared methods become a mask at build time, so a method no route could
declare masks to 0 and matches nothing, as an undeclared one already did.
Three behavior changes ride along.
Templates anchor as `\n?$`. A manifest declaring private /files/{p:path} before
public /files/{p} routed GET /files/x%0A to the public route here and to the
private one on the worker, because the path convertor refuses a newline where
str accepts it. The access gate reads the public flag of the route the front
picked, so it opened on a route starlette would not have selected.
slashAlternatePaths derives the escaped form from the transform it applied
rather than from the result's suffix. A request path of // trimmed to /, the
caller saw a trailing slash on that result, took the append branch, and handed
the worker a request line of /// against a decoded path of /.
The decoded path is capped at MaxPathLength, answering 414 above it. Matching
runs before anything sizes the request head, so net/http's own limit was the
only bound on what the matcher was handed.
A table too ambiguous to decide now dispatches rather than 404s: the worker's
own router still knows, and the preamble carries no route for it to be told
about. Nothing here knows whether that route is public, so the request needs a
grant. Dispatch keys on the match set, since a candidate can now join it
without resolving a route.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: log the manifest as a structured object
Router implements zapcore.ObjectMarshaler, so registration logs the table's
size and the templates whose shape forces the matcher to search under one key
rather than assembling fields at the call site. Which templates those are is
settled when the manifest is parsed, so it is worth reporting before any
request is served; what a single match cost belongs to that request instead.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: key templates by shape and export their ambiguity
Canonical renders a template as its literals and convertor kinds, so two
templates the trie cannot tell apart share a key. Param names reach the trie
only as a kind, so /x/{a} and /x/{b} accept the same paths; anything keying
routes by the declared spelling splits them apart. Literals are length-prefixed
because a brace that opens no well-formed param is literal text: /x/{:str}
matches itself and must not collide with /x/{a}.
ambiguousTemplate becomes Template.Ambiguous. It reads only the template's own
elements, so it answers for a manifest that was validated but never compiled
into a table of its own.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: merge worker manifests into one table per deployment
A deployment owns its route table. A route is one template shape and one method
together with the workers that declared it; registration takes the union of the
table and the arriving worker's manifest, deregistration retracts the worker and
drops the routes nothing is left declaring. Manifest stops being a compiled
router and becomes the ordered list a worker declared, so a fleet holds one
table rather than one per replica, and a request resolves in a single walk.
A mixed fleet is the point. Matching each worker's own table in turn already
served heterogeneous methods, but the route the front reported was the first
candidate's while the worker it dispatched to was any of them, and partial and
denied were accumulated across workers whose manifests disagreed. Both become
properties of one table, so the status a request gets and the template the
worker is told are decided together.
Merge order is the lowest position a route holds in any declaring manifest, tied
by shape then method. A fleet declaring one manifest reproduces that manifest's
order, and the result reads off the current set of manifests, so nodes holding
the same fleet agree. This does not preserve any one worker's internal order: a
worker can be handed a request the merged table resolved to a public route while
its own table routes that path to a private one. Merging the declaration chains
in order would hold the property and is not done here;
TestRouteTableMergeOrderInversion carries the case.
Routes are keyed by shape, so /x/{a} and /x/{b} are one route and a renamed path
param does not halve the fleet serving it. Each worker keeps the spelling it
declared, and the preamble carries that, since it is re-serialized per attempt.
The tree holds routes by pointer and is rebuilt only when the route set or its
order moves, so a worker joining or leaving an existing route swaps nothing. A
supersede runs the removal and the addition as one transaction: an unchanged
manifest would otherwise empty every route, drop it, and build a new one under
the same key, leaving the published tree naming routes nothing can reach and no
change to the key set to show for it. A reconnect can also land on a different
agent name or deployment, so the retiring epoch is retracted from its own table.
Ambiguity is now a property of the merged tree, and one worker's template shape
can carry the whole deployment's matcher over its step budget, which leaves no
route decided and so no public flag to clear an ungranted request.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* agent endpoints: scope the registry, let the embedder own tenancy
The registry was doing three jobs at once: fencing worker epochs by id,
listing a deployment's candidates, and holding its merged route table. The
last two are per-deployment state, so it keyed them on
(api key, agent name, deployment) and grew a tenancy concept that only an
embedder can actually define. Cloud has to lie to it, passing a project id
in a field named APIKey.
Split them. Scope is one deployment's serving state and stores no identity
at all; whoever embeds the package keys a map of scopes however its own
tenancy works, and hands the front a resolved one. Registry keeps only the
worker-id fence, which is genuinely node-wide: worker ids are server-issued,
so an epoch is superseded wherever it was scoped.
The front loses its registry, its SingleKeyFallback and FallbackRequest: the
resolver now returns the scope and a fallback already curried on the
deployment, plus an ok that carries the 401-vs-503 split the empty api key
used to encode. routeTable drops its key and takes the scope's logger, so
identity is curried in rather than stored.
pkg/service takes ownership of the "api key is the tenant" rule, which is
true there and nowhere else, and of releasing a scope once nothing holds it.
Behavior is unchanged, including serving public routes to an unauthenticated
caller when one configured key or one attached tenant makes the key
unambiguous.
* agent endpoints: give the http3 listener a server type
ListenWebTransport returned a stop closure, so every caller had to park it
next to the server it belonged to. In cloud that meant a second field on the
node base, written at start and read at stop, for one listener.
WebTransportServer embeds webtransport.Server and owns the sockets and
accept loops, so Listen and Shutdown are methods and the shape matches
http.Server. Shutdown takes a context: it stops accepting, sends GOAWAY, and
closes whatever has not drained by the deadline, where the closure closed
everything at once with no deadline of its own. It is safe on a server that
never listened, which is what lets a holder key teardown off the field alone.
The embedded Close still releases sessions without releasing the sockets;
that is what the type comment warns about.
* agent endpoints: fold the ident-start test into a helper
staticcheck QF1001 flagged the negated disjunction in scanIdent, which was
failing the lint gate and so keeping the test job from running at all. The
positive helper reads better than the De Morgan form and lets the continue
condition drop its own '_' case.
* go.mod: bump protocol to the merged branch head
* rtc tests: give the logger its own logging config
init() handed the logger &config.DefaultConfig.Logging, so the leveler's
mutex lived inside the global that NewConfig yaml-marshals. Marshalling
reflectively copies the whole struct, mutex included, which raced the
component-level lookups pion makes from its own goroutines and failed
TestPreferMediaCodecForPublisher under -race.
The values are the same; only the storage is now test-local. The integration
helper aliased the same global and gets the same treatment.
* rtc tests: drop the logging config comment
* auth: name the call the query-string read avoids
The token comes from RawQuery so the body reaches a proxied agent endpoint
intact. That only holds as long as nobody reaches for FormValue, which is
the obvious way to read a param and the one that drains the body, so the
comment names it.
* agent endpoints: tunnel WebSocket upgrades to workers
An exchange stream already carries opaque HTTP/1.1, so a WebSocket is an
ordinary GET route: the front forwards an HTTP/1.1 Upgrade: websocket
handshake, the worker's HTTP stack decides, and on a 101 the front hijacks
the client connection and splices it onto the stream. No protocol change.
- Only HTTP/1.x GET with Connection: upgrade and Upgrade: websocket (and no
body) is an upgrade; every other Upgrade token is still stripped. A 101 is
accepted only for such a request and only with Upgrade: websocket;
anything else stays a protocol error.
- A non-101 answer to an upgrade is an ordinary response; the stream then
ends with a FIN rather than a reset.
- Retries are unchanged until the 101; after it the attempt is committed.
- Each worker takes at most MaxTunnelsPerWorker tunnels (default half its
session's MaxStreams) so WebSockets cannot starve its HTTP routes; an
upgrade no worker can take falls to the fallback, then 503.
- Drain: a tunnel outlives its worker starting to drain by
TunnelDrainTimeout (default 30s), and Front.Drain closes tunnels once its
context is done. Both close with a 1001 frame when the client-bound side
is between frames, abruptly otherwise. The server drains tunnels while
participants leave, since http.Server.Shutdown cannot see them.
- access_token is dropped from the target and a LiveKit bearer token from
Authorization for every request: the worker gets identity from the
preamble, and the token must not reach application code.
- Full duplex: enable it before the first flush, so an HTTP/1 client can
keep streaming its body while the response streams back.
Config: agents.endpoints.max_tunnels, agents.endpoints.tunnel_drain_timeout.
* agent endpoints: keep one value per CORS header
The agent chain's CORS middleware writes Access-Control-* and Vary before
the front runs. A worker's head was added on top, duplicating
Access-Control-Allow-Origin, and the clear after a 1xx head dropped the
middleware's headers from the final response.
- A worker's Access-Control-* and Vary values replace the middleware's;
other headers are still added (MergeWorkerHeaders).
- Headers set before the front ran are restored after each 1xx head.
- Preflights stay with the middleware; a plain OPTIONS still reaches a
declared route. NewAgentEndpointCORS holds the agent chain's CORS
middleware so other chains can share it.
* agent endpoints: withhold endpoint settings from sessionless workers
A worker registering over WebSocket has no data plane, yet the handshake
negotiated endpoint settings, telling it its routes were live while every
request 503'd. Negotiate only when a WebTransport session exists, per the
endpoint_settings contract, and keep the worker registered for jobs.
* deps: pin protocol to the agent endpoints branch head
* deps: pin merged protocol
---------
Co-authored-by: Paul Wells <paulwe@gmail.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>