Skip to content

refactor(command): share cluster ids as Arc<str> instead of copying Strings - #1629

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/cluster-id-rc
Sep 27, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
refactor/cluster-id-rc

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Sep 27, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

sozu_command_lib::state::ClusterId was String. Every routed request cloned its cluster id out of the route table (RouteResult built from the matched Route::Frontend), 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 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.

ClusterId is now Arc<str>. The route table, HttpContext::cluster_id, the gate's SessionManager maps, ConnectPlan::Dial and the backend connection's Position::Client all 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, generated command.rs, not edited) keep String. The id is converted once, when a request or a saved state enters ConfigState or a proxy.

Measurements

These counts come from the test_allocations counting allocator in sozu-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 is Router::plan_connect, then on the gated path consult_ip_gate with its SessionManager bookkeeping and Router::plan_connect_resume, then the production release (unlink_stream + ledger drain). The harness was a temporary unit test beside a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id and is not committed. The BEFORE numbers were measured on 0155d40b and again on 58550dd4 (#1625 merged), with identical results. The AFTER numbers were measured on this branch, rebased on 58550dd4, with Arc<str>.

Backend connection Gate Before (release) After (release) Before (debug) After (debug)
H1 keep-alive none (no source address) 1 0 4 3
H1 keep-alive per-(cluster, source-IP) 4 0 7 3
H2 connected none 1.28 0.28 4.28 3.28
H2 connected per-(cluster, source-IP) 4.28 0.28 7.28 3.28
  • The remaining 0.28 on H2 is the backend H2 connection's stream table growing across the 64 streams. It is not a cluster id.
  • The remaining 3 in debug are the DebugEvent::Str history push, which is compiled out of release builds.
  • The frontend protocol (H1 or H2) makes no difference here. Routing stamps HttpContext::cluster_id the 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_id now includes the gate's SessionManager bookkeeping in its measurement. Its control covers only the debug history, and it asserts branched == controlled. I saw it fail (release, 64 vs 0) by handing track_cluster_connection a fresh ClusterId::from(&**cluster_id), then pass again once that was reverted.
  • a_dial_moves_the_planned_cluster_id_into_the_backend_connection also asserts that the new connection and the stream's HttpContext point at the same id. I saw it fail by stamping ConnectPlan::Dial with ClusterId::from(&**cluster_id).
  • a_tree_lookup_allocates_nothing_past_its_route_result: the control no longer counts a copy of the cluster id.

Arc rather than Rc

A worker is single-threaded, but ConfigState and the response types are public API that embedders share across threads.

  • proxy-manager keeps ConfigState in context::State (src/svc/context.rs), behind a tokio::sync::RwLock inside an Arc<Context>. That value is captured by multi-threaded tokio::spawn tasks and used as an axum::Extension, so it must be Send + Sync. proxy-manager depends on sozu-command-lib = "^2.2.0", so an Rc<str> alias would break its build on its next cargo update. An intermediate Rc<str> revision of this branch did exactly that when checked against proxy-manager: 36 errors per target.
  • Assertion: a compile-time assertion next to the alias (command/src/state.rs) now locks the contract. It holds ClusterId, ConfigState, StateError and response::{HttpFrontend, TcpFrontend, UdpFrontend, Backend} to Send + Sync.
    • With Rc<str> the crate fails with 14 E0277 errors (Rc<str> cannot be sent / shared between threads safely): one Send and one Sync error for each of the seven types.
    • With Arc<str> it builds.
  • Test harnesses: the moonpool-sim harness and the e2e worker handle also rely on Send, and are unchanged.
  • Cost: an Arc clone is an uncontended atomic increment.
  • proxy-manager check (origin/main 1f61a03, temporary detached worktree, nothing committed): after cargo update -p [email protected] --precise 2.2.1 and cargo 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: sozu main already requires mio ^1.2.3.

API break

  • sozu-command-lib:
    • state::ClusterId changes from String to Arc<str>. The types stay Send + Sync, and a compile-time assertion now guarantees it.
    • The following follow it: the keys of ConfigState::{clusters, backends, tcp_fronts, udp_fronts}, ConfigState::hash_state / get_cluster_ids_by_domain, the fields of StateError::UdpFrontendAddressTaken, and cluster_id on response::{HttpFrontend, TcpFrontend, UdpFrontend, Backend}.
    • serde's rc feature is enabled on the existing serde dependency, so these types keep deriving Serialize/Deserialize. There is no new crate and Cargo.lock is unchanged.
    • JSON output and state hashes are unchanged, because Arc<str> serializes and hashes as the str it 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_id and protocol::udp::ClusterConfig::cluster now take or return ClusterId.
  • To migrate, use .into() / ClusterId::from(..) from &str or String.

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}.rs diff is limited to types (plus one test fixture in h2.rs), and the branch was rebased on #1625. Doc citations were kept line-stable, so check_doc_citations.py --base origin/main passes without renumbering anything.

Commands run (on the pushed SHA unless noted)

  • cargo build --locked → exit 0
  • cargo build --all-features --locked → exit 0
  • cargo build --workspace --all-targets --all-features --locked → exit 0
  • cargo clippy --all-targets --locked -- -D warnings → exit 0 (also --all-features)
  • cargo +nightly fmt --all -- --check → exit 0
  • cargo test --workspace --locked --exclude sozu-e2e -- --skip tests::fuzz_tests:: → 1703 passed, 0 failed
  • cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests:: --test-threads=8 → 456 passed, 0 failed
  • cargo test --release -p sozu-lib --lib -- allocat copies_no_cluster_id a_dial_moves → 20 passed
  • RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked → 31 passed
  • cargo check --bins --locked in fuzz/ → exit 0 (both fuzz targets that build a ClusterConfig / route table were updated)
  • python3 .github/scripts/check_doc_citations.py --self-test → 0; --root . → 0; --root . --base origin/main → 0; --audit --root . → 0

CHANGELOG.md (Changed) and the docs that described the old copies (doc/testing.md, lib/src/protocol/mux/LIFECYCLE.md, the SessionManager and mux doc comments) are updated in the same commit.

Signed-off-by: Florentin Dubois [email protected]

@FlorentinDUBOIS FlorentinDUBOIS changed the title refactor(command): share cluster ids as Arc<str> instead of copying Strings refactor(command): share cluster ids as Rc<str> instead of copying Strings Sep 27, 2026
@FlorentinDUBOIS FlorentinDUBOIS changed the title refactor(command): share cluster ids as Rc<str> instead of copying Strings refactor(command): share cluster ids as Arc<str> instead of copying Strings Sep 27, 2026
…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
FlorentinDUBOIS merged commit 3a79685 into main Sep 27, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the refactor/cluster-id-rc branch September 27, 2026 23:55
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]>
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.

1 participant