Repository navigation
perf(router): copy no authority and allocate no trie path per request - #1594
Merged
Merged
Conversation
Router::route_from_request made three heap allocations per routed request (#1584). Two of them go away without a public type change. The authority was copied into HttpContext::original_authority on every request, for the X-Forwarded-Host header a host rewrite injects and that nothing else reads. HttpContext::authority still holds what the client sent when apply_request_rewrites_and_headers runs, because the rewrite mutates only the kawa status line and headers, so the helper now copies it there, only on a host rewrite, and moves that copy into original_authority. The field is None on a request without a host rewrite, as its documentation already said. Router::lookup handed the trie a Vec::with_capacity(16) to record the wildcard and regex segments it matched, even for a literal host that records none. A crate-private InlineTrieMatches keeps the first 16 segments on the stack and spills to a Vec only past them, so $HOST[n] templates still see every segment in walk order. TrieMatches and TrieNode::lookup_with_path are unchanged. In the release build route_from_request now allocates once per request: the cluster id cloned out of the route table, which needs ClusterId changed in sozu-command-lib and stays out of scope. The control of a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id is narrowed to that clone and the debug history push, so the rest of routing is measured. New tests pin Router::lookup allocations on literal, wildcard and regex hosts, a 20-segment regex host through the spill, the sink's rewind across the spill boundary, and original_authority plus X-Forwarded-Host with and without a host rewrite. Closes #1589 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 26, 2026 20:10
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 27, 2026
## Summary A `Tree`-position hostname numbered its `$HOST[n]` captures right to left (the order the trie walks the labels), while a `Pre`/`Post` hostname numbers them left to right (one whole-host regex). The same hostname therefore gave different rewrites depending on its position. - `doc/configure.md` stated no order. This change takes left to right, the reading order and the `Pre`/`Post` order, and documents it beside the template grammar. - `RouteResult::new_with_trie` now reads the trie's record in reverse (`InlineTrieMatches::iter` returns a `DoubleEndedIterator`). Each segment keeps its own groups in regex order. No allocation is added: the reverse read crosses from the spill into the inline array in place. - `a_host_capture_past_sixteen_trie_segments_keeps_every_segment` (#1594) pinned the walk order; it now expects `1-2-…-20`. The four spilled entries are the leftmost segments, so the reversed read still crosses the spill boundary. - New `a_tree_rule_numbers_its_host_captures_like_a_pre_or_post_rule`: `/a([0-9]+)/./([a-z])([0-9])/.example.com`, template `$HOST[1]-$HOST[2]-$HOST[3]`, host `a1.x9.example.com`. Before the fix: `left: Some("x-9-1") right: Some("1-x-9")` for `Tree`; after: all three positions give `1-x-9`. - `CHANGELOG.md`: BREAKING (behaviour) entry under Fixed, with who is affected and the migration. - `doc/configure_admin_ops.md`: one citation re-anchored to the same metrics-table line, moved by the new paragraph. ## Verification - `cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd` -> exit 0 - `cargo +nightly fmt --all -- --check` -> exit 0 - `cargo clippy --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd --all-targets -- -D warnings` -> exit 0 - `cargo test --locked -p sozu-lib` -> exit 0, 1234 passed (includes `a_tree_lookup_allocates_nothing_past_its_route_result` and `a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id`) - `cargo test --locked -p sozu` -> exit 0, 226 passed; `-p sozu-command-lib` -> exit 0, 193 passed - `cargo test --locked -p sozu-e2e -- --skip tests::fuzz_tests::` -> exit 0, 449 passed - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0; same flags `cargo clippy -p sozu-sim --all-targets -- -D warnings` -> exit 0 - `check_doc_citations.py`: `--self-test` 0, broken fixture 1 with its report, `--base origin/main` 0, plain 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0 Closes #1595 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.
Closes #1589
What
#1584 left three heap allocations per routed request inside
Router::route_from_request. This removes the two that need no public type change. The third, the cluster id cloned out of the route table, needsClusterId = Stringchanged in sozu-command-lib and is out of scope, as isSessionManager::track_cluster_connection.original_authority.route_from_requestcopied the authority (host.to_owned()) intoHttpContext::original_authorityon every request. Its only reader is theX-Forwarded-Hostinjection inapply_request_rewrites_and_headers, which runs only when the frontend rewrites the host. Routing never mutatesHttpContext::authority: the rewrite changes only the kawa status line and headers. So the helper now copiescontext.authorityitself, only on a host rewrite, and moves that copy intooriginal_authority. On the rewrite path this is one copy fewer than before, two instead of three.trie_path.Router::lookupgave the trie aVec::with_capacity(16)to record the wildcard and regex segments it matched. It allocated this even for a literal host, which records nothing.lookup_recursivewas already generic over itsSubMatchSink, so a crate-privateInlineTrieMatchesimplements that trait. It keeps the first 16 segments in a fixed array on the stack and spills to aVeconly past them.RouteResult::new_with_trieborrows the segments from it, so$HOST[n]templates see every segment in the same walk order.TrieMatchesandTrieNode::lookup_with_pathare unchanged. No new dependency and nounsafe.Observable difference
The field type is unchanged, but the value of one
pubfield changes.HttpContext::original_authorityis nowNoneon a request without a host rewrite, where it used to beSome(authority). Its own documentation already said "Nonewhen no host rewrite happened". Nothing else in the tree reads it: no access log, audit record or redirect reads it. On a host rewrite it is still set, andX-Forwarded-Hoststill carries the authority the client sent.Prior art: HAProxy (at
0ceb8c65)src/pattern.c:151:static THREAD_LOCAL struct pattern static_pattern;A map or ACL match returns its result through a per-thread buffer that is reused, never allocated (filled atsrc/pattern.c:516-520).src/pattern.c:507:ebst_lookup(&expr->pattern_tree, smp->data.u.str.area)walks the ebtree on the sample's own bytes, in place.src/pattern.c:683andsrc/pattern.c:991(ebmb_lookup_longest) do the same.src/sample.c:3487andsrc/regex.c:24useregmatch_t pmatch[MAX_MATCH], a fixed array for regex captures.src/regex.c:155-156clamps the match count atMAX_MATCH.InlineTrieMatchesuses the same fixed array but spills instead of clamping, so no segment is dropped and routing semantics stay the same.Measurements
The counts come from the crate's counting allocator (
crate::test_allocations); this change adds no#[global_allocator].route_from_request, per request, reused keep-alive backenda_routed_request_on_a_reused_backend_connection_copies_no_cluster_id: its control used to run all ofroute_from_request. It now counts only the cluster idto_owned()and the debug-onlyDebugEvent::Strpush, so the rest of routing is measured. It is red before the fix (left: 128, right: 0). It turns red again, at 64, if either site is reintroduced on its own.a_tree_lookup_allocates_nothing_past_its_route_result:Router::lookupon a literal, a wildcard and a regex host allocates exactly whatRouteResult::forwardof the cluster id allocates. It is red with the oldVec::with_capacity(16)(left: 4, right: 3).a_host_capture_past_sixteen_trie_segments_keeps_every_segment: a 20-segment regex host, rewritten through$HOST[1]…$HOST[20]. It pins today's tree order. It is red if the spilled entries are dropped.inline_trie_matches_rewinds_across_the_spill_like_a_vec: pushes and rewinds across the inline/spill boundary give the same record as aVec.only_a_host_rewrite_records_the_original_authority: with a host rewrite,original_authorityandX-Forwarded-Hostcarry the client's authority. Without one, both are absent. It is red with the old unconditional copy.A pre-existing quirk, unchanged here: a tree rule numbers its regex-segment captures right to left, in trie walk order, while a pre/post rule reads the whole-host regex left to right. The 20-segment test pins the current tree order, and this PR does not change it.
Verification
cargo build --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd, thencargo +nightly fmt --all -- --check, then clippy with the same features and--all-targets -- -D warningscargo test -p sozu-lib/-p sozu/-p sozu-command-lib, andcargo test -p sozu-e2e -- --skip tests::fuzz_tests::(449 passed)RUSTFLAGS="--cfg tokio_unstable"check_doc_citations.py--self-test,--root .,--base e49d78ab…and--audit --root .. One citation indoc/testing.mdmoved withroute_from_request; it is re-anchored to the samesni: sni.to_owned(),line in the same function.RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedCHANGELOG.mdanddoc/testing.mdare updated in the same commit.Signed-off-by: Florentin Dubois [email protected]