Repository navigation
refactor(command): share cluster ids as Arc<str> instead of copying Strings - #1629
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 27, 2026 20:16
FlorentinDUBOIS
force-pushed
the
refactor/cluster-id-rc
branch
from
September 27, 2026 21:09
ef10f3d to
6ce8c95
Compare
FlorentinDUBOIS
force-pushed
the
refactor/cluster-id-rc
branch
from
September 27, 2026 22:20
6ce8c95 to
e9012ea
Compare
…trings
`sozu_command_lib::state::ClusterId` was `String`, so routing cloned the
id out of the route table on every request, and the per-(cluster,
source-IP) gate cloned it three more times: in `consult_ip_gate`, in
`SessionManager::track_cluster_connection`, and as the `entry` key of
`SessionManager::track_cluster_ip`, the last one paid even when the
track is an idempotent no-op.
`ClusterId` is now `Arc<str>`. The route table, `HttpContext::cluster_id`,
the gate's maps, `ConnectPlan::Dial` and the backend connection's
`Position::Client` share the one allocation made when the frontend was
added; the TCP and UDP listeners, sessions and pipes share theirs the
same way. Protobuf messages keep `String`: the id is converted once,
where a request or saved state enters `ConfigState` or a proxy.
Allocations per routed request on a reused backend connection
(`plan_connect`, the gate with its `SessionManager` bookkeeping,
`plan_connect_resume`, release build, 64 requests after a warm-up):
H1 keep-alive 1 -> 0 ungated and 4 -> 0 gated; H2 connected
1.28 -> 0.28 ungated and 4.28 -> 0.28 gated, the 0.28 being the H2
stream table growing. Production traffic always carries a source
address, so it always takes the gated path.
`Arc` rather than `Rc`: `ConfigState` and the `response` types are
public API that embedders share across threads. proxy-manager keeps
`ConfigState` behind a `tokio::sync::RwLock` in an `Arc`, captured by
multi-threaded `tokio::spawn` tasks and used as an axum extension, so
it needs them `Send + Sync`; with `Rc<str>` it fails to build. A
compile-time assertion next to the alias now holds `ClusterId`,
`ConfigState`, `StateError` and the four `response` types to
`Send + Sync`. The count is never contended since each worker is
single-threaded.
This breaks the `sozu-command-lib` API: `ClusterId`, the keys of
`ConfigState::{clusters, backends, tcp_fronts, udp_fronts}`,
`ConfigState::{hash_state, get_cluster_ids_by_domain}`,
`StateError::UdpFrontendAddressTaken` and `cluster_id` on
`response::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}`. serde's
`rc` feature is enabled so these types keep their derives; the JSON of
a saved state and every hash are unchanged, since `Arc<str>` serializes
and hashes as its `str`. `sozu-lib` signatures carrying a cluster id
follow.
`a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id`
now measures the gate's bookkeeping and controls only for the debug
history, the tree-lookup test no longer counts a cluster id copy in its
control, and `a_dial_moves_the_planned_cluster_id_into_the_backend_connection`
also asserts that the connection and the stream point at the same id.
Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
refactor/cluster-id-rc
branch
from
September 27, 2026 22:50
e9012ea to
385f1dd
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
## Problem The access log's `client_rtt` and `server_rtt` each cost one `getsockopt(TCP_INFO)` per request. The H1 log sites (`H1::Complete`, `H1::Upgrade`, `H1::EarlyHint`) and `Endpoint::peer_rtt` read their socket at every line, and `Mux::expire_client_rtt` forgot the H2 frontend sample at every pass (#1598 made the read lazy, not rarer). On an H1 keep-alive connection that was 2.00 of the worker's 11.55 syscalls per request. ## Change Operator decision: accept one sample per connection. - `memoized_rtt` (`lib/src/protocol/mux/mod.rs`) keeps a connection's first sample in a `Cell<Option<Option<Duration>>>` on the connection (`ConnectionH1::rtt`, new field; `H2Shell::local_rtt`, existing field) and answers every later request from it. `Connection::rtt` dispatches H1/H2. - Every mux RTT read goes through it: the three H1 log sites, `EndpointServer::peer_rtt`, `EndpointClient::peer_rtt`, `ShellEndpoint::local_rtt` and `Mux::close`. A backend connection keeps its sample across keep-alive pool reuse, since the `Connection` carries it. - `Mux::expire_client_rtt` and `H2Shell::expire_local_rtt` are removed. - Pipe (TCP/WebSocket) and the TCP frontend already log once per session and are unchanged. After a WebSocket upgrade, `Pipe::log_request` still reads `socket_rtt` once, at the end of the session. That is one read per session, left out of scope. No syscall added anywhere, no allocation added (one `Cell` of 16 bytes per `ConnectionH1`), no I/O path touched. ## Sampling point, and why Hypothesis tested: "`tcpi_rtt` is 0 before the first data ACK". **Refuted** on Linux 7.2.7, loopback. A Python probe reading `TCP_INFO` (`tcpi_rtt`, `tcpi_rttvar`): - straight out of `accept`: 34 / 27 / 29 µs over three trials. This is the SYN/SYN-ACK measurement. - straight out of a blocking `connect`: 80 / 30 / 33 µs. - after 1st/2nd/3rd request on the same connection: 34 → 33 → 1301 µs. The SRTT keeps drifting. So a sample at `accept` would be valid. The chosen point is still **the connection's first access log**: - frontend: the first request completed on the connection; - backend: the first response logged through it. The lazy read is free on a connection that never logs. A backend dial is still in flight when its non-blocking `connect(2)` returns. Semantics, now documented: **"RTT sampled at the connection's first request"**, repeated on every line of that connection. The value is frozen and no longer follows the kernel's SRTT. The two cells of one line come from two different instants. ## Measurement `intentrace -p` on the worker. Release build `--no-default-features --features jemallocator,crypto-aws-lc-rs`, one worker, python `http.server` backend on loopback, `curl`, 20 requests on one client connection (plus warmup). Base `58550dd4`, runs interleaved base/after, two runs per cell, 1-minute load average 21–48 (shared host): | scenario | syscalls/req before | after | `getsockopt`/req before | after | |---|---|---|---|---| | H1 keep-alive, plaintext | 11.55, 11.55 | 9.65, 9.65 | 2.00 | 0.10 | | H1 keep-alive, TLS | 11.85, 11.85 | 9.95, 9.95 | 2.00 | 0.10 | | H2, 20 streams multiplexed on 1 connection | 12.35, 12.20 | 11.35, 11.30 | 2.00 | 1.05 | - **H1: −1.90 syscalls/req.** The remaining 0.10 is the two per-connection reads, one per side. - **H2 multiplexed: −1.00.** Sozu dials one backend H1 connection per concurrent stream (20 `connect`s in the window), so the 20 backend reads remain, one per connection. Only the 19 repeated frontend reads disappear. - **Access logs, after:** every one of the 27 lines per run carries both `client_rtt` and `server_rtt`, with no `-` cell. There are 4 distinct (client, server) pairs, one per client connection (readiness probe, two warmups, the measured one). Before: 27 distinct pairs. ## Tests Seen red on `58550dd4` before the fix, green after: - `keep_alive_requests_read_tcp_info_once_per_connection` (`h1.rs`, new). It drives 20 keep-alive requests through the real `H1::Complete` site of `ConnectionH1::writable`, with the backend recycled by `end_stream`/`start_stream` as a `Mux` does. It asserts two things: - 2 `TCP_INFO` reads in total. Red: `left: 40, right: 2`. - Both RTT cells are present on all 20 access lines, with identical values. - `a_mux_pass_keeps_the_connection_sample_and_reads_none_without_a_log` (`mod.rs`). This rewrites `a_mux_pass_forgets_the_previous_sample_and_reads_none_without_a_log`. Red: `left: None, right: Some(Some(4321s))`. Also rewritten: `snapshot_rtts_samples_the_frontend_once_per_pass` became `snapshot_rtts_samples_the_frontend_once_per_connection` (`h2.rs`). Its documented red (the memo hit removed from `memoized_rtt`) was checked: `left: 2, right: 1`. The old names are forwarded in `check_doc_citations.py` `RENAMED_TESTS`, because the CHANGELOG cites them. ## Docs - `doc/configure.md` "When each cell is measured": **Changed** RTT semantics in access logs. - `doc/observability.md`. - `doc/h2_mux_internals.md`: new "One sample per connection" section, with the measurements. - `lib/src/protocol/mux/LIFECYCLE.md`. - `CHANGELOG.md` (Changed). My line shifts in `h1.rs`, `h2.rs` and `mod.rs` moved 27 `file.rs:NNN` citations and three pinned blocks. They are re-anchored mechanically from a line diff, in both `LIFECYCLE.md`, `doc/testing.md` and `doc/h2_mux_internals.md`, and `--base origin/main` confirms every cited line's text is unchanged. ## Conflicts with open PRs - `git merge-tree` against #1628 and #1629: clean. The new test uses `"test-cluster".into()`, so it compiles with #1629's `ClusterId` too. - Against #1630: three pinned `h2.rs:NNNN` fence numbers in `doc/h2_mux_internals.md` / `LIFECYCLE.md` conflict, numbers only. Whichever PR merges second re-anchors them. - `kawa_h1/editor.rs` and `HttpContext` are untouched. ## Commands run - `cargo build --locked` - `cargo build --all-features --locked` - `cargo clippy --all-targets --locked -- -D warnings` - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` - `cargo +nightly fmt --all -- --check` - `check_doc_citations.py` (tree, `--base origin/main`, `--self-test`, broken-fixture `--root` exit 1 with its failure report) - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`: 2160 passed, 0 failed. Results: - The full battery passed on the pre-amend tree. - The final amend changed only a test literal (`to_owned()` → `into()`). After it I re-ran fmt, both clippy cells, the citation runs and the new test. - A first battery run had one failure: `tests::tests::test_async` (client1 99/100 responses) under `--test-threads=8` at load average 40+. I ran it 3 times in isolation on this branch and 3 times on `58550dd4`: 6/6 green. The second full battery run was green. Protocol/security impact: none. No framing, parsing, readiness or I/O change. The only change is when an access-log value is read. 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.
Motivation
sozu_command_lib::state::ClusterIdwasString. Every routed request cloned its cluster id out of the route table (RouteResultbuilt from the matchedRoute::Frontend), and the per-(cluster, source-IP) gate cloned it three more times: inconsult_ip_gate, inSessionManager::track_cluster_connection, and as theentrykey ofSessionManager::track_cluster_ip. The last clone happened even when the track was an idempotent no-op. Production traffic always carries a source address, so it always goes through the gate.ClusterIdis nowArc<str>. The route table,HttpContext::cluster_id, the gate'sSessionManagermaps,ConnectPlan::Dialand the backend connection'sPosition::Clientall share the one allocation made when the frontend was added. The TCP and UDP listeners, sessions, pipes and preread routes share theirs in the same way. The protobuf messages (command.proto, generatedcommand.rs, not edited) keepString. The id is converted once, when a request or a saved state entersConfigStateor a proxy.Measurements
These counts come from the
test_allocationscounting allocator insozu-lib. Each figure is the number of allocations per routed request on a reused backend connection, averaged over 64 requests after one warm-up. The measured path isRouter::plan_connect, then on the gated pathconsult_ip_gatewith itsSessionManagerbookkeeping andRouter::plan_connect_resume, then the production release (unlink_stream+ ledger drain). The harness was a temporary unit test besidea_routed_request_on_a_reused_backend_connection_copies_no_cluster_idand is not committed. The BEFORE numbers were measured on0155d40band again on58550dd4(#1625 merged), with identical results. The AFTER numbers were measured on this branch, rebased on58550dd4, withArc<str>.DebugEvent::Strhistory push, which is compiled out of release builds.HttpContext::cluster_idthe same way for both, so the axis that matters is the kind of backend connection.Allocation tests that pin the result:
a_routed_request_on_a_reused_backend_connection_copies_no_cluster_idnow includes the gate'sSessionManagerbookkeeping in its measurement. Its control covers only the debug history, and it assertsbranched == controlled. I saw it fail (release, 64 vs 0) by handingtrack_cluster_connectiona freshClusterId::from(&**cluster_id), then pass again once that was reverted.a_dial_moves_the_planned_cluster_id_into_the_backend_connectionalso asserts that the new connection and the stream'sHttpContextpoint at the same id. I saw it fail by stampingConnectPlan::DialwithClusterId::from(&**cluster_id).a_tree_lookup_allocates_nothing_past_its_route_result: the control no longer counts a copy of the cluster id.Arcrather thanRcA worker is single-threaded, but
ConfigStateand theresponsetypes are public API that embedders share across threads.ConfigStateincontext::State(src/svc/context.rs), behind atokio::sync::RwLockinside anArc<Context>. That value is captured by multi-threadedtokio::spawntasks and used as anaxum::Extension, so it must beSend + Sync. proxy-manager depends onsozu-command-lib = "^2.2.0", so anRc<str>alias would break its build on its nextcargo update. An intermediateRc<str>revision of this branch did exactly that when checked against proxy-manager: 36 errors per target.command/src/state.rs) now locks the contract. It holdsClusterId,ConfigState,StateErrorandresponse::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}toSend + Sync.Rc<str>the crate fails with 14E0277errors (Rc<str>cannot be sent / shared between threads safely): oneSendand oneSyncerror for each of the seven types.Arc<str>it builds.Send, and are unchanged.Arcclone is an uncontended atomic increment.origin/main1f61a03, temporary detached worktree, nothing committed): aftercargo update -p [email protected] --precise 2.2.1andcargo update -p mio --precise 1.2.3,cargo check --all-targets --config 'patch.crates-io.sozu-command-lib.path="<this branch>/command"'→EXIT=0. The mio update is a lockfile-only change: sozumainalready requires mio^1.2.3.API break
sozu-command-lib:state::ClusterIdchanges fromStringtoArc<str>. The types staySend + Sync, and a compile-time assertion now guarantees it.ConfigState::{clusters, backends, tcp_fronts, udp_fronts},ConfigState::hash_state/get_cluster_ids_by_domain, the fields ofStateError::UdpFrontendAddressTaken, andcluster_idonresponse::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}.rcfeature is enabled on the existing serde dependency, so these types keep derivingSerialize/Deserialize. There is no new crate andCargo.lockis unchanged.Arc<str>serializes and hashes as thestrit holds.sozu-lib:HttpContext::cluster_id,SessionManager::{track_cluster_ip, track_cluster_subnet, track_cluster_connection},BackendConnectionError::{MaxConnectionRetries, TooManyConnectionsPerIp},ProxySession::cluster_id,Pipe::set_cluster_idandprotocol::udp::ClusterConfig::clusternow take or returnClusterId..into()/ClusterId::from(..)from&strorString.This PR does not change protocol or security behaviour. No wire format, config key, metric, CLI flag or log line changes. The
lib/src/protocol/mux/{connection,mod,h2}.rsdiff is limited to types (plus one test fixture inh2.rs), and the branch was rebased on #1625. Doc citations were kept line-stable, socheck_doc_citations.py --base origin/mainpasses without renumbering anything.Commands run (on the pushed SHA unless noted)
cargo build --locked→ exit 0cargo build --all-features --locked→ exit 0cargo build --workspace --all-targets --all-features --locked→ exit 0cargo clippy --all-targets --locked -- -D warnings→ exit 0 (also--all-features)cargo +nightly fmt --all -- --check→ exit 0cargo test --workspace --locked --exclude sozu-e2e -- --skip tests::fuzz_tests::→ 1703 passed, 0 failedcargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests:: --test-threads=8→ 456 passed, 0 failedcargo test --release -p sozu-lib --lib -- allocat copies_no_cluster_id a_dial_moves→ 20 passedRUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked→ 31 passedcargo check --bins --lockedinfuzz/→ exit 0 (both fuzz targets that build aClusterConfig/ route table were updated)python3 .github/scripts/check_doc_citations.py --self-test→ 0;--root .→ 0;--root . --base origin/main→ 0;--audit --root .→ 0CHANGELOG.md(Changed) and the docs that described the old copies (doc/testing.md,lib/src/protocol/mux/LIFECYCLE.md, theSessionManagerand mux doc comments) are updated in the same commit.Signed-off-by: Florentin Dubois [email protected]