Skip to content

fix(h1): read an answer template's Connection value as an option list - #1705

Merged
FlorentinDUBOIS merged 1 commit into
mainfrom
fix/answers-connection-options
Sep 30, 2026
Merged

FlorentinDUBOIS merged 1 commit into
mainfrom
fix/answers-connection-options

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

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 whole Connection value with close (compare_no_case(val_data, b"close")). An operator template carrying Connection: keep-alive, close or Connection: close, x-custom was 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, made pub(crate); no duplication), the case-insensitive, trimmed, comma-list matcher the request and response paths already use (RFC 9110 §7.6.1). Each Connection line is still examined, so a close on any line closes. Connection: closed does not close.

Protocol impact

  • H1 frontend keep-alive decision after a rendered default answer (keep_alive returned by HttpAnswers::get / redirect templates, consumed in mux::answers::set_default_answer), for operator-written templates with a list-valued Connection.
  • No wire-byte change: the template bytes are emitted as written.
  • The 14 built-in templates and the fallback all carry a lone Connection: close and behave identically.

Sweep

The only whole-value Connection compare on the answer paths was the one in Template::new. lib/src/protocol/mux/answers.rs only consumes the template's keep_alive flag and pushes a literal Connection: close in terminate_default_answer (no compare); mux/converter.rs likewise pushes, and the pkawa.rs hits 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 ,CLOSE must close; closed, keep-alive, x-close, clo se must not; a close on a second Connection line 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):

test protocol::kawa_h1::answers::tests::a_template_listing_the_close_option_closes_the_connection ... FAILED
test protocol::kawa_h1::answers::tests::every_built_in_template_closes_the_connection ... ok
thread 'protocol::kawa_h1::answers::tests::a_template_listing_the_close_option_closes_the_connection' panicked at lib/src/protocol/kawa_h1/answers.rs:1935:13:
`Connection: keep-alive, close` lists the close option and must close
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 1381 filtered out; finished in 0.00s

GREEN (after the fix):

test protocol::kawa_h1::answers::tests::a_template_listing_the_close_option_closes_the_connection ... ok
test protocol::kawa_h1::answers::tests::every_built_in_template_closes_the_connection ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 1381 filtered out; finished in 0.05s

Docs

  • doc/configure.md: template Connection handling reads the value as an option list.
  • CHANGELOG.md (Unreleased, Fixed).
  • Template::keep_alive field doc.

Validation (each checked by its own exit code)

Command Exit
cargo build --all-features 0
cargo +stable clippy --all-features --all-targets --locked -- -D warnings 0
cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings 0
cargo +nightly fmt --all -- --check 0
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked 0
cargo test -p sozu-lib (1383 passed) 0
cargo test -p sozu 0
cargo test -p sozu-e2e -- answer default_answer custom_answer (5 passed) 0
cd fuzz && cargo +nightly fuzz build 0
python3 .github/scripts/check_doc_citations.py 0
python3 .github/scripts/check_doc_citations.py --base origin/main 0
python3 .github/scripts/check_doc_citations.py --self-test 0
python3 .github/scripts/check_doc_citations.py --root .github/scripts/testdata/citations 1 (expected, reports do not resolve)

`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
FlorentinDUBOIS merged commit 4918ad4 into main Sep 30, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the fix/answers-connection-options branch September 30, 2026 00: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]>
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.

h1: answer templates compare the Connection value as a whole

1 participant