Skip to content

perf(router): copy no authority and allocate no trie path per request - #1594

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
perf/route-lookup-no-alloc
Sep 26, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
perf/route-lookup-no-alloc

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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, needs ClusterId = String changed in sozu-command-lib and is out of scope, as is SessionManager::track_cluster_connection.

original_authority. route_from_request copied the authority (host.to_owned()) into HttpContext::original_authority on every request. Its only reader is the X-Forwarded-Host injection in apply_request_rewrites_and_headers, which runs only when the frontend rewrites the host. Routing never mutates HttpContext::authority: the rewrite changes only the kawa status line and headers. So the helper now copies context.authority itself, only on a host rewrite, and moves that copy into original_authority. On the rewrite path this is one copy fewer than before, two instead of three.

trie_path. Router::lookup gave the trie a Vec::with_capacity(16) to record the wildcard and regex segments it matched. It allocated this even for a literal host, which records nothing. lookup_recursive was already generic over its SubMatchSink, so a crate-private InlineTrieMatches implements that trait. It keeps the first 16 segments in a fixed array on the stack and spills to a Vec only past them. RouteResult::new_with_trie borrows the segments from it, so $HOST[n] templates see every segment in the same walk order. TrieMatches and TrieNode::lookup_with_path are unchanged. No new dependency and no unsafe.

Observable difference

The field type is unchanged, but the value of one pub field changes. HttpContext::original_authority is now None on a request without a host rewrite, where it used to be Some(authority). Its own documentation already said "None when 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, and X-Forwarded-Host still 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 at src/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:683 and src/pattern.c:991 (ebmb_lookup_longest) do the same.
  • src/sample.c:3487 and src/regex.c:24 use regmatch_t pmatch[MAX_MATCH], a fixed array for regex captures. src/regex.c:155-156 clamps the match count at MAX_MATCH. InlineTrieMatches uses 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 backend before after
debug test build, compared with the control +2 (128 over 64 requests, both ungated and gated) 0
release build 3 (as measured in #1583) 1, the cluster id clone
  • a_routed_request_on_a_reused_backend_connection_copies_no_cluster_id: its control used to run all of route_from_request. It now counts only the cluster id to_owned() and the debug-only DebugEvent::Str push, 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::lookup on a literal, a wildcard and a regex host allocates exactly what RouteResult::forward of the cluster id allocates. It is red with the old Vec::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 a Vec.
  • only_a_host_rewrite_records_the_original_authority: with a host rewrite, original_authority and X-Forwarded-Host carry 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, then cargo +nightly fmt --all -- --check, then clippy with the same features and --all-targets -- -D warnings
  • cargo test -p sozu-lib / -p sozu / -p sozu-command-lib, and cargo test -p sozu-e2e -- --skip tests::fuzz_tests:: (449 passed)
  • the sim test and sim clippy under RUSTFLAGS="--cfg tokio_unstable"
  • check_doc_citations.py --self-test, --root ., --base e49d78ab… and --audit --root .. One citation in doc/testing.md moved with route_from_request; it is re-anchored to the same sni: sni.to_owned(), line in the same function.
  • RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked

CHANGELOG.md and doc/testing.md are updated in the same commit.

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

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
FlorentinDUBOIS merged commit bbceca8 into main Sep 26, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/route-lookup-no-alloc branch September 26, 2026 21:09
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]>
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.

perf(router): route_from_request still allocates for original_authority and the trie path

1 participant