Repository navigation
fix(h1): read an answer template's Connection value as an option list - #1705
Merged
Merged
Conversation
`Template::new` compared the whole `Connection` value with `close`, so an operator template carrying `Connection: keep-alive, close` or `Connection: close, x-custom` was not recognised as closing and the frontend connection stayed open after the answer. Match the `close` option with `has_connection_option`, now `pub(crate)`, the case-insensitive comma-list matcher the request and response paths already use (RFC 9110 §7.6.1). `Connection: closed` still does not close, and the built-in templates behave as before. Closes #1702 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 29, 2026 23:03
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 30, 2026
Refs #1684. This is the third PR of the sequence the maintainer set in #1684 (comment): G2 = (a), the UDP shape with reservation at selection. It is based on `origin/main` `4918ad4f`, which includes #1698 (G1), #1700 (G3), #1704 and #1705. ## Design - **Selection reserves.** - `BackendMap::reserve_backend(cluster, now)` and `reserve_sticky_backend(cluster, cookie, now)` choose a backend, then raise its `active_connections` by one (`Backend::reserve_connection`). The raise happens under the same borrow as the choice. - The next selection weighs that reservation exactly as it weighed the count `Backend::try_connect` took at the dial. - Nothing connects during selection. - The empty and no-candidate handling that `backend_from_cluster_id` had moved into a private `BackendMap::select_backend`, which both paths share. - **The embedder dials.** - The router's seam returns a backend and no socket. - `Mux::dial_backend` connects to `BackendId::address` after the selection borrow is released. The address travels inside `BackendId`, which is the `(BackendId, SocketAddr)` shape the maintainer asked for. - **A failed dial releases, through the ledger.** - A `connect(2)` error pushes the new `BackendChange::DialFailed(Instant)` and returns `BackendError::ConnectionFailures`. - Applying `DialFailed` calls `Backend::release_failed_dial`, which does `dec_connections`, `failures += 1` and `retry_policy.fail(at, rng)`. - `BackendRegistry::apply_all` now takes the worker's `&RefCell<BackendMap>`. It borrows it only in the `DialFailed` arm, to draw the backoff jitter from the map's generator; every other change leaves the map alone. - The existing drain before each `Router::plan_connect` applies the release before the next selection reads the counters. The backend then sits exactly where a failed `Backend::try_connect` left it. - **A successful dial keeps the reservation** as its connection's count. `ConnectionClosed` releases it, as before. - **A factory `sim/` can reach:** `pub fn BackendId::new(slot, backend_id, address)`. - A slot means something only to the registry that issued it; the mux still mints through `BackendRegistry::id_for`. - A selector holds no socket, so a simulator implements one without `mio`. `git grep -q mio -- sim/Cargo.toml` still exits 1. - **LIFECYCLE §9, invariant 14** gains the bullet "Selection reserves, failure releases". The "Drain before any read" bullet drops its argument for selecting and dialling in one call. - **Unchanged:** the TCP proxy (`tcp.rs`) still calls `BackendMap::backend_from_cluster_id` and `Backend::try_connect`. ### Renames, for #1706 (#524, `feat/lb-affinity-key-l7-tcp`) #1706 adds an affinity `key` to `select_and_dial` and `backend_from_cluster_id`. Whichever PR merges second rebases onto the other: - `router::BackendDialer` → `router::BackendSelector` - `BackendDialer::select_and_dial` → `BackendSelector::select`, same `(cluster_id, affinity)` parameters - `router::DialedBackend` → `router::SelectedBackend`, which drops its `socket` field - crate-private `RegistryDialer` → `RegistrySelector` - `Router::backend_from_request` now returns `BackendId`, where it returned `(TcpStream, BackendId)` `BackendMap::backend_from_cluster_id` keeps its signature. The mux now calls the new `reserve_backend` and `reserve_sticky_backend`, so #1706's `key` belongs on those as well. ### Pre-existing `active_connections` leak, not fixed here Three exits of `Mux::dial_backend` after a successful `connect(2)` drop the new connection without releasing its connection count: 1. `Connection::new_h2_client` returning `None`, when the buffer pool is exhausted (`BackendConnectionError::MaxBuffers`). 2. A refused `Connection::start_stream`, when the backend's maximum concurrent streams is reached. 3. The `register_socket` rollback. It releases the `active_requests` charge and the gauges, but not `active_connections`. On `main` each of these already leaked the `+1` that `Backend::try_connect` took on success. Now each leaks the reservation, which is the same `+1` taken earlier. **This change does not make it worse:** on each of these paths the count is the same before and after. So I did not fix it here, and LIFECYCLE §9 names the three exits. **Proposed follow-up:** push `BackendChange::ConnectionClosed` for the reserved slot on all three exits, the same release a closing connection emits. Pin it with one test per exit, asserting `active_connections == 0` after the drain. ### Behaviour - A successful dial behaves the same. - A failed synchronous dial leaves the same end state (`active_connections`, `failures`, backoff), applied at the next drain. - The AllDown → Available availability event now fires after a successful selection rather than after a successful connect. - The pinned pick sequences (`backend_selection_pick_sequences_are_pinned`) are unchanged. ## Measurements Measured with a throwaway probe (`size_of`, plus `test_allocations::allocations()` around `Mux::dial_backend`), not committed. | | before (`080351ba`) | after | |---|---|---| | heap allocations per `Mux::dial_backend`, selection to linked stream (3 runs) | 6, 6, 6 | 6, 6, 6 | | steady-state selection (`backend_selection_allocates_nothing_in_steady_state`) | 0 | 0 | | router stamping (`stamping_a_dialled_backend_allocates_nothing`) | 0 | 0 | | `size_of::<BackendChange>()` / `BackendDelta` | 16 / 24 B | 16 / 24 B (`Instant` fits the niche) | | `Backend` / `BackendList` / `BackendMap` / `MuxClear` | 208 / 72 / 472 / 4984 B | unchanged | No new allocation, syscall or dynamic dispatch is added on the dial path. - The `connect(2)` moved from `Backend::try_connect` to `Mux::dial_backend`; it is the same single syscall. - The `BackendMap` borrow happens only on a failed dial. ## Tests: red, then green For each mutation below, I changed the production code, quoted the failing assertion, then restored it. All pass green afterwards. - **Mutation:** `Backend::reserve_connection` returns `Ok(())` without `inc_connections`. - `a_second_selection_observes_the_first_selections_reservation`: `the second selection landed on the first one's backend: the first selection did not reserve its connection (first=backend-a active=0, second=backend-a active=0)` - `power_of_two_weighs_every_reservation`: `2 selections must hold 2 reservations, got [0, 0]` - `a_failed_dial_releases_its_reservation_and_records_the_failure`: `selection reserves`, `left: 0 right: 1` - **Mutation:** `release_failed_dial` without `dec_connections`. - `a_failed_dial_releases_its_reservation_and_records_the_failure` and `a_synchronously_failed_dial_releases_its_reservation` both fail with `a failed dial must release exactly its one reservation (saturating at 0)`, `left: 1 right: 0` - **Mutation:** `Mux::dial_backend` returns the connect error without pushing `DialFailed`. - `a_synchronously_failed_dial_releases_its_reservation`: `the failed dial must release the reservation selection took`, `left: 1 right: 0` - **Mutation:** an extra `inc_connections` after a successful connect. - `a_successful_dial_counts_its_connection_once`: `one dial must hold exactly one connection on its backend`, `left: 2 right: 1` Notes on the new and changed tests: - `a_second_selection_observes_the_first_selections_reservation` replaces `a_second_selection_observes_the_first_dials_connection`. It now selects twice with no dial and no drain in between. A `RENAMED_TESTS` entry keeps the #1550 CHANGELOG citation resolving. - `a_synchronously_failed_dial_releases_its_reservation` dials `255.255.255.255:80`, which fails before any packet leaves (`ENETUNREACH`, or `EACCES` with a default route). It asserts the `Err`, so a host where that connect succeeds fails the test instead of passing it. - `invariant_14_*` in `h2.rs`: all 6 pass, and every assertion is unchanged. Only two things changed: - their `reconcile` helper gains an `unreachable!` arm for `DialFailed`, since no invariant-14 scenario dials; - two `registry.apply(delta)` calls now pass a local `BackendMap`. - `stamping_a_dialled_backend_allocates_nothing` now uses a socket-free `StubSelector` whose id comes from `BackendId::new`. That is the shape a simulator will use. ## Docs - `lib/src/protocol/mux/LIFECYCLE.md`: §3.2 and §9 invariant 14. - `router.rs`: the `BackendSelector` doc, rewritten. The old doc argued that selection and dial had to be one call; it now describes reservation and release. - `doc/lifetime_of_a_session.md` and `doc/benchmark.md`: the dial path. - `doc/rate-limit-design.md` and `lib/src/server.rs`: they now say where the non-blocking dial lives, `Mux::dial_backend` for HTTP and `Backend::try_connect` for TCP. - `e2e/src/tests/tests.rs`: a TO SEE THIS RED note now points at the dial's new site and says its measurement was taken at the old one. - `doc/testing.md` §5: how a simulator's selector mints ids, and the reservation rule it must keep. - `CHANGELOG.md`: a BREAKING (library API) entry, listing the renames. ## Validation Run on head `208ed9eb`, rebased onto `4918ad4f`. Each exit code was checked directly, never through a pipe: - `cargo +nightly fmt --all -- --check` -> exit 0 - `cargo clippy --all-targets --locked -- -D warnings` -> exit 0 - `cargo clippy --all-targets --all-features --locked -- -D warnings` -> exit 0 - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings` -> exit 0 - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0 - `cargo test --workspace --locked --exclude sozu-e2e` -> exit 0 (1865 passed, 0 failed, 17 ignored, all ignores already on main) - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0 (31 passed) - `cargo test -p sozu-e2e --locked -- --skip tests::fuzz_tests::` -> exit 0 (515 passed) - `cd fuzz && cargo +nightly fuzz build` -> exit 0 - `python3 .github/scripts/check_doc_citations.py` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --base origin/main` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --self-test` -> exit 0 - `python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations` -> exit 1 (the broken fixture must fail) 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 #1702
What
Template::new(lib/src/protocol/kawa_h1/answers.rs) decided whether a parsed answer template closes the frontend connection by comparing the wholeConnectionvalue withclose(compare_no_case(val_data, b"close")). An operator template carryingConnection: keep-alive, closeorConnection: close, x-customwas therefore not recognised as closing, and the session kept the client connection open after an answer whose framing may rely on the close.It now uses
has_connection_option(lib/src/protocol/kawa_h1/editor.rs, madepub(crate); no duplication), the case-insensitive, trimmed, comma-list matcher the request and response paths already use (RFC 9110 §7.6.1). EachConnectionline is still examined, so acloseon any line closes.Connection: closeddoes not close.Protocol impact
keep_alivereturned byHttpAnswers::get/ redirect templates, consumed inmux::answers::set_default_answer), for operator-written templates with a list-valuedConnection.Connection: closeand behave identically.Sweep
The only whole-value
Connectioncompare on the answer paths was the one inTemplate::new.lib/src/protocol/mux/answers.rsonly consumes the template'skeep_aliveflag and pushes a literalConnection: closeinterminate_default_answer(no compare);mux/converter.rslikewise pushes, and thepkawa.rshits are header-name compares.Tests
a_template_listing_the_close_option_closes_the_connection(new):close,Close,keep-alive, close,close, x-custom,x-custom ,CLOSEmust close;closed,keep-alive,x-close,clo semust not; acloseon a secondConnectionline must close.every_built_in_template_closes_the_connection(new): behaviour guard that every built-in template and the fallback close the connection. It passed both before and after the fix by design (built-ins must behave identically), so it is not a red/green test.RED (before the fix):
GREEN (after the fix):
Docs
doc/configure.md: templateConnectionhandling reads the value as an option list.CHANGELOG.md(Unreleased, Fixed).Template::keep_alivefield doc.Validation (each checked by its own exit code)
cargo build --all-featurescargo +stable clippy --all-features --all-targets --locked -- -D warningscargo +1.93.1 clippy --all-features --all-targets --locked -- -D warningscargo +nightly fmt --all -- --checkRUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --lockedcargo test -p sozu-lib(1383 passed)cargo test -p sozucargo test -p sozu-e2e -- answer default_answer custom_answer(5 passed)cd fuzz && cargo +nightly fuzz buildpython3 .github/scripts/check_doc_citations.pypython3 .github/scripts/check_doc_citations.py --base origin/mainpython3 .github/scripts/check_doc_citations.py --self-testpython3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citationsdo not resolve)