Repository navigation
fix(mux): end a Content-Length response truncated by a backend close in error - #1640
Merged
Merged
Conversation
FlorentinDUBOIS
requested review from
Wonshtrum and
llenotre
as code owners
September 28, 2026 00:54
FlorentinDUBOIS
force-pushed
the
fix/truncated-content-length
branch
2 times, most recently
from
September 28, 2026 03:24
046092d to
32b7990
Compare
…in error A `Connection: close` H1 backend that closed before its announced `Content-Length` had its body ended as if complete: END_STREAM to an H2 client (RFC 9113 §8.1.1: malformed), and to an H1 client the short body, `H1::Complete` in the access log and a keep-alive wait. - `ConnectionH1::terminate_close_delimited` (`lib/src/protocol/mux/h1.rs`) and the `EndStreamAction::CloseDelimited` arm of `ConnectionH2::end_stream` (`lib/src/protocol/mux/h2.rs`) now treat a `Content-Length` body still expecting bytes like a chunked body without its zero chunk (RFC 9112 §6.3 rule 5, §7.1): `warn!`, `h1.backend_eof_before_message_complete`, Error phase. Only a body with neither framing ends cleanly at the close (rule 8). - `end_stream_decision` (`lib/src/protocol/mux/shared.rs`) answers `ForwardUnterminated` for a response in the Error phase whose kawa is already `consumed`. It used to answer `SendDefault(502)`, which wrote a 502 behind the bytes already sent: into the body of the 200 for an H1 client, as DATA with END_STREAM on the same stream for an H2 client. That also broke the existing chunked fix behind a `Connection: close` backend. Before any byte left, the clean 502 stands. - `ConnectionH1::writable` closes an H1 client connection once an errored response is flushed (`defer_close_for_tls_flush`, write-only shutdown), never keeping it alive: the client sees a close before `Content-Length`, and no pipelined response can follow. This also ends the hang, until the frontend timeout, of an H1 client whose keep-alive backend died mid-body. Closes #1633 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
fix/truncated-content-length
branch
from
September 28, 2026 03:50
32b7990 to
688cc25
Compare
This was referenced Sep 28, 2026
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…1645) ## What During a soft stop, `Server::shut_down_sessions` calls `shutting_down()` on every draining session at each 100 ms tick. For an H2 frontend, `Mux::drive_frontend_shutdown_io` forces one `writable()` pass, then kept looping until the WRITABLE **event** bit cleared. The forced pass sets that bit itself (`signal_pending_write`), and `writable()` clears it only on `WouldBlock`. For an idle draining session with a writable socket, the bit never cleared, so every tick ran all `MAX_LOOP_ITERATIONS` (10 000) empty `writable()` calls, for every draining H2 session. The loop now stops as soon as nothing is queued (`has_pending_write()`) or the socket blocks. The forced first pass is unchanged. The loop's exit condition dates from 28c6807. ## Evidence **Locating it.** No sampling profiler could run on this workstation: `perf` is absent, and samply needs `perf_event_paranoid <= 1` where it is 2, with no root. I bisected with thread CPU time (`CLOCK_THREAD_CPUTIME_ID`) instead, using temporary instrumentation that is not part of this PR. It showed that `shut_down_sessions()` accounts for the whole drain-pass cost. A per-call counter in the write loop then printed, for all 50 calls on the e2e drain test: ``` DBGDRIVE iterations=10000 cpu=29.49ms (median) has_pending_write=false event_writable=true ``` **Before/after.** Thread CPU time of one `shut_down_sessions()` call on `test_h2_continuation_survives_a_graceful_drain_mid_reassembly`, run alone in an isolated network namespace, 3 runs per cell: | build | before, median per pass | after, median per pass | total over 3 runs | |---|---|---|---| | release | 3.94 ms | 7 µs (5 µs, re-measured on `51547b63`) | 397 ms → 1.3 ms | | debug | 79.5 ms | 116 µs | 5.55 s → 15 ms | So the cost is real in release builds. It is paid per draining session and per tick, and every other event on the worker waits behind it: 100 draining sessions cost about 400 ms of CPU per 100 ms tick. **Test seen red.** `mux::tests::an_idle_draining_h2_session_makes_one_writable_pass_per_shutdown_tick` builds an idle draining H2 `Mux` with a live stream and budget left, runs one `shutting_down()` pass, and counts `writable()` calls through a `cfg(test)` thread-local counter. With the old exit condition restored: ``` assertion `left == right` failed: one shutdown pass on an idle draining H2 session must make exactly the one forced writable() call, not spin until MAX_LOOP_ITERATIONS (10000); got 10000 ``` ## Effect on #1623 (budget untouched) #1623's command, `taskset -c 0 sozu_e2e h2 --skip tests::fuzz_tests:: --test-threads=20`, 10 runs per tree, each in an isolated network namespace. `h2_graceful_shutdown_deadline_seconds` keeps its 5 s default, and the test is unchanged. | test | `main` @ `3a79685e` | this PR @ `1c4b4fbe` | |---|---|---| | `test_h2_continuation_survives_a_graceful_drain_mid_reassembly` (#1623) | **failed 10/10** | **failed 0/10** | | `test_h2_graceful_shutdown_completes_large_transfer` | failed 10/10 | failed 3/10 | | `e2e_h2_flow_per_stream_idle_timeout` | failed 7/10 | failed 2/10 | | `test_h1_to_h2_basic_request` | failed 6/10 | failed 2/10 | | `test_rewrite_path_h1_h2` | failed 5/10 | failed 1/10 | | `test_h1_to_h2_backend_smoke` | failed 4/10 | failed 2/10 | | `test_h2_goaway_graceful_drain` | failed 3/10 | failed 0/10 | | `test_h2_graceful_shutdown_deadline_configurable_short` | failed 2/10 | failed 0/10 | | `test_h2_flood_threshold_live_patch` | failed 0/10 | failed 1/10 | | `test_h2_settings_ack_timeout_goaways_the_frontend` (#1624) | failed 10/10 | failed 8/10 | After rebasing onto `85f0ae33`, two more runs of the same command on `51547b63` passed the whole suite both times (249/249). After rebasing onto `96b4bca9` (#1640), one more run on `f6a6e6a7`: 254/254. The single `test_h2_flood_threshold_live_patch` failure noted below was checked in review: that test passes 10/10 on both the base and this branch, so it is not a regression. The two series ran one after the other, under the same ambient machine load. `test_h2_settings_ack_timeout_goaways_the_frontend` is a separate test bug (its handshake runs under a 100 ms poll timeout), fixed by #1636, which was not yet on this branch for the 10-run series. `test_h2_flood_threshold_live_patch` failed once in these 10 runs; review then ran it 10/10 green on both trees. ## Review question: does an RFC 9218 yield now drain once per tick? (not reproduced) The concern: on an incremental same-urgency yield, `finalize_write` returns `RetainPendingBack` (invariant 16) without setting `expect_write`, so `has_pending_write()` is false and the new loop stops after one pass, where the old one kept going. Reading the code, the state should not be stranded. `ready()`'s inner loop continues while `frontend.readiness().filter_interest()` is non-empty, and `RetainPendingBack` keeps both `interest` and the `signal_pending_write` event bit. So `ready()` resumes the retained writes itself before it returns, and a drain pass starts with no retained work. This is an inference from the code; the recipe below tests it. Recipe (temporary e2e, not committed): two streams `u=3, i` on one connection, 1 MiB bodies (64 DATA frames each), isolated namespace, default 5 s drain budget. Three runs per tree. | variant | old loop | this PR | |---|---|---| | stream windows at 16 KiB, soft stop lands while both are flow-blocked, then WINDOW_UPDATE on the connection and both streams | **truncated**: 290 to 481 KiB of 1 MiB delivered, cut at 4.65 to 4.98 s | full 1 MiB on both, in 90 to 126 ms | | windows open, client stops reading so the socket blocks, soft stop, client resumes reading | full, 38 to 50 ms | full, 37 to 48 ms | So in the scenario that concern describes, the old loop is the one that fails to drain, and this change fixes it. ## Docs The added lines shift `lib/src/protocol/mux/mod.rs`, which drifts 16 numeric citations (15 in `LIFECYCLE.md`, 1 in `doc/testing.md`). Each is replaced by the symbol its prose already names (`Mux::ready_inner`, `Mux::timeout_inner`, `Mux::shutting_down_inner`), so they no longer move with the line numbers. `check_doc_citations.py --base origin/main` passes. CHANGELOG entry under Fixed. ## Validation - `cargo build --locked`, `cargo clippy --all-targets --locked -- -D warnings`, `cargo +nightly fmt --all -- --check`: ok - `cargo test --workspace --lib --locked --exclude sozu-e2e`: ok (113 + 184 + 1299) - `check_doc_citations.py`: `--self-test` exit 0; broken fixture exit 1 with the failure report; `--base origin/main` exit 0; plain run exit 0 - `sozu_e2e h2_ --skip tests::fuzz_tests::` on `f6a6e6a7` (isolated namespace): 246 passed - The e2e H2 suite under contention: covered by the 10 runs above. Across those runs, every failure on this branch is in a test that also fails on `main`. Closes #1623 Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…#1638) Closes #1631 ## Problem On a backend H2 connection (`Position::Client`), `ConnectionH2::start_stream` allocates the stream id and registers it as soon as the router links a request, but the HEADERS leave with a later write pass. When the frontend gives up in between (client RST_STREAM or disconnect, stream idle timeout, backend timeout), `ConnectionH2::end_stream` and `ConnectionH2::cancel_timed_out_streams` queued `RST_STREAM(CANCEL)` for a stream the backend had never seen: | Backend connection state | What the backend received (reproduced on `d5161919`) | |---|---| | `Header`, HEADERS not written (or encoded and parked unsent) | `RST_STREAM(1)` on an idle stream: RFC 9113 §5.1/§6.4 connection error | | `ClientPreface` (TCP connect in progress) | `RST_STREAM(1)` **before** `PRI * HTTP/2.0` (§3.4) | | `ServerSettings` (preface out, server SETTINGS not read) | sozu itself force-disconnects: `Unexpected combination: (Writable, ServerSettings, Client)` | `Router::connect` multiplexes the streams of several clients on one backend connection, including one still `Connecting`, so one cancelled request took all of them down. While reproducing the third row I found it does not need `end_stream`: `start_stream` alone arms WRITABLE, and a backend connection is `Connected` from its first writable, before its preface is written, so the router links onto it during the handshake window and the next writable force-disconnects it (`a_request_linked_during_the_handshake_goes_out_after_the_settings` is red on `d5161919` with no `end_stream` at all). ## Fix - `Position::Client` arm of `ConnectionH2::end_stream`: RST only if `stream.front.consumed` (on this position exactly "a request byte reached this socket"; a stream's first frame is its HEADERS). A stream the backend never saw is retired with no frame — what hyperium/h2 does for a stream still pending open. HAProxy (`h2_frame_check_vs_state`) and hyperium/h2 (`Recv::ensure_not_idle`) both answer the idle-stream RST with GOAWAY(PROTOCOL_ERROR). - `ConnectionH2::cancel_timed_out_streams`: same guard before `enqueue_rst`. - `H2WritePhase::Prepare` arm of `ConnectionH2::poll_write_target` (found by the adversarial review): a request that turned `Error` while its backend stream is registered and its HEADERS never left (an H1 frontend rejecting a malformed chunked body answers 400 itself and leaves the backend stream in place) is no longer handed to the converter, whose `initialize` queued `RST_STREAM(INTERNAL_ERROR)` for the idle stream. It is left for `end_stream` / the idle reaper, which retire it without a frame. Fixed at the emission point rather than in the H1 error arm so every producer of a front `Error` is covered and H1 backends are untouched. - `dispatch_writable_state`: `(ServerSettings, Client)` leaves the `Unexpected combination` arm; it withdraws WRITABLE and continues. The SETTINGS ACK the read queues re-arms it, so a request linked during the handshake goes out after it (RFC 9113 §3.4 even allows sending before the server preface; sozu keeps waiting, which is the smaller change). - `(ClientPreface, Client)` debug-asserts that nothing is queued ahead of the preface. - **R1 (pre-existing, same arm family, requested in review):** `ConnectionH1::readable`, `Position::Server` parse-error arm — when the response already started (`back.consumed`), it is cut with `forcefully_terminate_answer` and the connection closes for writing (`defer_close_for_tls_flush`) instead of a complete `HTTP/1.1 400` being spliced into the streamed body; before any response byte the 400 is kept. - TigerStyle post-conditions: no frame queued for a never-opened stream (`end_stream`, `cancel_timed_out_streams`), the wire id is retired, WRITABLE withdrawn / READABLE kept while awaiting SETTINGS. **Stream ids (RFC 9113 §5.1.1).** The burnt id is not reused; the next HEADERS on a higher id closes it implicitly on the backend, which is harmless since it never processed it. Order is preserved: a write pass resumes a parked stream first and otherwise prepares client streams in ascending id (default urgency), so a lower id never gets its HEADERS after a higher one because of this change. **HPACK:** a HEADERS block encoded and parked unsent (#1627 situation on `Position::Client`) is dropped with the stream, and #1630's `parked_header_block` resets the encoder table on the next pass — `a_backend_stream_ended_with_its_headers_parked_is_not_reset` checks the next stream's block decodes on the backend. Nominal path: one `bool` read per retired backend stream, no allocation. ## Tests (red → green) All in `lib/src/protocol/mux/h2.rs`; red obtained by applying only the test changes onto the `d5161919` source (the first six) and the `6eef0ba1` source (the last). - `a_backend_stream_ended_before_its_headers_left_is_not_reset`: red `left: [0, 0, 4, 3, 0, 0, 0, 0, 1, 0, 0, 0, 8], right: []` - `a_backend_stream_ended_before_the_preface_leaves_the_preface_first`: red `the connection preface must come first, got [0, 0, 4, 3, 0, 0, 0, 0, 1, 0, 0, 0, 8, 80, 82, 73, ...]` - `a_backend_stream_ended_during_the_handshake_keeps_the_connection`: red `the shared connection must survive the handshake, got Error` - `a_request_linked_during_the_handshake_goes_out_after_the_settings` (liveness of the withdrawn readiness): red `premise: nothing is written before the server SETTINGS, got [] in Error` - `a_backend_stream_reaped_before_its_headers_left_is_not_reset`: red `a stream reaped before its HEADERS left must not be reset` - `a_backend_stream_ended_with_its_headers_parked_is_not_reset` (paced socket, 0-byte first write): red `no frame may name stream 1, which the backend never saw: [(3, 0, 1, [0, 0, 0, 8]), (1, 5, 3, ...)]` - `a_backend_stream_whose_request_failed_before_its_headers_left_is_not_reset` (reviewer's scenario): red on `6eef0ba1` `no frame may name stream 1, which the backend never saw: [(3, 0, 1, [0, 0, 0, 2])]` - `h1::tests::a_request_error_after_the_response_started_cuts_it_instead_of_splicing_a_400` (R1): red with the new arm removed, `no 400 may follow a response already on the wire, got "HTTP/1.1 400 Bad Request\r\n..."` - `end_stream_on_a_backend_mid_data_payload_sends_its_rst_before_reading_on`: fixture now sets `front.consumed = true` (the backend is answering, so the request left); it still pins that an opened stream IS reset. ## Commands - `cargo build --locked` -> exit 0; `cargo build --all-features --locked` -> exit 0 - `cargo clippy --all-targets --locked -- -D warnings` -> exit 0 - `cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings` -> exit 0 - `cargo +nightly fmt --all -- --check` -> exit 0 - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8` -> exit 0, 2215 passed, 0 failed - `RUSTFLAGS="--cfg tokio_unstable" cargo test -p sozu-sim --locked` -> exit 0, 31 passed - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` -> exit 0 - `python3 .github/scripts/check_doc_citations.py` `--self-test`, `--root .`, `--root . --base origin/main`, `--audit --root .` -> all exit 0 ## Docs `LIFECYCLE.md` §2.2 (backend handshake states), §8.2 (never RST a backend stream still idle), §8.4, new invariant 29; `doc/h2_mux_internals.md` new "A backend stream the backend never saw"; CHANGELOG (Fixed, two entries). Line citations shifted by this change re-anchored. ## Coordination Merge order #1640, #1638, #1639. #1639 is rebased after this one and numbers its LIFECYCLE invariant 30. Line citations this diff touches are converted to symbol citations where possible, so the next rebases do not conflict on them. Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
added a commit
that referenced
this pull request
Sep 28, 2026
…n: close (#1648) ## Summary After a response carrying the backend's `Connection: close`, sozu forwarded that header to a keep-alive H1 client but kept the client connection open: `ConnectionH1::writable` (`lib/src/protocol/mux/h1.rs`) decided on `keep_alive_frontend` alone, which only follows the client's request. For a close-delimited body (neither `Content-Length` nor chunked, RFC 9112 §6.3 rule 8) the body can only end with the close, so: - the client waited for more body until the frontend timeout; - with pipelining, the response to the next request was appended to that body. Closes #1642. ## Fix The `Terminated` branch of `ConnectionH1::writable` now keeps the connection only while **both** `keep_alive_frontend` and `keep_alive_backend` hold. Otherwise it takes the existing `response-complete` exit, the one a client `Connection: close` already uses: access log, then `defer_close_for_tls_flush` (write-only shutdown once the response is flushed, never `Shutdown::Both`), RFC 9112 §9.6. A pipelined request already buffered is dropped with the connection and never processed; the client retries it (§9.3.2). `keep_alive_backend == false` covers both cases in the issue: an explicit backend `Connection: close` (forwarded unchanged by `HttpContext::on_response_headers`), and every close-delimited body, because `ConnectionH1::terminate_close_delimited` only runs for such a backend. No new field, no allocation. **Why not in `HttpContext::on_response_headers`:** `HttpContext` also serves H2 frontends, and `ConnectionH2::write_streams` sends GOAWAY when `keep_alive_frontend` is false. Clearing it there would GOAWAY every H2 client behind a `Connection: close` backend after each response. Two new H2 e2e tests go red with that variant (checked locally) and stay green with this fix. **Frontend H2: not affected.** `Connection` never reaches an H2 client (RFC 9113 §8.2.2) and a close-delimited body ends with END_STREAM (`test_h2_close_delimited_body_ends_stream_at_backend_close`, from #1640). The new tests check that the H2 connection then serves another stream. ## Close vs. re-framing as chunked RFC 9112 would let a proxy re-frame the body as chunked and keep the client connection. I chose closing: - **HAProxy** closes too. `h1_set_cli_conn_mode` (`src/mux_h1.c`), response pass: `!(H1_MF_XFER_LEN) || H1_MF_CONN_CLO → H1S_F_WANT_CLO`. Its chunk injection needs `H1_MF_XFER_LEN` (a known length without CL/chunked, e.g. from an H2 backend), so it never re-frames a close-delimited H1 body. HAProxy also strips the server's `Connection` header (`H1_MF_CLEAN_CONN_HDR`), so for a *framed* response with `Connection: close` it keeps the client alive. sozu forwards that header, so it has to close. - **Re-framing cost:** a chunked output path in the kawa converter, a `Transfer-Encoding` injection, eliding `Connection: close`, an HTTP/1.1-client gate, all in the security-sensitive mux. That means more code and more risk for a legacy-backend case. Eliding `Connection: close` on framed responses to keep the client alive, as HAProxy does, could come later as an optimisation. It is not needed for correctness. ## Tests changed on purpose Two existing tests pinned the defect itself: each reused a client connection after sozu had forwarded `Connection: close` to it. - `test_h1_content_length_complete_then_backend_close_stays_alive` (#1640) → `test_h1_content_length_complete_then_backend_close_closes_client`: reads to EOF and requires the full `0123456789` body, then the close. The reuse leg is gone because RFC 9112 §9.6 forbids it. - `test_keep_alive`, leg "front: keep / back: close": now requires the client connection closed (`receive_until_eof` + `!is_connected()`). The next leg reconnects. - `test_h1_close_delimited_body_ends_at_backend_close` → `test_h1_close_delimited_body_closes_client`: its doc said it deliberately did not pin this defect. It now reads to EOF. ## Tests Red on `main` (96b4bca), green here: | Test | Red on main | |---|---| | `test_h1_close_delimited_body_closes_client` | still open after 5 s, `…\r\n\r\nabcd` read | | `test_h1_close_delimited_body_read_with_the_eof_closes_client` (body + EOF in one read) | still open after 5 s | | `test_h1_close_delimited_body_is_not_followed_by_a_pipelined_response` | `abcdHTTP/1.1 200 OK…pong1`: second response glued into the body | | `test_h1_content_length_complete_then_backend_close_closes_client` | still open after 5 s | | `test_keep_alive` | `assert!(!client.is_connected())` | Non-regression (green before and after): - `test_h1_framed_keep_alive_responses_keep_the_client`: a CL response and a chunked response keep the client connection, and a client `Connection: close` still closes it. - `test_h2_close_delimited_body_keeps_the_h2_connection` and `test_h2_content_length_with_connection_close_keeps_the_h2_connection`: no GOAWAY, and stream 3 is answered. No `sleep` added and no timeout raised. Ports come from `port_registry`, and reads use `raw_read_until_eof` / `receive_until_eof`. ## Commands run All on `ef4b6c3a`, exit 0 each: - `cargo build --locked` - `cargo build --all-features --locked` (clang toolchain for `aws_lc_fips` with gcc 16) - `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` - `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked` - `cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8`: 2204 passed, 0 failed, 14 ignored - `check_doc_citations.py`: `--self-test`, broken fixture tree (exit 1 + report as expected), `--base origin/main`, plain ## Docs - `lib/src/protocol/mux/LIFECYCLE.md` §8.4: new paragraph on the H1 close after a clean `Connection: close` response. - `lib/src/protocol/kawa_h1/LIFECYCLE.md` §2: `on_response_headers` bullet. - `CHANGELOG.md`: Fixed. Signed-off-by: Florentin Dubois <[email protected]>
This was referenced Oct 3, 2026
Closed
FlorentinDUBOIS
added a commit
that referenced
this pull request
Oct 3, 2026
…losed (#1820) ## Summary A slow client could get a truncated response, ending in a clean close, when the backend had already written the whole response and closed. Nothing was logged at the default level; the only trace was `http.infinite_loop.error`. This is the intermittent failure of `tls_tests::test_plain_client_half_close_after_request_receives_large_response` (CI run 37019159928, 8,284,694 of 8,388,608 body bytes). **Cause** (`lib/src/protocol/mux/mod.rs` on `main`): - `:3218`: `HUP | ERROR` are always in a backend's interest. A backend that is dead but kept for its buffered bytes (`:3113-3115`, `has_buffer_pressure`) therefore has `filter_interest() == HUP`, so `all_backends_readiness_are_empty` stays false. - When the client's socket would block (or an H2 stream window is exhausted), nothing can progress, and the inner loop runs to `MAX_LOOP_ITERATIONS` within one `ready()` call. - `:3425`/`:3435`: the budget branch only consults the connection-level `has_pending_write()`. That is false for a plain-TCP H1 frontend, and for an H2 connection whose DATA is still in `back.out`. The branch returns `Close`, and the body tail is never sent. Instrumentation at the budget branch, from the unit repro below: frontend `I(RWEH-) R(-----)`, backend `I(R-EH-) R(---H-)` with `has_buffer_pressure == true`, `frontend.has_pending_write() == false`, one block in `back.out`. This matches the readiness that PR #1818 captured in the failing CI-shaped runs. ## Fix - `Connection::has_loop_work`: a backend counts as loop work for READABLE or WRITABLE, or for a HUP or ERROR, unless it is kept for buffered bytes (`has_buffer_pressure`). Only a dead backend waiting for the client to drain the stream buffer stops counting; `try_resume_reading` wakes it. A HUP sozu raises itself mid-pass (`force_disconnect` after an H2 backend protocol error) still brings the loop back to close the backend and answer the client. - `Mux::wait_for_client_at_loop_limit`: reaching the budget logs a `warn!` with the frontend and backend readiness. If output is still queued (connection level, or in an open stream's `back.out`/`back.blocks`), the session keeps WRITABLE interest, drops the stale event, arms the frontend timeout, and waits for the next writable edge. A session with nothing queued is closed, and so is one that reaches the limit again with no byte written to the client since, so a spin that recurs on every wake-up costs at most two budgets. The outer loop no longer re-enters a spent budget. The budget stays as the safety bound. The shared `has_pending_write_including_streams` H1 arm is deliberately left unchanged, because widening it would also change every delayed-close and timeout path. - Corrected the stale comment that said interest never holds HUP/ERROR. `mux/LIFECYCLE.md` (close triggers, §7.4 step 6, invariant 12) and `doc/lifetime_of_a_session.md` now describe the exit condition and the budget. CHANGELOG entry added. This is a different defect from #1640, where a backend FIN in the middle of the body was forwarded as a complete response. Here the backend sends the response whole and the proxy dropped its tail. ## Tests (red on `main`, green here) - `a_slow_client_receives_the_whole_response_of_a_backend_that_closed` and `a_half_closed_slow_client_...`: the H1 frontend socket would block (small send/receive buffers), and the backend wrote 160 KiB and closed. On `main` the first pass returns `Close` and the client gets 32,805 of 163,883 bytes. With only the spin fix reverted: `ran 9999 iterations`. - `the_loop_limit_waits_for_the_client_while_a_stream_holds_its_response`: red with the old `has_pending_write()`-only check. `the_loop_limit_closes_a_session_with_nothing_queued` is the guard: a recycled slot's leftover bytes do not keep a session. - e2e `test_h2_window_stalled_client_receives_the_whole_response_of_a_closed_backend`: the H2 client keeps the default 65,535-byte windows until the backend has closed. On `main`: `http.infinite_loop.error=1 reopened=false body=65535/131072`. Here: `http.infinite_loop.error=0 body=131072/131072 ended=true`. Limitation: the H1 frontend has no dedicated e2e. The kernel autotunes sōzu's frontend send buffer and no listener setting controls it, so a client that only reads slowly does not reach the state deterministically. I measured this: with the client stalled on a 4 MiB response, the frontend was still writable when the backend's FIN arrived, and stepped reads of 8 MiB never went red on `main`. H1 is covered by the two unit tests and by the stress run below. Flow control stalls the H2 frontend whatever the buffer sizes. - e2e `test_idle_h2_backend_sending_data_on_stream_zero_is_answered_at_once` and `test_idle_h2_backend_sending_headers_on_an_idle_stream_is_answered_at_once`: an idle H2 backend sends a bad frame and keeps its socket open. With 5000055 (the first version of this PR, which ignored every backend HUP): `answered=false ending=timeout elapsed=12.0s`. Here: a 5xx in about 0.51 s. - `a_second_loop_limit_without_progress_closes_the_session`: pins the bounded wait. - The slow-client unit tests count limit hits with a test-only counter, so they also check in release builds. Red in release with the fix reverted: 284 and 262 hits. The H1 `force_disconnect` path (`ConnectionH1::end_stream`) is not a regression: it clears the backend's interest before it raises HUP, so `filter_interest()` was already empty on `main`, and nothing counted that HUP before this PR either. With `has_loop_work` it now counts, so that backend is closed in the same pass rather than on the next event. ## Validation - `cargo +nightly fmt --check`: OK - `cargo +1.93.1 clippy --all-features --all-targets --locked -- -D warnings`: OK - `RUSTDOCFLAGS="-D warnings" cargo +1.93.1 doc --no-deps --locked -p sozu-lib`: OK - `cargo +1.93.1 test -p sozu-lib --lib --all-features --locked`: 1597 passed - full e2e `--features opentelemetry,splice,simd`: 625 passed - `check_doc_citations.py --root . --base origin/main`: OK - `test_plain_client_half_close_after_request_receives_large_response`, 150 runs under `taskset -c 0` with 4 busy loops pinned to CPU 0: **0/150 failures** (450 exchanges) with the first version, and **0/100** with the current head. The same setup gave 1/30, 1/60, 1/80 and 2/150 on `main`. Fixes #1819 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.
Problem
A
Connection: closeH1 backend that closes before its announcedContent-Lengthhad its body ended as if complete (#1633):content-length: 10. RFC 9113 §8.1.1 makes that response malformed.H1::Completein the access log, and the client connection kept alive. The client waits for bytes that never come, and a pipelined response would land where the client still expects the missing body.ConnectionH1::terminate_close_delimitedonly treatedBodySize::Chunkedas truncated. TheEndStreamAction::CloseDelimitedarm ofConnectionH2::end_streamhad the same shape (#1630 guarded chunked only).Writing the red tests exposed a second defect, which also breaks the existing chunked fix whenever the backend says
Connection: close. Once the back kawa is inError, the backend's HUP reachesend_stream_decision.Erroris not a main phase, so it answeredSendDefault(502), andset_default_answerwrote a 502 behind the bytes already sent:HTTP/1.1 200 OK … 4\r\nabcd\r\nHTTP/1.1 502 Bad Gateway …on one connection, with the 502 inside the 200's body.body_bytes=1454 end_stream=true rst=false).test_h2_chunked_backend_crash_mid_stream_rstsdoes not see this because its backend is keep-alive and never reachesterminate_close_delimited.Fix
ConnectionH1::terminate_close_delimited(lib/src/protocol/mux/h1.rs): any body other thanBodySize::Emptythat is still in its body phase at the EOF is truncated (RFC 9112 §6.3 rule 5, §7.1). It gets the samewarn!, the sameh1.backend_eof_before_message_completemetric and the sameErrorphase as the chunked case. Only a body with neither framing ends cleanly at the close (rule 8).ConnectionH2::end_stream,CloseDelimitedarm (lib/src/protocol/mux/h2.rs): the guard goes from== Chunkedto!= Empty, with the same RST_STREAM, metric andwarn!. This covers the socket-error and backend-timeout path.end_stream_decision(lib/src/protocol/mux/shared.rs): a back kawa inErrorwhoseconsumedis set (Kawa::consume, called by the H1 write path and the H2 converter) now getsForwardUnterminated: RST_STREAM(INTERNAL_ERROR) on H2. If nothing of the response has left yet, the clean 502 still stands.ConnectionH1::writable: once a response inErrorhas been flushed, the H1 frontend closes (defer_close_for_tls_flush, so write-only shutdown and TLS close_notify). It is never kept alive. The client sees a close beforeContent-Length, which is the RFC 9112 §6.3 signal for an incomplete message, and no pipelined response can follow.Mux::closelogs the stream as an error. This also fixes a keep-alive backend dying mid-body: before, the H1 client hung until the frontend timeout (test_h1_keep_alive_backend_dying_mid_body_closes_client, red without this hunk).No allocation is added. The new
debug_assert!s cover internal kawa invariants only: body phase on entry,expects > 0for aLengthbody still in its body phase, and an errored response that is not also terminated. None of them asserts on network input.Red → green
Every test below failed on
d5161919(unmodified production code) and passes on this branch.d5161919h1::tests::only_a_close_delimited_body_ends_cleanly_at_the_backend_eofa truncated Length(10) body must end in Error, got Terminatedshared::tests::an_errored_response_already_handed_to_the_client_is_not_replacedleft: SendDefault(502) right: ForwardUnterminatedh2::tests::a_content_length_response_cut_short_ends_with_a_resetstream 1 must end with RST_STREAM, frames [(1, 0), (0, 0), (0, 1)]test_h2_content_length_truncated_by_backend_close_rstsFAIL H2-CL-TRUNC: body_bytes=4, end_stream=true, rst=falsetest_h2_content_length_truncated_after_forwarded_head_rstsFAIL H2-CL-TRUNC-SPLIT: body_bytes=4, end_stream=true, rst=falsetest_h2_chunked_truncated_by_closing_backend_rstsFAIL H2-CHUNKED-TRUNC: body_bytes=1454, end_stream=true, rst=false(the 502 page as DATA)test_h1_content_length_truncated_by_backend_close_closes_clientthe client connection was not closed: still open after 5s, read so far: "HTTP/1.1 200 OK … Content-Length: 10 … abcd"test_h1_content_length_truncated_after_forwarded_head_closes_clienttest_h1_chunked_truncated_by_backend_close_closes_client4\r\nabcd\r\nHTTP/1.1 502 Bad Gateway …inside the 200 bodytest_h1_keep_alive_backend_dying_mid_body_closes_clientConnectionH1::writablehunk revertedNon-regression, green before and after:
test_h2_content_length_complete_then_backend_close_ends_streamandtest_h1_content_length_complete_then_backend_close_stays_alive: a whole 10-byte body followed by EOF ends cleanly. On H1 the same connection then serves a second request.test_h2_close_delimited_body_ends_stream_at_backend_closeandtest_h1_close_delimited_body_ends_at_backend_close: a body with noContent-Lengthends cleanly at the EOF.test_h2_chunked_backend_crash_mid_stream_rstsandtest_h2_close_delimited_large_response: unchanged.The H1 truncation tests also check that
http.active_requestsgoes back to 0 after the close.Protocol / security impact
Neighbouring defect, not fixed here
After a close-delimited body (no
Content-Length, no chunked), sozu forwards the backend'sConnection: closeto a keep-alive H1 client but does not close the client connection, so the client cannot find the end of the body until the frontend timeout.test_h1_close_delimited_body_ends_at_backend_closereads until the body arrives rather than until EOF, so it does not pin this.The obvious fix, clearing
keep_alive_frontend, would also close the whole H2 connection (theclose_frontendcheck inConnectionH2's write pass), so it needs its own change and its own issue.Parallel work
The
h2.rsproduction diff is limited to theCloseDelimitedarm ofConnectionH2::end_stream(guard, comment,warn!argument,debug_assert!message), and the line count is unchanged so doc citations do not move. The otherh2.rschanges are one new unit test and one doc-comment line in the existing chunked test.ConnectionH2::start_streamand the rest ofend_streamare untouched. That keeps the overlap withfix/h2-backend-stream-lifecycle(#1631/#1632) to one arm.Docs
lib/src/protocol/mux/LIFECYCLE.md§8.4: new "backend close before the end of the response" paragraph. The driftedh1.rs:NNNcitations are replaced by symbols.lib/src/protocol/kawa_h1/LIFECYCLE.md:on_response_headers/keep_alive_backend, andset_default_answer's new boundary.doc/h2_mux_internals.md: the close-delimited arm now also coversContent-Length.doc/configure.md: theh1.backend_eof_before_message_completerow names the real emission sites (the oldmux/h1.rs::back_readablesymbol no longer exists) and the H1 behaviour.CHANGELOG.md: new Fixed entry.HAProxy and hyperium/h2 sources were not re-read for this change. The fix rests on RFC 9112 §6.3/§7.1 and RFC 9113 §8.1.1.
Commands run
The red proofs above were taken on
d5161919. The commands below ran on the pushed commit, rebased on3a79685e:cargo build --locked→ exit 0cargo build --all-features --locked→ exit 0cargo clippy --all-targets --locked -- -D warnings→ exit 0cargo clippy --all-targets --locked --no-default-features --features crypto-ring,opentelemetry,splice,simd -- -D warnings→ exit 0cargo +nightly fmt --all -- --check→ exit 0cargo test --workspace --locked -- --skip tests::fuzz_tests:: --test-threads=8→ exit 0 (sozu-lib1292 passed,sozu-e2e467 passed, 0 failed)RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features --locked→ exit 0check_doc_citations.py --self-test→ exit 0check_doc_citations.py --root .github/scripts/testdata/citations→ exit 1 with itsdo not resolvereport, as expectedcheck_doc_citations.py --base origin/main→ exit 0check_doc_citations.py→ exit 0cargo test -p sozu-e2e -- backend_close backend_rsts closing_backend forwarded_head dying_mid_body), 5 consecutive runs → 11 passed each timeCloses #1633
Signed-off-by: Florentin Dubois [email protected]