Repository navigation
feat(udp): first-class UDP load balancing (#1273) - #1274
Merged
Merged
Conversation
Add a `udp` listener type alongside tcp/http/https so Sōzu can load-balance datagram services (DNS, syslog, NTP, generic UDP) without a second load balancer in front of it, reusing the control plane, metrics/logging and e2e harness. Architecture: a two-level sans-io core (lib/src/protocol/udp/: UdpManager admission/flow-table/generation-token timer-wheel over per-flow UdpFlow, pure and property-tested) driven by an I/O shell (lib/src/udp.rs) on the existing single-threaded mio loop. Static per-listener worker ownership; scale across cores by running multiple listeners. Flows reset on hot-upgrade (listener fd handed off via SCM, flow state not migrated). - Control plane: UdpListenerConfig + RequestUdpFrontend proto, TOML config parsing, ConfigState with diff/generate_requests/activate replay symmetry, SCM listener-fd hand-off, ctl CLI + master-process routing, and sozu top/listener-list/frontend-list/cluster display parity. - Datapath: virtual 4-tuple flows, three-knob teardown (responses / idle timeout / requests), symmetric NAT return via a per-flow connected upstream socket, bounded per-flow/per-listener write-queue egress backpressure with writable re-arm, max_flows fd-pressure shedding. No panic on network input (EMFILE/ENFILE/oversize/invalid -> drop + metric). - Load balancing: round-robin + HRW/rendezvous (default) + Maglev (opt-in), selectable per cluster via a key: Option<u64> threaded through the LB trait; the Maglev table is rebuilt only on backend-set change, never per datagram. - PROXY protocol v2 to the backend (first-datagram default, per-cluster every-datagram opt-in; DGRAM transport byte 0x12/0x22). - Active health checks bound to the endpoint: companion TCP probe (primary) + app-level UDP probe (secondary), rise/fall hysteresis, fail-open. - Metrics (udp.*) with no gauge underflow on any teardown path, and per-flow access logs under the UDP / UDP-FLOW log tag. - Tests: sans-io quickcheck/state-machine core tests, 14 e2e scenarios (RR/HRW/Maglev affinity, NAT return, teardown, truncation, PPv2, health/fail-open, hot reconfig, upgrade fd hand-off) with a mock UDP backend/client, and a fuzz_udp_flow cargo-fuzz target. - Docs: doc/configure.md UDP listener/cluster/health section + metrics, CHANGELOG, README, architecture. Plaintext only. Single-listener multi-core / eBPF SK_REUSEPORT / userland dispatcher / DSR / io_uring / DTLS / QUIC / UDP-over-HTTP / flow-state migration across upgrade are explicit non-goals. Signed-off-by: Florentin Dubois <[email protected]>
`test_udp_hrw_affinity_stable` asserted that >= half of 6 source keys keep their backend after an unrelated backend is added. HRW hashes the backend *address*, and e2e backend ports are dynamically allocated, so a favourably-hashing newcomer can legitimately capture a majority of a small key set (observed in CI: 4 of 6 keys moved, preserved=2/6). Combined with `repeat_until_error_or(5, ...)` requiring every round to pass, the test was ~18% flaky across port allocations. Replace the statistical preserved-fraction check with HRW's *provable*, port-independent minimal-disruption invariant: adding a backend can only move a key from its previous winner to the *new* backend (iff the newcomer now scores highest) — it can never reshuffle a key between two pre-existing backends. Assert every key either keeps its backend or moves to the newcomer. Signed-off-by: Florentin Dubois <[email protected]>
…rness
Adopt the TigerBeetle/FoundationDB deterministic-simulation testing patterns
for the sans-io UDP datapath, since the core is pure (injected clock + seed,
no I/O) and therefore bit-for-bit reproducible under a seed.
Assertion density (TigerStyle): dense `debug_assert` pre/post/invariant and
pair assertions (positive + negative space) throughout the core
(`protocol/udp/{manager,flow}.rs`), with a private `check_invariants()`
post-condition run at the end of every public `UdpManager` mutating method
(table/slab consistency, table injectivity, flow_count == slab len, no Closing
flow persists, Established<=>backend, timer coherence, counter bounds), plus
moderate invariants in the shell (`udp.rs`, inverse upstream/flow maps;
write-queue bound), health probes, and Maglev (table index/size/prime). All
gated by `debug_assertions` — compiled out in release, live in every test /
e2e / fuzz / dev build, turning silent correctness bugs into loud crashes.
Deterministic simulator (moonpool/VOPR style): `lib/tests/udp_simulation.rs`
drives `UdpManager` under a seeded `StdRng` + virtual clock with a randomized
adversarial workload (client/backend datagrams from a bounded source pool,
stale/unknown resolves, reconfig storms, max_flows shrink/grow, giant clock
jumps) and a FoundationDB-`buggify`-style fault-injection helper. Per-step and
drain-to-zero invariants run on top of the embedded asserts. Default sweep:
256 seeds x 3000 steps (~2s, runs in normal `cargo test`); env knobs
`SOZU_UDP_SIM_SEED` / `SOZU_UDP_SIM_SEEDS` / `SOZU_UDP_SIM_STEPS` for
single-seed replay and wider/deeper sweeps (VOPR failing-seed reproduction).
A 5.1M-step confidence run (1024 x 5000) is clean.
Also closes a latent gap in the log-layout regression scanner: the
`log_flow_context!` envelope (`UDP-FLOW` tag) was never registered in
`CONTEXT_MACROS` and only passed by falling within the lookbehind window;
register it so the canonical-envelope guard actually covers the UDP-flow site.
Docs: `doc/udp_simulation.md` (harness + replay/sweep commands), linked from
`doc/README.md`; CHANGELOG note.
Signed-off-by: Florentin Dubois <[email protected]>
Two CI failures introduced by the assertion-density + simulation commit: 1. `debug_assert!` compiles its arguments in EVERY profile — it gates only runtime execution, not compilation. The new pair-assertions snapshotted a "before" value under `#[cfg(debug_assertions)]` but read it inside a `debug_assert!`, so in release (where `cargo bench` and the Docker `--release` image build) the snapshot was cfg-removed while the read remained → E0425 "cannot find value" for `old_gen`, `before`, `flows_before_admit`, `flows_before_drop`. `cargo test` (debug) could not catch it. Drop the `#[cfg(debug_assertions)]` from the five trivial snapshot bindings: they are read only inside `debug_assert!`s (dead code in release, dropped by the optimizer) so they cost nothing but must compile. 2. `test_udp_maglev_affinity_stable` asserted ≥2 distinct backends across only 6 source keys. Maglev hashes the (CI-allocated) backend addresses, so a small key sample can legitimately land entirely on one backend's table slots (observed: distinct=1). Probe 20 keys instead — with a balanced Maglev table over 3 backends the all-on-one probability drops from ~1-in-700 to ~2e-9. Probes are serialised over loopback, so the larger key set adds no datagram-loss risk to the determinism check. Signed-off-by: Florentin Dubois <[email protected]>
Add `doc/testing.md` as the authoritative testing guide: the assertion-first (TigerBeetle TigerStyle) + deterministic-simulation (FoundationDB simulator / VOPR, and the moonpool-sim Rust engine in that lineage) doctrine, the five test categories (unit, integration/e2e, fuzz, deterministic simulation, regression guards), how to run each, the assertion-density standard, the deterministic- simulation recipe, the e2e conventions, the `#[ignore]` policy, and the checklist of what every change must land with. - CONTRIBUTING.md gains a Testing section with the contributor rules. - CLAUDE.md (project agent instructions) Testing section refreshed: points to doc/testing.md, adds the assertion-density + simulation rules, fixes the stale fuzz-target count (now three incl. fuzz_udp_flow) and the fuzz-e2e-wrapper note. - doc/README.md indexes the testing guide; CHANGELOG notes the harness. - The one pre-existing bare `#[ignore]` now carries its reason string. Cite the moonpool-sim crate as prior art; Sōzu does not depend on it (the `sozu-lib` no-`async fn` rule + the synchronous sans-io core make a direct seeded loop the right fit). The CI enforcement (the nightly fuzz_udp_flow run, the bare-#[ignore] guard job, and the scheduled simulation seed-sweep workflow) lands in the companion workflow commit on this branch. Signed-off-by: Florentin Dubois <[email protected]>
…weep - The nightly `fuzz` job now also runs `fuzz_udp_flow` (300s), alongside fuzz_frame_parser and fuzz_hpack_decoder. - New `Test hygiene` job rejects a bare `#[ignore]` (one without a reason string), per CONTRIBUTING.md#testing / doc/testing.md. - New scheduled `simulation-sweep.yml`: a daily FoundationDB-style seed swarm over the deterministic UDP simulator (debug build, so the TigerStyle `debug_assert` invariants are live) plus extended fuzzing of all three targets, both overridable via workflow_dispatch. Signed-off-by: Florentin Dubois <[email protected]>
Add lib/src/protocol/udp/LIFECYCLE.md, the canonical internals reference for the UDP load-balancing datapath, matching the existing mux/kawa_h1/proxy_protocol LIFECYCLE.md siblings: numbered sections, ASCII state-machine + datapath diagrams, and every claim anchored to a concrete file.rs:LINE. Covers: the one-listener-many-flows model, the two-level sans-io split and its ManagerInput/Output contract, the userland-conntrack flow table, the flow lifecycle state machine, the symmetric-NAT return via per-flow connected sockets, the three-knob + idle-timer teardown with generation tokens, PPv2 DGRAM, load balancing, health checks, the control plane (config/SCM/upgrade), and the hardening rules. Wire pointers from the module doc comments (mod.rs, udp.rs) and from doc/architecture.md, doc/README.md, and doc/lifetime_of_a_session.md, following the convention used for the other LIFECYCLE docs. Docs-only; no behavior change. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Jun 4, 2026
…based onto UDP) Rebase the full assertion-density sweep (Waves 1–5) onto current main, which now includes the merged UDP load balancing (#1274). ~1100 debug_assert + ~16 check_invariants across the H2/H1 mux, all protocols, the data plane, the server event loop, the command-plane (channel/scm/state/config/request/response/cert), and the bin supervisor + master command server. All debug_assert! only — compiled out in release, no behavior change. Includes three real bugs found by the sweep: - pattern-trie arithmetic-underflow panic on regex-leading hostnames (+ regression test); - pool checkout-capacity over-strict ==→>= (poule aligns 16393→16400); - diff() hot-reconfig listener-deactivation: a listener whose config changes while it stays active was silently deactivated on replay. Fixed for ALL listener types (http/https/tcp AND udp): emit ActivateListener after the Remove+Add when the target keeps it active; re-enabled listener-map convergence (incl. udp_listeners) in the diff() check_invariants postcondition. UDP-integration fixes to the rebased assertions (UDP added a fourth listener/ frontend protocol the Wave-4 command-plane asserts predate): count_frontends and the scm FD-count reconciliation (send + receive) now fold udp; the per-frontend order count accepts AddUdpFrontend; the scm receive "final cursor == total" asserts moved past the udp zip with a udp pairing assert. Two wrong server.rs assertions (single-token assumptions — sessions are multi-token) were corrected earlier. 602 lib + 100 command-lib + 116 bin unit tests pass with assertions live; all crates release-clean; clippy -D warnings. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Jun 4, 2026
…(backends, LB, socket, lib root) Complete the assertion sweep across the five files the UDP PR was rewriting, now that #1274 has merged — so the assertions land on the final code with no deferred work. - backends.rs: BackendList check_invariants (monotonic registration id, unique (address, backend_id)); health rise/fall streak exclusivity + saturating connection counters; try_connect success/failure accounting; cluster availability (available <= total, empty != AllDown); add/remove map ±1; keyed and non-keyed selection return a live cluster member. - load_balancing.rs: RoundRobin index-in-bounds + empty guard; HRW score finite and the winner maximizes it (weight >= 1); Maglev table indices < size, the populate loop fills exactly `size` slots (termination), lookup maps into the healthy subset; Random/LeastLoaded/PowerOfTwo population + selection. - socket.rs: server_bind/udp_bind/udp_connect post-conditions (nonblocking + SO_REUSE flags set, addr family matches, the connected udp socket's ephemeral source port is non-zero and getpeername echoes the backend); read/write cursor-in-bounds + reported-count <= remaining on the symmetric tcp/rustls paths (the 4.5 MB-truncation-class guard). - lib.rs: Readiness check_invariants (no bit outside READABLE|WRITABLE|ERROR|HUP); signal_pending_read/write/arm_writable each set exactly their bit and touch nothing else; filter_interest yields a subset present in both words. Also one more UDP-integration fix surfaced by the UDP upgrade e2e: generate_activate_requests' active-listener census now folds udp_listeners (it predated the fourth listener protocol). No assertion fired beyond the census gaps fixed here; selection/socket/readiness behavior is unchanged. lib + command + bin unit tests pass with assertions live; udp/listener_update/tls e2e green; release-clean; clippy -D warnings. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Jun 4, 2026
…based onto UDP) Rebase the full assertion-density sweep (Waves 1–5) onto current main, which now includes the merged UDP load balancing (#1274). ~1100 debug_assert + ~16 check_invariants across the H2/H1 mux, all protocols, the data plane, the server event loop, the command-plane (channel/scm/state/config/request/response/cert), and the bin supervisor + master command server. All debug_assert! only — compiled out in release, no behavior change. Includes three real bugs found by the sweep: - pattern-trie arithmetic-underflow panic on regex-leading hostnames (+ regression test); - pool checkout-capacity over-strict ==→>= (poule aligns 16393→16400); - diff() hot-reconfig listener-deactivation: a listener whose config changes while it stays active was silently deactivated on replay. Fixed for ALL listener types (http/https/tcp AND udp): emit ActivateListener after the Remove+Add when the target keeps it active; re-enabled listener-map convergence (incl. udp_listeners) in the diff() check_invariants postcondition. UDP-integration fixes to the rebased assertions (UDP added a fourth listener/ frontend protocol the Wave-4 command-plane asserts predate): count_frontends and the scm FD-count reconciliation (send + receive) now fold udp; the per-frontend order count accepts AddUdpFrontend; the scm receive "final cursor == total" asserts moved past the udp zip with a udp pairing assert. Two wrong server.rs assertions (single-token assumptions — sessions are multi-token) were corrected earlier. 602 lib + 100 command-lib + 116 bin unit tests pass with assertions live; all crates release-clean; clippy -D warnings. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Jun 4, 2026
…(backends, LB, socket, lib root) Complete the assertion sweep across the five files the UDP PR was rewriting, now that #1274 has merged — so the assertions land on the final code with no deferred work. - backends.rs: BackendList check_invariants (monotonic registration id, unique (address, backend_id)); health rise/fall streak exclusivity + saturating connection counters; try_connect success/failure accounting; cluster availability (available <= total, empty != AllDown); add/remove map ±1; keyed and non-keyed selection return a live cluster member. - load_balancing.rs: RoundRobin index-in-bounds + empty guard; HRW score finite and the winner maximizes it (weight >= 1); Maglev table indices < size, the populate loop fills exactly `size` slots (termination), lookup maps into the healthy subset; Random/LeastLoaded/PowerOfTwo population + selection. - socket.rs: server_bind/udp_bind/udp_connect post-conditions (nonblocking + SO_REUSE flags set, addr family matches, the connected udp socket's ephemeral source port is non-zero and getpeername echoes the backend); read/write cursor-in-bounds + reported-count <= remaining on the symmetric tcp/rustls paths (the 4.5 MB-truncation-class guard). - lib.rs: Readiness check_invariants (no bit outside READABLE|WRITABLE|ERROR|HUP); signal_pending_read/write/arm_writable each set exactly their bit and touch nothing else; filter_interest yields a subset present in both words. Also one more UDP-integration fix surfaced by the UDP upgrade e2e: generate_activate_requests' active-listener census now folds udp_listeners (it predated the fourth listener protocol). No assertion fired beyond the census gaps fixed here; selection/socket/readiness behavior is unchanged. lib + command + bin unit tests pass with assertions live; udp/listener_update/tls e2e green; release-clean; clippy -D warnings. Signed-off-by: Florentin Dubois <[email protected]>
This was referenced Jun 5, 2026
Closed
Closed
FlorentinDUBOIS
added a commit
that referenced
this pull request
Jun 5, 2026
Three stale spots contradicted the code: - doc/configure.md described the cluster load-balancing key as `load_balancing_policy` with values "roundrobin"/"random". The key is `load_balancing` (SCREAMING_SNAKE_CASE) and six algorithms exist: ROUND_ROBIN, RANDOM, LEAST_LOADED, POWER_OF_TWO, HRW, MAGLEV (lib/src/load_balancing.rs, command.proto LoadBalancingAlgorithms). - bin/config.toml listed only four values, omitting HRW/MAGLEV. - doc/upgrade/1.x-to-2.0.md still listed UDP load balancing (#654) as "future"; it landed via #1274. Doc/comment-only change, no behavior impact. Signed-off-by: Florentin Dubois <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a first-class
udplistener type to Sōzu alongsidetcp/http/https, so Sōzu can load-balance datagram services (DNS, syslog, NTP, generic UDP) without a second load balancer in front of it. Implements issue #1273. The design preserves Sōzu's architecture — userland, single-threaded mio per worker, hot-reconfig via protobuf IPC + SCM fd-passing, slab sessions, the e2e harness — and introduces a two-level sans-io UDP core (a pure flow state machine, I/O at the edges) for testability.Architecture
lib/src/protocol/udp/):UdpManager(admission, 4-tuple flow table,max_flowscap + shedding, LB-selection request, single-deadline timer wheel with generation tokens) over per-flowUdpFlow(three-knob teardown, idle/lifetime deadlines, PPv2 bookkeeping). No socket, no clock, no rand — fully unit/property/fuzz-tested.lib/src/udp.rs): owns syscalls, per-flow connected upstream sockets (the NAT-return demux key), bounded write-queue egress backpressure with writable re-arm, the buffer pool, the timer wheel, health checks and metrics. Wired into the event loop inlib/src/server.rsvia a UDP-specific listener-ingest/readiness path (not the TCPaccept()/create_sessionmodel).What's included
UdpListenerConfig+RequestUdpFrontendproto, TOML config parsing ([[listeners]]+[clusters.<id>.udp(.health)]),ConfigStatewith diff/generate/activate replay symmetry, SCM listener-fd hand-off,sozuctlCLI (listener udp …,frontend udp …) + master-process routing, andsozu top/listener-list/frontend-list/cluster display parity.key: Option<u64>threaded through the LB trait. Maglev's lookup table is rebuilt only on backend-set change (never per datagram) and selection is health-aware.0x12/0x22).udp.*) with no gauge underflow on any teardown path, and per-flow access logs under theUDP/UDP-FLOWlog tag.Security / protocol impact
This is a security-sensitive datapath (UDP is an amplification/DoS vector with no backpressure), built within Sōzu's conservative no-panic-on-network-input model:
EMFILE/ENFILE/max_flows→ shed, never panic.max_flowsdefaults to ~70% of the softRLIMIT_NOFILE, clamped against shared-slab headroom so a UDP listener cannot starve HTTP/TCP.max_rx_datagram_sizeis clamped tobuffer_size.udp.active_flowsis balanced on every close (idle, responses/requests reached, drain, soft/hard-stop, listener remove/deactivate, upstream-open failure).UdpSocketfd hand-off across re-exec verified fd-type-agnostic; no double-close;O_NONBLOCK/SO_REUSE*preserved.A 3-reviewer pass over the new code (core/LB, shell/wiring, control-plane) surfaced and fixed: a Maglev per-packet table-rebuild DoS amplifier, an
active_flowsgauge leak on listener removal, a broken config-file UDP-frontend path (the documented DNS example now loads),recv_bufnot resized on listener update, and UDP objects missing fromlist/display.Testing
quickcheckstate-machine tests (generation-token races, reaper-drains-to-zero / no fd leak, cap-never-exceeded, three-knob teardown) + byte-exact PPv2 tests + HRW/Maglev distribution/stability tests + a state round-trip test.e2e/src/tests/udp_tests.rs, new mock UDP backend/client): basic forward + symmetric NAT return, RR distribution, HRW & Maglev affinity,responses/requests/idle teardown, oversized-datagram drop, PPv2-to-backend, hot add/remove/activate listener, fail-open,SOURCE_IP_PORTaffinity, and listener fd hand-off across upgrade.fuzz/fuzz_targets/fuzz_udp_flow.rs(flow-key extraction + manager input handling + PPv2 framing) — 20k runs, no crash.Commands run (all green)
Docs
doc/configure.md(UDP listener/cluster/health config +udp.*metrics),CHANGELOG.md,README.md,doc/architecture.mdupdated in the same changeset.Non-goals (explicit)
Plaintext only. Single-listener multi-core / eBPF
SK_REUSEPORT/ userland dispatcher / DSR / io_uring / XDP / DTLS / QUIC-HTTP3 / UDP-over-HTTP tunneling / flow-state migration across upgrade / inbound UDP PROXY decode are out of scope by design.