Skip to content

fix(agent): honour UDPRoute drains and bind the heaviest backend (#873) - #914

Merged
bpalermo merged 5 commits into
mainfrom
fix/873-udproute-weights
Sep 23, 2026
Merged

bpalermo merged 5 commits into
mainfrom
fix/873-udproute-weights

Conversation

@bpalermo

@bpalermo bpalermo commented Sep 23, 2026 •

Copy link
Copy Markdown
Owner

Closes #873.

What udp_proxy can and cannot express — checked, not assumed

#873's fix direction says "udp_proxy supports matcher-based route selection (and weighted clusters via the matcher API) in current versions". Both halves of that are wrong, verified against the pinned Envoy (go-control-plane/envoy v1.39.0, upstream tag v1.39.0):

Weights. UdpProxyConfig.route_specifier is a oneof of cluster (deprecated) and matcher. The matcher's terminal action is envoy.extensions.filters.udp.udp_proxy.v3.Route, which has exactly one field:

message Route {
  string cluster = 1 [(validate.rules).string = {min_len: 1}];
}

The action registry is keyed on udp_proxy's own private RouteActionContext (source/extensions/filters/udp/udp_proxy/router/router_impl.cc:30) and holds that one action. The HTTP router's weighted route_list action lives in a disjoint registry and is unreachable from here. tcp_proxy's weighted_clusters has no udp_proxy counterpart, in this version or any other.

Per-service selection. This is blocked one layer lower, for a reason #873 does not mention:

  • the CNI captures UDP with an nftables redirect, which rewrites the destination before delivery;
  • a datagram listener's only addressing cmsg is IP_PKTINFO (listener_impl.cc:776-780), so a matcher's DestinationIPInput reads the post-DNAT header — the ClusterIP is gone. Envoy never reads IP_RECVORIGDSTADDR/IP_ORIGDSTADDR anywhere in the tree, and original_dst is structurally TCP-only (OriginalDstFilter implements Network::ListenerFilter, not UdpListenerFilter; LDS hard-rejects it on a UDP listener);
  • DestinationPortInput is not packet-derived at all — the port is stamped from the listening socket's own port (io_socket_handle_impl.cc:258-281), so it is the constant ProxyCapturePort no matter what was dialled.

A udp_proxy matcher therefore has nothing to discriminate on. Per-service UDP routing needs TPROXY capture, or a listener per service on its own port — a CNI change, not a control-plane one. Switching to the matcher specifier today would buy nothing and cost a field still marked work_in_progress in 1.39.

What this PR fixes

Two of the three things the UDP path discarded were bugs, not limits:

  1. weight: 0 is now honoured as a drain. An explicit 0 is a Gateway API DRAIN, shipped for TCP and TLS in fix(l4route): honor weight:0 as drain, don't normalize to 1 #492 and passed through unchanged by common/l4project precisely so the Envoy builders can omit it. The UDP path took backends[0] regardless of weight, so a drained backend listed first took all of the service's datagrams — the inverse of what the route asks for. A service whose every backend is drained now contributes nothing instead of capturing the pod's only UDP listener.

  2. The bound backend no longer depends on backendRef order. backends[0] meant a 10/90 split written canary-first sent 100% to the 10% canary. The heaviest backend now wins, ties broken by cluster name (fix(agent): make cluster/CLA protos deterministic to stop spurious CDS churn #135 — a selection that varies between rebuilds of identical input re-hashes the listener on every push).

  3. The split itself stays unrepresentable, and is reported rather than faked — see above. UnsupportedUDPRouteShapes (fix(agent): say out loud what the UDP capture listener discards (#873) #874) still names it, and still feeds aether.agent.l4route.udp_unsupported.

The detector and the generator no longer duplicate the selection: both call selectUDPRoute. #874 shipped the duplicate deliberately, pinned by a test, because a drifted detector confidently names the wrong cluster and is worse than no warning; sharing the decision makes that drift unrepresentable rather than merely tested for. TestUnsupportedUDPRouteShapesTracksTheGenerator stays as the end-to-end pin.

A dangling-cluster hole found on the way (not in #873)

Same class as proposal 037 Risk 1 and #877. captureUDPClusters skips a backend service the cluster cache does not hold (or whose registered port is unreadable), but the generator would name its cluster anyway. udp_proxy has no on-demand cluster path, so those datagrams are accepted and dropped with no NACK, no log and no stat — indistinguishable from a backend that is down. Heaviest-wins made it more likely to bite, since the unroutable backend can be the heavy one.

  • udpClusterForLocked is now the single skip predicate, consulted by both captureUDPClusters and the listener path, so CDS and the listener cannot disagree.
  • An unroutable backend is blanked rather than removed, so a service left with nothing still reports itself instead of going quiet, and the listener falls through to a backend that does resolve.
  • reconcileUDPCaptureListeners runs on every snapshot push and rebuilds when the bindable cluster moves. Without it a UDPRoute landing before its backend registers would produce no listener and stay dark until the next UDPRoute event — SetUDPServiceRoutes is the only other trigger. This is the same discipline reconcileCaptureTCPChains follows for the TCP floor's identity gate, and for the same stated reason. Steady state is a map walk and a string compare; nothing is rebuilt, and nothing is re-warned, unless the bound cluster actually changed.

The #895 chain→CDS resolver gate does not cover this path, and could not: TestCaptureChainsResolveAgainstCDS walks filter chains looking for tcp_proxy, and a connection-less UDP listener has no filter chains at all — udp_proxy is a listener filter. TestUDPCaptureListenerResolvesAgainstCDS is the UDP arm of the same check.

Seen red

1. The behaviour bugs (//agent/internal/xds/proxy:proxy_test)

Five new assertions against the unmodified generator — real test failures, not compile errors:

--- FAIL: TestUDPCaptureListenerHonoursWeightZeroDrain (0.01s)
        Error:      Not equal:
                    expected: "udp:live.mesh"
                    actual  : "udp:drained.mesh"
        Messages:   weight 0 is an explicit DRAIN (#492): the drained backend must
                    never be the one the listener binds
--- FAIL: TestUDPCaptureListenerFullyDrainedServiceIsNotChosen (0.00s)
        Error:      Not equal:
                    expected: "udp:b1.mesh"
                    actual  : "udp:a1.mesh"
        Messages:   a service whose every backend is drained has nothing to route
                    to and must be skipped
--- FAIL: TestUDPCaptureListenerAllDrainedProducesNoListener (0.00s)
        Error:      Expected nil, but got: &listenerv3.Listener{... Name:"capture_udp_pod-all-drained" ...}
        Messages:   every backend drained means no UDP route at all
--- FAIL: TestUDPCaptureListenerBindsTheHeaviestBackend (0.00s)
        Error:      Not equal:
                    expected: "udp:stable.mesh"
                    actual  : "udp:canary.mesh"
        Messages:   a 10/90 split cannot be honoured, but binding the 10% backend
                    because it was listed first is not the closest answer
--- FAIL: TestUDPCaptureListenerHeaviestBackendIsOrderIndependent (0.00s)
        Error:      Not equal:
                    expected: "udp:stable.mesh"
                    actual  : "udp:canary.mesh"
        Messages:   the bound backend must not depend on backendRef order
        Error:      Not equal:
                    expected: "udp:z.mesh"
                    actual  : "udp:a.mesh"
        Messages:   an equal-weight tie must break deterministically
FAIL

2. The dangling cluster (//agent/internal/xds/cache:cache_test)

Run before routableUDPRoutes existed, with a UDPRoute whose heavier backend is a service the registry does not hold. The ghost is also the FIRST backend, so this is red against the original backends[0] generator and against the heaviest-wins one alike — only checking against the clusters actually built fixes it:

--- FAIL: TestUDPCaptureListenerResolvesAgainstCDS (0.01s)
        Error Trace: agent/internal/xds/cache/udproute_cds_test.go:113
        Error:       map[string]struct {}{"app_client-0_8080":…, "udp:udp-a.aether-test.aether.internal":…}
                     does not contain "udp:ghost.aether-test.aether.internal"
        Messages:    UDP capture listener "capture_udp_client-0" routes to cluster
                     "udp:ghost.aether-test.aether.internal", which is not in the
                     snapshot — udp_proxy has no ODCDS cold path, so those datagrams
                     are accepted and dropped in silence

Both tests assert against the CDS set and the generated listener, so neither can pass by the package failing to build.

Green

--- PASS: TestUnsupportedUDPRouteShapes (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/no_routes_is_silent (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/single_service_single_weighted_backend_is_representable (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/multiple_backends_discard_the_weights (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/second_service_is_dropped_entirely (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/weight_0_drain_leaves_the_service_with_nothing_to_route_to (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/empty_backend_lists_are_skipped,_not_chosen (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/every_shape_at_once (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/weights_are_still_discarded_among_the_backends_that_survive_the_drain (0.00s)
    --- PASS: TestUnsupportedUDPRouteShapes/a_service_with_no_resolvable_backend_reports (0.00s)
--- PASS: TestUnsupportedUDPRouteShapesTracksTheGenerator (0.00s)
--- PASS: TestUDPCaptureListenerHonoursWeightZeroDrain (0.00s)
--- PASS: TestUDPCaptureListenerFullyDrainedServiceIsNotChosen (0.00s)
--- PASS: TestUDPCaptureListenerAllDrainedProducesNoListener (0.00s)
--- PASS: TestUDPCaptureListenerBindsTheHeaviestBackend (0.00s)
--- PASS: TestUDPCaptureListenerHeaviestBackendIsOrderIndependent (0.00s)
--- PASS: TestUDPCaptureListenerResolvesAgainstCDS (0.01s)
PASS

Whole tree: make test — 109 tests pass.
Race, scoped: bazel test --config=race //agent/internal/l4route:all //agent/internal/xds/cache:all //agent/internal/xds/proxy:all — 3/3 pass.
Lint: bazel build --config=lint --@aspect_rules_lint//lint:fail_on_violation //agent/internal/xds/... //agent/internal/l4route/... //common/l4project/... — clean.
//test/envoy_validate:envoy_validate_test (real envoy --mode validate on the UDP capture listener) — passes.

Existing tests: two expectations updated, none removed

TestUnsupportedUDPRouteShapes keeps all seven of its cases and gains three. Two cases pinned behaviour this PR fixes, so their expectations moved:

  • "weight 0 drain is not honoured for UDP" → renamed "weight 0 drain leaves the service with nothing to route to". Still 1 reason, still containing weight 0 (drain), but it now describes a drain that is honoured and leaves the service with no data path, rather than one that is ignored.
  • "every shape at once" → 3 reasons became 1. Two of the three were the bugs: the drain is honoured, which leaves that service with exactly one routable backend, so nothing about it is discarded any more. The one real limit — a second UDPRoute-backed service on the same pod — still reports.

Not touched

agent/internal/xds/cache/cachemetrics/cachemetrics.go. #882 — the udp_unsupported counter was registered but never seeded at zero, so it had no Prometheus series — was fixed in parallel and landed as #905 while this branch was open. That is a dependency of this PR's observability, not a conflict: the reasons added here, including the new unroutable-backend one, feed that same counter, and without #905 they would be visible only in the WARN log. This branch is based on 5b0c199 and touches none of those files; the merge base diff is the 12 files above.

Deliberately not done, and why

Two things could produce a real split. Both are follow-ups to #873, not drive-bys, and I'd rather they be designed than smuggled in here:

  • Weighted endpoints in one merged cluster. NewUDPServiceCluster is STATIC with an inline load assignment, so merging several backends' endpoints with scaled load_balancing_weight is mechanically easy, and use_per_packet_load_balancing would even re-select per datagram. But it collapses the per-backend udp:<svc> clusters that the node dependency set, the UDPLoadAssignment port rewrite, outlier detection and every cluster.udp:* stat are keyed on — a 90/10 split would become unobservable per backend. Exact ratios also require scaling weights by endpoint counts, which re-churns the cluster on every backend scale event.
  • A sticky runtime_fraction bucket. envoy.matching.matchers.runtime_fraction works as a custom_match predicate with a static default_value (no runtime key needed), giving an N/D split. But it needs the matcher specifier — still work_in_progress in 1.39 — it is an xxHash of an input, so it splits per source socket rather than per datagram, and >2 backends needs cascaded conditional probabilities.

Docs

docs/conformance/gateway-api-features.md and docs/getting-started.md both said UDPRoute was "Supported" with no mention of either limit. #873's complaint was that "the only way to discover this is to read the generator", so both now state the no-split and one-service-per-pod limits, that weight: 0 is honoured, and where the counter is.

No charts/ change, so no Chart.yaml bump.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

udp_proxy carries ONE cluster, and the per-pod UDP capture listener was
choosing it with `backends[0]` of the lexicographically first service. Two
of the three things that discarded were bugs, not limits:

  - an explicit weight 0 is a Gateway API DRAIN (#492, shipped for TCP and
    TLS) and the UDP path forwarded to the drained backend anyway;
  - which backend won depended on backendRef ORDER, so a 10/90 split written
    canary-first sent 100% to the canary.

Both are fixed: drained backends are never bound, a service whose every
backend is drained contributes nothing rather than capturing the listener,
and among what is left the heaviest backend wins with ties broken by cluster
name (#135 — a selection that varies between rebuilds of identical input
re-hashes the listener on every push).

A genuine traffic SPLIT stays unrepresentable, and this states why instead of
faking it. Verified against Envoy v1.39.0: udp_proxy's route action registry
is keyed on its own private RouteActionContext and holds exactly one action,
`Route`, whose only field is `cluster`. tcp_proxy's weighted_clusters has no
counterpart.

So does per-service selection, for a reason #873 does not mention and which
rules out its suggested fix direction. The capture path REDIRECTs UDP, which
rewrites the destination before delivery; a datagram listener's only
addressing cmsg is IP_PKTINFO, so a matcher's DestinationIPInput reads the
post-DNAT header and the ClusterIP is gone. Envoy never reads IP_ORIGDSTADDR
anywhere and original_dst is structurally TCP-only. DestinationPortInput is
not packet-derived at all — the port is stamped from the listening socket's
own port. A udp_proxy matcher therefore has nothing to discriminate on; that
needs TPROXY capture or a listener per service, which is a CNI change.

Also closes a dangling-cluster hole found on the way, of the same class as
proposal 037 Risk 1 and #877: captureUDPClusters skips a backend service the
cluster cache does not hold, but the generator would still name its cluster,
and udp_proxy has no on-demand cluster path — the datagrams are accepted and
dropped in silence. Both sides now consult one predicate
(udpClusterForLocked), so the listener and CDS cannot disagree, and
reconcileUDPCaptureListeners rebuilds on snapshot push when the bindable
cluster changes, so a UDPRoute landing before its backend registers does not
stay dark until the next UDPRoute event.

The detector #874 added is no longer a duplicate of the selection it reports
on: both call selectUDPRoute, so the drift that test was pinning is now
unrepresentable. The test stays as the end-to-end pin.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr
@bpalermo
bpalermo merged commit af8a9c9 into main Sep 23, 2026
21 of 22 checks passed
@bpalermo
bpalermo deleted the fix/873-udproute-weights branch September 23, 2026 11:02
bpalermo added a commit that referenced this pull request Sep 23, 2026
A pod may have at most one UDP service routed to it. #914 made that choice
principled — heaviest live backend, weight:0 honoured as drain, the discarded
shapes counted rather than dropped — but the limit itself is unchanged, and it
is not fixable in the control plane.

The cause is that the capture path destroys the information needed to tell one
service from another. TCP recovers the pre-DNAT destination via
use_original_dst; UDP has no equivalent. Envoy never reads IP_RECVORIGDSTADDR,
original_dst is structurally TCP-only, DestinationPortInput is the listening
socket's own port, and the five UdpMatchingData inputs cannot distinguish two
services behind a REDIRECT.

So #873's suggested fix does not work on either half: udp_proxy has no weighted
route action in any version (its matcher's terminal action has exactly one
field, `cluster`), and switching to `matcher` buys nothing while the input
carries no service identity.

This proposes TPROXY instead, which leaves the IP header intact so ipi_addr
still carries the ClusterIP.

Three of four premises were verified by experiment before writing this, in a
netns with no aether code:

  TPROXY   -> matcher arm A (saw the ClusterIP), reply delivered
  REDIRECT -> matcher arm B, reply delivered VIA CONNTRACK UN-DNAT
  TPROXY with the listener off the service port -> nothing delivered

The REDIRECT row is the control that makes the first row mean something, and it
also explains why this was never noticed: REDIRECT produces working traffic with
lost routing information, because conntrack repairs the reply.

The third row forces the design. Envoy's sendmsg never reads self_ip->port(), so
a reply's source port is always the bound port, and a connected UDP client drops
anything else — a port-rewriting TPROXY would give matching that works and
traffic that silently fails one way. Hence: preserve the dport, one transparent
listener per distinct UDP service port, destination_ip disambiguating within it.

The fourth premise is NOT established and Phase 0 exists to settle it: aether
binds capture listeners INTO the pod netns via network_namespace_filepath, and
the spike could not test that — the rig gave contradictory results for the same
nominal config, so neither reading is usable, and a rootless user namespace
cannot host the test at all. If Phase 0 says no, the proposal stops and #916
stands as a documented limit.

Also recorded: the Talos-host persistence risk flagged earlier is superseded.
The rules live in the POD netns, created at pod setup and dying with it, so
machine config never touches them.

Refs #916, #873


Claude-Session: https://claude.ai/code/session_01NArCRTfMPZkw4Y97U9Gdsr

Co-authored-by: Bruno Palermo <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

UDPRoute ignores backend weights and collapses multiple services onto one cluster

1 participant