Repository navigation
feat(h2): HTTP/2 support via unified Mux session layer - #1209
Conversation
- Use standard HTTP reason phrases in default answers (e.g., "Not Found" for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer" - Use HTTP/1.1 version in default answers instead of H2 - Remove extra Content-Length: 0 from error responses to match old behavior - Fix cookie header matching in HPACK decoder: compare against "cookie" instead of debug artifact "cookie---", forward cookies as regular headers - Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum - Remove stale commented-out nom macro parser code - Fix typo "trat" -> "treat" in parser comment - Document the http2 proto field on Cluster message Signed-off-by: Florentin Dubois <[email protected]>
331ae82 to
dd89b71
Compare
- Use standard HTTP reason phrases in default answers (e.g., "Not Found" for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer" - Use HTTP/1.1 version in default answers instead of H2 - Remove extra Content-Length: 0 from error responses to match old behavior - Fix cookie header matching in HPACK decoder: compare against "cookie" instead of debug artifact "cookie---", forward cookies as regular headers - Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum - Remove stale commented-out nom macro parser code - Fix typo "trat" -> "treat" in parser comment - Document the http2 proto field on Cluster message Signed-off-by: Florentin Dubois <[email protected]> Co-authored-by: Eloi Demolis <[email protected]>
9eab7f3 to
2a65aa7
Compare
|
Works on cleverapps.io, everything seems fine, need more time in production, but this implementation seems promising |
|
Spike on services, are massive load state on restart |
f7cd216 to
f40637d
Compare
Critical fixes: - C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count (self.streams.len()) instead of global context.active_len() - C-2: Parser rejects SETTINGS ACK with non-zero payload as FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth) - C-3: update_initial_window_size uses i64 intermediate math to prevent overflow on large deltas High-priority fixes: - H-1: RefusedStream sends RST_STREAM (stream error) instead of GOAWAY (connection error) per RFC 9113 §5.1.2 - H-3: Bounds check on storage.end before CONTINUATION header removal - H-4: Use saturating_sub for active_requests decrement - H-5: Buffer space checks before SETTINGS ACK and PING writes - H-6: H1→H2 header name validation rejects control chars/high bytes - H-7: Cap pending_window_updates at 202 entries Medium-priority fixes: - M-1: new_stream_id returns Option with exhaustion check - M-2: Reuse lowercase_buf across converter calls - M-3: Defensive .max(0) before casting window to usize - M-5: Flood detector uses half-decay instead of full reset - M-6: Skip pushing back zero-length chunks after split - M-7: Skip Content-Length: 0 for 1xx/204/304 responses - M-8: SETTINGS_ACK timeout checked in writable() too Low-priority fixes: - L-1: Replace Clone::clone() with to_owned() on strings - L-3: H2FloodDetector fields now pub(super) - L-4: Remove dead reuse_connecting variable Tests: - 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds, unknown frames, frame size validation) - 3 e2e tests (max concurrent streams RST, window overflow, empty DATA flood CVE-2019-9518) Signed-off-by: Florentin Dubois <[email protected]>
- Use standard HTTP reason phrases in default answers (e.g., "Not Found" for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer" - Use HTTP/1.1 version in default answers instead of H2 - Remove extra Content-Length: 0 from error responses to match old behavior - Fix cookie header matching in HPACK decoder: compare against "cookie" instead of debug artifact "cookie---", forward cookies as regular headers - Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum - Remove stale commented-out nom macro parser code - Fix typo "trat" -> "treat" in parser comment - Document the http2 proto field on Cluster message Signed-off-by: Florentin Dubois <[email protected]> Co-authored-by: Eloi Demolis <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
fef6d07 to
b215e87
Compare
Critical fixes: - C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count (self.streams.len()) instead of global context.active_len() - C-2: Parser rejects SETTINGS ACK with non-zero payload as FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth) - C-3: update_initial_window_size uses i64 intermediate math to prevent overflow on large deltas High-priority fixes: - H-1: RefusedStream sends RST_STREAM (stream error) instead of GOAWAY (connection error) per RFC 9113 §5.1.2 - H-3: Bounds check on storage.end before CONTINUATION header removal - H-4: Use saturating_sub for active_requests decrement - H-5: Buffer space checks before SETTINGS ACK and PING writes - H-6: H1→H2 header name validation rejects control chars/high bytes - H-7: Cap pending_window_updates at 202 entries Medium-priority fixes: - M-1: new_stream_id returns Option with exhaustion check - M-2: Reuse lowercase_buf across converter calls - M-3: Defensive .max(0) before casting window to usize - M-5: Flood detector uses half-decay instead of full reset - M-6: Skip pushing back zero-length chunks after split - M-7: Skip Content-Length: 0 for 1xx/204/304 responses - M-8: SETTINGS_ACK timeout checked in writable() too Low-priority fixes: - L-1: Replace Clone::clone() with to_owned() on strings - L-3: H2FloodDetector fields now pub(super) - L-4: Remove dead reuse_connecting variable Tests: - 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds, unknown frames, frame size validation) - 3 e2e tests (max concurrent streams RST, window overflow, empty DATA flood CVE-2019-9518) Signed-off-by: Florentin Dubois <[email protected]>
|
So, it runs on cleverapps.io, we identified two main issues which are now fixed or in progress to be fixed.
|
- Use standard HTTP reason phrases in default answers (e.g., "Not Found" for 404, "Bad Gateway" for 502) instead of generic "Sozu Default Answer" - Use HTTP/1.1 version in default answers instead of H2 - Remove extra Content-Length: 0 from error responses to match old behavior - Fix cookie header matching in HPACK decoder: compare against "cookie" instead of debug artifact "cookie---", forward cookies as regular headers - Add #[repr(u32)] with explicit RFC 7540 error codes to H2Error enum - Remove stale commented-out nom macro parser code - Fix typo "trat" -> "treat" in parser comment - Document the http2 proto field on Cluster message Signed-off-by: Florentin Dubois <[email protected]> Co-authored-by: Eloi Demolis <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
Critical fixes: - C-1: MAX_CONCURRENT_STREAMS now checks per-connection stream count (self.streams.len()) instead of global context.active_len() - C-2: Parser rejects SETTINGS ACK with non-zero payload as FRAME_SIZE_ERROR (RFC 9113 §6.5 defense-in-depth) - C-3: update_initial_window_size uses i64 intermediate math to prevent overflow on large deltas High-priority fixes: - H-1: RefusedStream sends RST_STREAM (stream error) instead of GOAWAY (connection error) per RFC 9113 §5.1.2 - H-3: Bounds check on storage.end before CONTINUATION header removal - H-4: Use saturating_sub for active_requests decrement - H-5: Buffer space checks before SETTINGS ACK and PING writes - H-6: H1→H2 header name validation rejects control chars/high bytes - H-7: Cap pending_window_updates at 202 entries Medium-priority fixes: - M-1: new_stream_id returns Option with exhaustion check - M-2: Reuse lowercase_buf across converter calls - M-3: Defensive .max(0) before casting window to usize - M-5: Flood detector uses half-decay instead of full reset - M-6: Skip pushing back zero-length chunks after split - M-7: Skip Content-Length: 0 for 1xx/204/304 responses - M-8: SETTINGS_ACK timeout checked in writable() too Low-priority fixes: - L-1: Replace Clone::clone() with to_owned() on strings - L-3: H2FloodDetector fields now pub(super) - L-4: Remove dead reuse_connecting variable Tests: - 12 unit tests for parser (SETTINGS ACK, WINDOW_UPDATE bounds, unknown frames, frame size validation) - 3 e2e tests (max concurrent streams RST, window overflow, empty DATA flood CVE-2019-9518) Signed-off-by: Florentin Dubois <[email protected]>
145847b to
219d6ee
Compare
|
I think the new 5s H2 shutdown timeout changes In That means a slow but healthy H2 upload/download/stream can now be truncated during The flush retry and quiesced-stream fixes make sense to me. The 5s forced close does not, unless |
The `Crypto providers` matrix at lines 32-48 advertised three Cargo features (`crypto-ring`, `crypto-aws-lc-rs`, `crypto-openssl`) that do not exist in this workspace. `rustls` is wired to `ring` through the workspace `Cargo.toml`; there is no pluggable provider surface today. The "`--all-features` does not work" warning was also untrue on this branch — `cargo build --all-features --locked` succeeds. Replace the section with a `Cargo features` table that lists the flags actually published (`tolerant-http1-parser`, `simd`, `splice`, `opentelemetry`, `logs-debug`, `logs-trace`, `e2e-hooks`) and points readers at the per-crate `Cargo.toml` for the authoritative source. The 16393 buffer-size note in the `HTTP/2 support` section is left untouched. Signed-off-by: Florentin Dubois <[email protected]>
`sozuctl` was folded into the `sozu` CLI long ago; the audit-log documentation still cited it as the actor `comm` value in two example payloads (lines 223, 302) and in two prose bullets (lines 239, 242). Rewrite the four sites: `actor_comm=sozuctl` and the JSON `"comm": "sozuctl"` become `actor_comm=sozu` / `"comm": "sozu"` so they match what `/proc/<pid>/comm` actually returns from the CLI today, and the prose bullets describe the binary as the `sozu` command-socket client (the `sozu` binary running with the `command` sub-command) instead of `sozuctl`. Signed-off-by: Florentin Dubois <[email protected]>
The mux module-layout table was frozen at the pre-rewrite shape (7 modules, 11 178 lines). HEAD ships 13 modules totalling 18 666 lines (`wc -l lib/src/protocol/mux/*.rs`). Refresh the table to the current per-file counts (mod 1818, h1 823, h2 7562, parser 2246, serializer 557, converter 1410, pkawa 2229) and add the missing rows for `connection.rs` (578), `router.rs` (678), `stream.rs` (290), `answers.rs` (302), `shared.rs` (93), `debug.rs` (80). Three permalinks pointed at long-stale SHAs (`01a78be7…/lib/src/lib.rs#L527`, `3111e2db…/lib/src/logging.rs`, `3111e2db…/lib/src/network/metrics`); the cited paths have moved (`logging` lives under `command/src/logging`, `metrics` under `lib/src/metrics`). Rewrite the three permalinks to point at the current `main`-branch paths. Add a single-line note under "Key design decisions" referencing the on-branch `lib/src/protocol/mux/LIFECYCLE.md`, and clarify under "H2 backend (h2c)" that `cluster.http2` is a backend-capability hint and does NOT gate frontend H2 (frontend H2 is TLS-ALPN driven). Signed-off-by: Florentin Dubois <[email protected]>
Drop the literal `TODO` under "Release Notes" and link the project `CHANGELOG.md` instead. Add bullets for the seven previously-unlinked docs (`configure_cli.md`, `debugging_strategies.md`, `lexicon.md`, `observability.md`, `benchmark.md`, `rate-limit-design.md`, `nightly-ci-notes.md`) and `configure_admin_ops.md` (planned for the admin-ops narrative pass). Reorganise into "Operating Sōzu" (config + admin + observability + debugging + bench + rate-limit) and "Going deeper" (mux internals + in-tree LIFECYCLE.md + lifetime-of-a-session). Add a link from "Going deeper" to `lib/src/protocol/mux/LIFECYCLE.md` so readers can cross-reference the in-tree state-machine notes that ship alongside the code. Signed-off-by: Florentin Dubois <[email protected]>
Part A — module-level //! headers across 34 files: mux (converter, h1,
h2, parser, pkawa, serializer), protocol/mod, kawa_h1 (mod, answers,
editor, parser, diagnostics), proxy_protocol (mod, expect, header,
parser, relay, send), pipe, rustls, https, socket, metrics/mod,
command (channel, scm_socket, buffer/{mod,fixed,growable}), bin
(upgrade, command/{mod, server, sessions, requests}), and the two
fuzz targets. Texts cite RFC sections, sibling modules, or the
canonical write-up they delegate to.
Part B — load-bearing invariant comments at six previously
undocumented sites:
- mux/mod.rs 16-iteration drain loop: explain the missing
invariant-15 hop and cross-link mux/LIFECYCLE.md;
- mux/connection.rs //!: point at mux/h2.rs as the canonical home
for the edge-trigger discipline;
- write-only shutdown invariant on the three undocumented call
sites (mux/mod.rs backend ×2, http.rs frontend);
- FrontRustls::socket_write + socket_write_vectored symmetry
contract with regression-test pointer (h2_correctness_tests +
h2_tests::test_h2_large_*);
- command/src/config.rs H2_MIN_BUFFER_SIZE enforcement: cross-link
mux/LIFECYCLE.md;
- e2e/src/tests/mod.rs //!: narrow serial_test::serial(force_h2_
client_failure) discipline to e2e-hooks AtomicBool toggles only.
No behaviour changes. Validates: cargo +nightly fmt --check, cargo
build --all-features --locked, cargo clippy --all-targets --locked,
( cd fuzz && cargo +nightly check ).
Signed-off-by: Florentin Dubois <[email protected]>
Annotate the 63 previously-undocumented `unsafe { … }` blocks across the
worker, supervisor, and command-channel paths with explicit `// SAFETY:`
comments. Annotation only — no block body changes, no new or removed
`unsafe`. Each annotation states the precondition the block relies on and
points back to the upstream source of truth (call site, parser invariant,
sibling `Drop`).
Family breakdown: 14 `from_raw_fd` ownership transfers (server, scm,
upgrade, util, worker, command/server), 6 `from_utf8_unchecked` ASCII /
UTF-8 proofs (http, https, kawa_h1/parser, access_logs OpenTelemetry),
5 raw-pointer `DuplicateOwnership` impls + `into_binary_access_log` (with
the double-free obligation called out per type-level guidance at
`access_logs.rs:26`), 15 overlap-safe `ptr::copy` calls (buffer/fixed,
buffer/growable, pool), and 23 syscall / FFI sites (`getpid`, `fork`,
`getrlimit`/`setrlimit`, `sched_setaffinity`, `getsockopt`,
`sendmmsg`, `env::set_var`, `BorrowedFd::borrow_raw`, `from_raw_fd`
borrow-then-release).
Parity (dynamic): `unsafe_n=69`, `safety_n=69`. The expected delta is
`safety = unsafe + 1` because `kawa_h1/mod.rs:1211` carries a SAFETY
comment over a non-`unsafe` `Shutdown::Both` (the TLS-truncation
invariant). Counted via:
unsafe_n=$(git grep -cE 'unsafe[[:space:]]*\{' lib/src command/src bin/src \
| awk -F: '{s+=$2}END{print s}')
safety_n=$(git grep -cE '// SAFETY' lib/src command/src bin/src \
| awk -F: '{s+=$2}END{print s}')
Validation: `cargo +nightly fmt --check`, `cargo build --all-features
--locked`, `cargo clippy --all-targets --locked` (no new warnings),
`cargo test --all-features --locked` (805 passed, 9 ignored across 10
suites).
Signed-off-by: Florentin Dubois <[email protected]>
Sweep the last six in-source `sozuctl` references in the supervisor
surface so the renamed `sozu` CLI is consistent with the prose work
already done in C2 (`RELEASE.md`/`CONTRIBUTING.md`) and C6
(`doc/observability.md`):
- `bin/src/command/server.rs`: two doc comments on `peer_comm` (the
per-accept `/proc/<pid>/comm` reader behind LISA-009).
- `bin/src/command/sessions.rs`: two field-doc comments on
`ClientSession::session_ulid` and `actor_comm`.
- `bin/src/command/requests.rs`: one comment in the `audit_log_context!`
macro doc and one test-fixture string in the audit-format tests.
`/proc/<pid>/comm` is capped at 15 chars by the kernel, so the
fixture stays short ("sozu"); prose uses "sozu CLI" or
"sozu command-socket client" depending on context. Pure comment +
test-fixture-string churn — no functional change.
Acceptance:
- `git grep -n 'sozuctl' bin/ doc/ command/ lib/ e2e/`: zero matches.
- `git grep -n '"sozuctl"' bin/ command/ lib/ e2e/`: zero matches.
- `cargo test -p sozu --all-features --locked`: 18 passed.
Signed-off-by: Florentin Dubois <[email protected]>
Add the maintainer-facing siblings to lib/src/protocol/mux/LIFECYCLE.md plus an operator-facing admin-ops worked-examples doc and a fuzz crate README that stays honest about the absent OSS-Fuzz wiring. New files: - lib/src/protocol/kawa_h1/LIFECYCLE.md (270 lines) H1 frontend / H1 backend lifecycle: per-stream accept → parse → route → backend connect → response stream → keep-alive → close, the HttpContext editor pass, the DefaultAnswer template machinery, the diagnostics envelope, and the load-bearing invariants (no panic on network input; write-only TLS shutdown; H1 readiness lifecycle owned by the editor; tolerant-http1-parser opt-in). Cross-links the mux LIFECYCLE for the H2 path. - lib/src/protocol/proxy_protocol/LIFECYCLE.md (199 lines) Three-role narrative (expect ingress, relay forwarding, send synth) with v1 vs v2 wire-format reminder, the per-state machine, and the hardening rules (bounded 232-byte buffer, fast-close on bare-TCP healthchecks, MAX_LOOP_ITERATIONS ceiling, error counters on every reject, no panic on adversarial input). - bin/src/command/LIFECYCLE.md (283 lines) Supervisor lifecycle: begin_main_process → main loop → shutdown / re-exec; the SO_PEERCRED accept envelope (ULID, actor_uid/gid/pid, PID-reuse-guarded actor_comm, cached actor_user, socket_path, connect_ts); verb dispatch and worker fan-out; hot-upgrade interaction. Recent additions subsection groups the post-feat/h2-mux hardening: command_allowed_uids admission, audit-log envelope (text + JSON sinks, sanitize_for_audit chokepoint), Lisa LISA-009 PID-reuse guard, drop-on-register-fail. - fuzz/README.md (225 lines) Crate layout, the two harnesses with bug classes (fuzz_frame_parser for the RFC 9113 length-confusion CVE family backing ensure_frame_size!; fuzz_hpack_decoder for RFC 7541 / loona-hpack oversize + incomplete-update flaws), local-run instructions, regression repro workflow, triage workflow that funnels findings to CODEOWNERS rather than directing readers to open issues, and an honest OSS-Fuzz section that records the absence of .clusterfuzzlite/ on this branch and outlines the integration steps per the ClusterFuzzLite docs. - doc/configure_admin_ops.md (261 lines) Operator-facing worked-examples doc: patchable listener fields with preserve-on-omit semantics, tightening H2 flood thresholds under attack, toggling disable_http11 per listener, the cluster h2 enable|disable query-then-resubmit dance behind bin/src/ctl/request_builder.rs:214-238, plus an operational write-up (not a duplicate reference table) of the post-feat/h2-mux behaviours: per-connection stream-Vec shrink, channel message_len upper bound, drop-on-register-fail, SNI trailing-dot normalisation, https.alpn.rejected.unsupported counter, ensure_frame_size! macro. Two patches to doc/configure.md: - :65 — bump example buffer_size from 16384 to 16393 so the example matches the H2-enforced minimum already documented at :40. - :939 — add a row for the https.alpn.rejected.unsupported counter alongside the existing https.alpn.rejected.http11_disabled, matching the SOC bucket noted in the operational write-up. Validation: - §2.5 grep on the six touched files: zero hits for tasks/ and zero hits for ~/.claude/, /home/florentin/.claude/, /tmp/. - Markdown link sanity loop on all five new files: zero broken links. - cargo build --all-features --locked: passes. Signed-off-by: Florentin Dubois <[email protected]>
Replace the entire body of doc/lifetime_of_a_session.md (256 lines from 2022-12, pinned to a removed-files SHA permalink and citing modules that no longer exist on feat/h2-mux: lib/src/https_openssl.rs and lib/src/protocol/http/mod.rs). The new 500-line narrative covers the current architecture: single-threaded mio worker, edge-triggered readiness contract, slab- backed SessionManager, accept-queue + max_connections backpressure, TLS handshake (rustls + ALPN dispatch with per-cause refusal metrics), PROXY-protocol pre-flight, the three per-protocol session paths (Kawa-backed H1, H2 mux with stream lifecycle + RFC 9218 priorities + H2FloodDetector + GOAWAY draining, pipe pass-through), backend routing + load balancing, edge-triggered forwarding pitfalls, the TLS write-only shutdown invariant, hot reconfig + upgrades, and a metrics sidebar. Cross-links the four LIFECYCLE.md siblings introduced in C12 (mux/, kawa_h1/, proxy_protocol/, bin/src/command/). All cited file:line references re-grepped at write time. No SHA-pinned permalinks; legacy module names appear only in the §12 "Removed and migrated APIs" historical block. Signed-off-by: Florentin Dubois <[email protected]>
Replace archived `actions-rs/*` actions with `dtolnay/rust-toolchain` +
direct cargo invocations, and add three new always-required jobs that
mirror the local validation baseline documented in CLAUDE.md "Build":
* fmt — `cargo +nightly fmt --all -- --check` (rustfmt.toml uses
the unstable `ignore` key, so nightly is mandatory)
* clippy — `cargo clippy --all-targets --all-features --locked
-- -D warnings` (option (a) chosen — see pre-flight below)
* msrv — `cargo build --all-features --locked` against
`dtolnay/[email protected]`, advertising the MSRV
declared in Cargo.toml `rust-version = "1.85.0"`. The
`rust-toolchain` file still pins 1.88.0 for everyday
development; this job verifies that 1.85.0 still builds.
The existing `test`, `doc`, and `dockerhub` jobs keep their semantics:
* `test`: matrix stable/beta/nightly preserved; nightly stays
`experimental: true`. The previously-undefined
`${{ matrix.features }}` interpolation is replaced by an explicit
`--all-features` flag, matching the rest of the workspace baseline.
`protoc`, `cargo-fuzz`, and `h2spec` install steps are unchanged.
* `doc`: same toolchain, same `cargo doc --verbose` output.
* `dockerhub`: now carries an inline note that it tags `sozu:${SHA}`
on every push and that release tagging lives in RELEASE.md.
Pre-flight clippy (option-decision per the C14 plan):
cargo clippy --all-targets --all-features --locked -- -D warnings
-> 0 warnings, 0 errors, exit 0.
The `clippy::if_same_then_else` warning that was historically present
in `e2e/src/tests/h2_correctness_tests.rs` is no longer reachable on
this branch (test file has been refactored repeatedly during the
H2 mux work), so option (a) — the strict `--all-features` clippy gate
— ships cleanly without any accompanying Rust source change. Option
(b) (drop `--all-features`) and option (c) (`#[allow]` directives)
were considered and rejected per the plan's safety ranking.
Local validation of the new gates:
cargo +nightly fmt --all -- --check ok
cargo build --all-features --locked ok
cargo clippy --all-targets --all-features --locked -- -D warnings ok
yamllint .github/workflows/ci.yml no
new
findings
vs.
pre-existing
baseline
No `actions-rs/*` remain (`grep -rn 'actions-rs' .github/` returns
zero hits).
Signed-off-by: Florentin Dubois <[email protected]>
Append two narrative sub-sections to the freshly regenerated
`feat/h2-mux - Unreleased` block summarising the documentation +
continuous-integration audit pass shipped in C1-C14:
- `### 📚 Documentation` (7 bullets) covers the README/RELEASE/CONTRIBUTING
refresh, the `doc/` folder resync (crypto-providers section dropped,
architecture line counts refreshed, observability audit examples
rewritten, configure.md `buffer_size` example bumped, README index
populated), the full rewrite of `doc/lifetime_of_a_session.md` cross-
linking the new per-protocol LIFECYCLE.md siblings, the module-level
`//!` doc headers across the previously-bare critical surfaces, the 63
new `// SAFETY:` annotations (parity check `safety = unsafe + 1`), the
load-bearing in-source invariant comments (16-iter drain loop,
socket_write symmetry, write-only TLS-frontend shutdown rule, e2e
serial_test discipline), the new narrative documents (kawa_h1 +
proxy_protocol + bin/src/command LIFECYCLE.md, fuzz README with
OSS-Fuzz roadmap, configure_admin_ops.md), and the comment-only
sozuctl→sozu rename.
- `### 🤖 Continuous Integration` (4 bullets) covers the
`actions-rs/*@v1` retirement (replaced by `dtolnay/rust-toolchain`),
the new enforced `fmt` and `clippy` (`-D warnings`) jobs that were
previously local-only conventions in CLAUDE.md, the new MSRV (1.85.0)
build gate, and the noted clippy hygiene status (the
`if_same_then_else` warning called out in CLAUDE.md is no longer
reachable on this branch, so the `-D warnings` gate ships clean
without a Rust-source change).
Validation:
- `git grep -nE '(^|[^/[:alnum:]])tasks/' -- CHANGELOG.md` → zero hits.
- `git grep -nE '(~/\.claude|/home/florentin/\.claude|/tmp)' -- CHANGELOG.md`
→ zero hits.
- All 7 relative `(...md)` links in the new bullets resolve to existing
files: `doc/lifetime_of_a_session.md`, `doc/configure_admin_ops.md`,
`fuzz/README.md`, `lib/src/protocol/{mux,kawa_h1,proxy_protocol}/LIFECYCLE.md`,
`bin/src/command/LIFECYCLE.md`.
- `[Unreleased]: …compare/1.1.1...HEAD` Keep-a-Changelog footer line
unchanged from C3.
- `cargo build --all-features --locked` succeeds (no Rust source changed).
Signed-off-by: Florentin Dubois <[email protected]>
The C14 GitHub Actions modernisation passed local validation but failed in CI on the two new gates. Both failures were YAML config issues, not warnings on the actual source code. Fix: * fmt job — install `protobuf-compiler` and run `cargo +nightly check -p sozu-command-lib --locked` before `cargo +nightly fmt --all -- --check`. `command/build.rs` runs `prost-build`, which generates `command/src/proto/command.rs`. Without that file present, rustfmt fails to resolve `mod command;` while walking the module tree, even though `rustfmt.toml` lists the file in the `ignore` array. * clippy job — switch the lint command from `cargo clippy ...` to `cargo +stable clippy ...`. The repo's `rust-toolchain` file pins `1.88.0`, which `cargo` honours by default and overrides the `dtolnay/rust-toolchain@stable` install. Stable does carry the `clippy` component installed alongside it; the explicit `+stable` toolchain selector points cargo at that toolchain. Local toolchains pass without these steps because (a) prior workspace builds leave the prost-generated file on disk, and (b) the local `1.88.0` toolchain typically has clippy installed alongside it. CI's fresh checkout reproduces neither. The MSRV job (1.85.0 build) was already green; no change there. Signed-off-by: Florentin Dubois <[email protected]>
The previous fix used `cargo +stable clippy` to bypass the `rust-toolchain` pin, but stable 1.95 fires several lints that 1.88 does not (`clippy::derivable_impls` on `MetricDetailLevel` in `command/src/config.rs`, `mismatched_lifetime_syntaxes` on five parser/serializer functions in `lib/src/protocol/mux/`). CLAUDE.md "Build" documents the workspace as warning-free under `cargo clippy --all-targets --locked` (no `--all-features`); the implicit baseline there is the pinned 1.88.0 toolchain. Pin the CI clippy job to `dtolnay/[email protected]` with the `clippy` component so the gate enforces the same baseline. Triaging the newer-stable lints across the workspace is its own follow-up, tracked alongside the eventual rust-toolchain bump. Locally verified: `cargo clippy --all-targets --all-features --locked -- -D warnings` on 1.88.0 → 0 issues. Signed-off-by: Florentin Dubois <[email protected]>
Keep the router DebugEvent import behind debug_assertions so release all-feature bin builds do not warn while debug builds keep recording the route in DebugHistory. Signed-off-by: Florentin Dubois <[email protected]>
1cd36dc to
9cdf2c2
Compare
Replace the stale post-1.1.1 generated index with current main..HEAD coverage for feat/h2-mux so reviewers can audit all 429 branch commits from one place. Signed-off-by: Florentin Dubois <[email protected]>
Align the advertised MSRV of every workspace crate with the `1.88.0` toolchain already pinned in `rust-toolchain`. The MSRV CI gate now runs on `dtolnay/[email protected]`, the `rust-version` field is bumped in `bin/`, `command/`, `e2e/`, and `lib/` manifests, and the prose references in README.md and CLAUDE.md are updated in lockstep. The corresponding "MSRV (1.88.0) build gate" line in CHANGELOG.md was already refreshed under the unreleased feat/h2-mux section. Signed-off-by: Florentin Dubois <[email protected]>
`cargo update --manifest-path fuzz/Cargo.toml` rolls the out-of-workspace fuzz crate's `Cargo.lock` forward to the latest patch / minor releases of transitive dependencies (icu_*, hashbrown 0.16->0.17, indexmap 2.13->2.14, zerocopy 0.8.42->0.8.48, rustls-pki-types 1.14.0->1.14.1, etc.). No direct dependency versions or fuzz target behaviour changes; corpus + harness untouched. The workspace `Cargo.lock` already tracks the same upstream versions, so only the fuzz lockfile moves here. Signed-off-by: Florentin Dubois <[email protected]>
Internal "Lisa LISA-XXX" tags from a private threat-modelling exercise leaked into in-tree comments and the changelog. Drop the tokens while preserving the technical rationale they prefixed: RFC citations, CWE references, defense-in-depth notes, and PID-reuse / NSS-cache mitigations now read on their own. Touches comments and prose only — no code or behaviour change. Verified with `cargo build --all-features --locked`, `cargo clippy --all-features --all-targets --locked`, `cargo +nightly fmt --all -- --check`, and `cargo test --workspace --lib --bins` (781 passed). Signed-off-by: Florentin Dubois <[email protected]>

Summary
Adds full HTTP/2 support to Sōzu through a unified Mux session layer that handles both HTTP/1.1 and HTTP/2 connections. The Mux layer replaces the old
Http<Front>protocol and enables all four protocol combinations transparently.This work builds on the mux_v1 architecture originally designed and implemented by @Edemolis (Eloi Demolis), with contributions from @hcaumeil (Helian Caumeil) on H2↔H2 SETTINGS handshake and H1→H2 upgrade path. The original
mux_v1branch established the coreMuxsession,Connection::H1/Connection::H2enum,Streamabstraction, and the H2 frame state machine. This PR extracts, adapts, hardens, and completes that work for production readiness.Architecture
The Mux layer uses kawa as the unified HTTP representation (headers, body, trailers as
Blocks), nom for H2 binary frame parsing, and loona-hpack for HPACK header compression. Buffer memory comes from poole (pooled slab allocator). ThePositionenum (Serverfor frontend,Client(cluster_id, backend, status)for backend) drives position-aware stream splitting.Protocol support matrix
Key changes
Core Mux session (
lib/src/protocol/mux/, ~14k lines)mod.rsMux<Front, L>struct,Connectionenum,Endpointtrait, session state machine,connect_to_backend, stream lifecycleh2.rsparser.rstake(payload_len)symmetry across fixed-length framespkawa.rsBlocks with full RFC 9113 validation, cookie splitting, Content-Length enforcement, RFC 9218 priority header parsingconverter.rsH2BlockConverterwith reusable cookie bufferh1.rsserializer.rsrouter.rsconnection.rsstream.rsanswers.rsshared.rsdebug.rsSupporting modules
lib/src/pool.rslib/src/socket.rsensure_tls_flushed(),signal_pending_write/read()lib/src/splice.rsIntegration (
lib/src/http.rs,lib/src/https.rs)HttpStateMachine::Http→HttpStateMachine::Mux(MuxClear)HttpsStateMachine::Http→HttpsStateMachine::Mux(MuxTls)["h2", "http/1.1"](H2 preferred)cluster.http2config fieldConfiguration (
command/src/config.rs,command/src/command.proto)New per-listener protobuf fields with compile-time defaults:
h2_initial_connection_windowh2_max_concurrent_streamsh2_stream_shrink_ratioh2_max_rst_stream_per_windowh2_max_ping_per_windowh2_max_settings_per_windowh2_max_empty_data_per_windowh2_max_continuation_framesh2_max_glitch_counth2_max_header_table_sizeCLI (
bin/src/)cluster h2 enable/cluster h2 disablecommands--http2flag for runtime H2 toggling--features simd)Removed
lib/src/protocol/h2/module (459 + 477 + 37 + 157 + 102 = 1232 lines)RFC compliance
RFC 9113 (HTTP/2)
Passes 127/145 h2spec 2.0 conformance tests (external
h2specbinary; the 18 failing checks cluster in §5.3, §6.9, §8.2.2, §8.3, and §8.1.2.6 — tracked as#1209-h2spec-hardening):MAX_CONCURRENT_STREAMSstart_stream() → bool,active_requestsrollback, back-pressure on repeatedREFUSED_STREAMdrainingflag,peer_last_stream_id, streams > last_stream_id retried on new connection, auto-close when drained, default-answer streams drained before closechecked_addoverflow handling per spectrailersvalue accepted:scheme/:pathsyntax enforcedRFC 7541 (HPACK)
h2_max_header_table_sizeconverter_buf/lowercase_bufafter large headersRFC 9218 (Extensible Priorities)
Prioriserstruct withHashMap<StreamId, (u8, bool)>for urgency + incremental flagparse_rfc9218_priority()parsespriorityheader (u=N, iformat)RFC 9110 (HTTP Semantics)
is_invalid_h2_header()set_content_length()helper:authorityreconciliation in H2→H1 downgrade pathSecurity hardening
Crash safety — zero panic paths
Every error handling path in the mux module is graceful. No network input can crash the worker:
unwrap()/expect()in production codeunreachable!()/assert!()/assert_eq!()in production codetodo!()/unimplemented!()/panic!()write_all()→invalid_headersflag patternerror!()+ GoAway/RST_STREAM/CloseSession (never crash)Request smuggling mitigations
transfer-encoding,connection,keep-alive,proxy-connection,upgrade) rejected in H2:schememust behttp/https,:pathmust start with/or be*:authoritymismatch detected and rejectedstrict_sni_binding(421 Misdirected Request + metric on mismatch)Flood detection (configurable)
Per-window and lifetime flood thresholds protect against protocol abuse, all configurable per-listener:
h2_max_rst_stream_per_windowh2_max_ping_per_windowh2_max_settings_per_windowh2_max_empty_data_per_windowh2_max_continuation_framesh2_max_glitch_counth2_max_rst_stream_lifetimeh2_max_rst_stream_abusive_lifetimeh2_max_rst_stream_emitted_lifetimeWhen a threshold is exceeded, the connection is terminated with GOAWAY(ENHANCE_YOUR_CALM). The MadeYouReset counter (added in Round 10) closes the emission-direction-flipped sibling of Rapid Reset: an attacker sending legitimate-looking frames (Content-Length mismatch, header parse error, rejected priority, zero-increment
WINDOW_UPDATEon an open stream) coerces the server into emitting RST_STREAM; gracefulNoErrorcancels are exempt.Pending RST_STREAM cap
MAX_PENDING_RST_STREAMS(200) with lifetime counter prevents memory exhaustion from accumulated RST_STREAM framesFuzz testing (
fuzz/)fuzz_frame_parser— H2 binary frame parser fuzzing with corpus (connection preface, all frame types)fuzz_hpack_decoder— HPACK decoder fuzzing with corpus (Huffman, indexed, incremental, never-indexed)crash-d7a34a0d-padded-headers-underflow-regressioncaptured and guardedPerformance
752e470awritable()Vec allocationc5ffba040fe3591f4dd11bd2fad019afVec::new()perwritable()cycleu=0) written before lower-priority ones (images atu=5)b486b700--features simdenables kawa SIMD HTTP parser9b850dbdBenchmarks
lib/benches/h2_scheduling.rs— Priority scheduling sort strategy comparison (insertion sort vs stable sort vs unstable sort)lib/benches/header_formatting.rs— Header formatting micro-benchmarks (expanded)Observability
OpenTelemetry trace propagation
#[cfg(feature = "opentelemetry")]feature flagtraceparent/tracestateheaders from H2 frames during stream creationSpanContextinto access log entries for distributed tracing correlationMetrics
http.active_requests, response time, request count, error rateconnections_per_backendgauge underflow fixSession-context logging prefix (Round 10)
Every protocol-layer log line now carries a structured session prefix matching the RUSTLS convention:
log_context!macros:rustls,pipe,tcp,kawa_h1,mux/h2,mux/h1,mux/mod(plus alog_context_lite!for borrow-conflict sites).session_ulidonMux) so every event for one frontend connection isgrep-correlatable.log_colored: bold accent protocol label, cyanSessionkeyword, gray attribute keys, bright-white values. ANSI codes are skipped when the sink is non-stdout.sozu_command::logging::is_logger_colored()public helper.H2FloodDetector::check_flood()refactored to returnOption<H2FloodViolation>so flood logs get emitted at the caller with full session context before GOAWAY.Configuration knobs documented
log_colored,access_logs_colored,access_logs_format,automatic_state_save,disable_cluster_metrics,back_timeout,accept_queue_timeout,worker_timeout— previously accepted by the parser but missing fromdoc/configure.mdand/orbin/config.toml; now fully documented.Test coverage
E2E tests — 227 tests across 12 files (20,387 lines)
h2_tests.rsh2_security_tests.rsh2_security_header_injection.rsh2_security_parser.rsh2_security_session.rsh2_security_sni.rsmux_tests.rstests.rsh1_security_tests.rstcp_tests.rstls_tests.rsfuzz_tests.rs#[ignore]d — require nightly + cargo-fuzz)Test infrastructure additions
e2e/src/mock/raw_h2_response_backend.rs— Raw-byte H2 response mock for adversarial:statustestinge2e/src/mock/h2_backend.rs— H2 backend mock for H2↔H2 scenariose2e/src/tests/h2_utils.rs— Shared H2 test utilities (frame builders, raw connection helpers, parameterized SNI)e2e/src/port_registry.rs— Port allocation registry for parallel test executionlib/assets/multi-sni-cert.pem+multi-sni-key.pem— Multi-SAN certificate for SNI E2E testslib/src/protocol/mux/cfg(test)hooks for router leak and stream-ID exhaustion testingConformance
test_h2spec_conformanceis no longer gated#[ignore]; it gracefully skips when theh2specbinary is missing from PATH.Crash safety
Code structure (h2.rs internals)
Sub-struct decomposition
ConnectionH2fields are organized into logical groups for maintainability:H2FlowControlwindow,peer_window,initial_window_sizeH2ByteAccountingoverhead_bytes,zero_window_countH2DrainStategoaway_sent,last_stream_id,pending_rst_streamsH2FloodConfigPrioriserHashMap<StreamId, (u8, bool)>Extracted methods
Large monolithic functions have been decomposed for readability:
handle_header_state()readable()handle_continuation_header_state()readable()write_streams()writable()flush_pending_control_frames()writable()flush_zero_to_socket()handle_1xx_reset()write_streams()ensure_tls_flushed()Result:
readable()~213 lines (was ~420),writable()~75 lines (was ~310).Dependencies
loona-hpackhpack0.3.0 which had panic vulnerabilities)nomkawapooleDocumentation
doc/h2_mux_internals.mddoc/architecture.mddoc/configure.mddoc/configure_cli.mdcluster h2 enable/disableCLI referencedoc/getting_started.mdCHANGELOG.mdFiles changed (128 files, +47,207/−2,350)
lib/src/protocol/mux/{mod,h1,h2,pkawa,converter,parser,serializer,router,connection,stream,answers,shared,debug}.rslib/src/pool.rslib/src/protocol/h2/{mod,parser,serializer,state,stream}.rslib/src/{http,https,lib,socket,tcp,splice,timer,tls}.rs,lib/src/protocol/{mod,kawa_h1/editor,pipe}.rscommand/src/{config,command.proto,proto/display,state,channel}.rsbin/src/{cli,command/requests,command/server,command/sessions,command/upgrade,ctl/*,upgrade,util,worker}.rslib/src/metrics/local_drain.rse2e/src/tests/{h2_tests,h2_security_tests,h2_security_header_injection,h2_security_parser,h2_security_session,h2_security_sni,mux_tests,h1_security_tests,tcp_tests,tls_tests,fuzz_tests,h2_utils}.rse2e/src/{port_registry,mock/h2_backend,mock/raw_h2_response_backend}.rs,lib/assets/{multi-sni-cert,multi-sni-key}.pemfuzz/{Cargo.toml,fuzz_targets/*.rs,corpus/**}lib/benches/h2_scheduling.rse2e/src/tests/{tests,mod}.rs,e2e/src/mock/{https_client,async_backend,sync_backend}.rsdoc/{h2_mux_internals,architecture,configure,configure_cli,getting_started,README}.md,CHANGELOG.md.github/workflows/{benchmark.yml,rsa-2048.cnf}Related issues
Closes #1211 — Configurable flood detection thresholds
Closes #1212 — OTel trace propagation from H2 headers to access logs
Closes #1213 — Proportional overhead distribution by bytes transferred
Closes #1214 — ConnectionH2 sub-struct decomposition
Closes #1215 — RFC 9218 extensible priorities
Closes #1216 — Code structure improvements / readable+writable split
Review rounds
This PR went through 10 rounds of systematic review:
Round 1 (commit
025822cf)Round 2 (commit
664bb659)Round 3 (commit
21e7514d)Round 4 (commits
7da4f580..fc606d23)Round 5 (commit
9f414492)ensure_tls_flushed(),signal_pending_write/read())Round 6 — Protocol hardening (commits
4a798013..497cd256)take(payload_len)in parser for all fixed-length framescfg(test)hooks for router leak and stream-ID exhaustion testingRound 7 — Security E2E expansion (commits
7e0c02ff..3942f674)Round 8 — Performance, correctness, and hardening (commits
0d8ea2fe..5dd49765)connections_per_backendgauge underflow, CI benchmark certificate hostnameh2_max_header_table_sizeconfig knobRound 9 — Multi-phase security hardening (commits
7f0b8871..dcc1a701)7f0b8871): keepssocket_writeandsocket_write_vectoredstructurally symmetric, tightens teardown ordering, rejects CL mismatches on trailers.2008ab3b): converts the per-stream timer from a lifetime cap to a true idle timeout — trickle DATA resets it, slow-multiplex Slowloris is cancelled per stream instead of pinningmax_concurrent_streamsslots for the full connection timeout.080e43f2): strengthens header validation, graceful-shutdown edge cases, and converter output bounds.b92ef8b7): port-equality semantics on:authority, overflow-safe arithmetic on flood counters, audit-driven hardening.dcc1a701): widens the settings-flood test read window to absorb event-loop jitter.2ba95847): MessageClient response logs downgraded frominfotodebugto keep prod stderr readable.Round 10 — Observability, documentation, and MadeYouReset (commits
b4148751..67e78070)b4148751): rolls out theMUX-H2 Session(peer=…, streams=N, last_peer_id=X, window=W, draining=…) >>>prefix across all seven protocol macros (rustls/pipe/tcp/kawa_h1/mux h2/h1/mod). Adds per-Muxsession_ulid, alog_context_lite!for borrow-conflict sites, andsozu_command::logging::is_logger_colored(). RefactorsH2FloodDetector::check_floodto returnOption<H2FloodViolation>so flood logs carry full context.9237f3ea): removes a duplicatelog_context!(self)arg inhandle_flood_violationand the GoAwayFrame serialize-error branch (flagged by the Lisa threat-hunt swarm audit).7953696d): caps server-emitted RST_STREAM with thetotal_rst_streams_emitted_lifetimecounter insideH2FloodDetector::record_rst_emitted(); wired throughreset_stream()on non-NoErrorresets (Content-Length mismatch, header parse error, priority rejection, zero-increment WINDOW_UPDATE on an open stream). Crossing the default 500 ceiling escalates to GOAWAY(EnhanceYourCalm). +3 new unit tests covering below-threshold, ceiling, and no-decay invariants. Privacy/retention note added todoc/configure.mdcovering the new per-line fields (peer IP, SNI, ULID).91e56270): cross-audit ofcommand/src/config.rs::FileConfigvsdoc/configure.md+bin/config.tomlsurfaced eight undocumented global keys (log_colored,access_logs_colored,access_logs_format,automatic_state_save,disable_cluster_metrics,back_timeout,accept_queue_timeout,worker_timeout) — all now documented with examples.67e78070): promotes the CVE-2025-8671 cap from a compile-time default to a listener-levelh2_max_rst_stream_emitted_lifetimeknob. Touches the proto (field Make TLS options configurable #27 onHttpListenerConfig, add a timeout to reactivate the "readable" event for the config socket #39 onHttpsListenerConfig),ListenerBuilder,add_h2_flood_rowsdisplay helper, bothget_h2_flood_configreaders,doc/configure.md, andbin/config.toml.Round 10b — RFC 9218 scheduler, audit-log enrichment, ergonomics, H2 polish (commits
7f8596c6..5e523ac0)RFC 9218 priority scheduling — prerequisite work for Round 11's ET-rearm pass:
7ddf1f30): the H2 receiver accepts client-emitted PRIORITY_UPDATE frames (RFC 9218 §7.1) and reseatsPrioriserentries mid-connection.3f9f5e38): scopeincremental_peer_countto the same urgency bucket plus ready peers, so a higher-urgency busy stream no longer forces an incremental yield.f6c02912): skip the incremental yield when only one stream occupies the bucket — no peer to round-robin to.8d226b88): suppress the incremental yield between the final DATA frame and the closing flags block, which would otherwise stall the trailing frame at stream close.164ba27a):finalize_writeandhas_pending_writenow enforce the invariant so forward progress is guaranteed after a priority reordering pass.465fb108) and mixed-urgency body-stall repro (5e523ac0).Audit log enrichment (control plane) — the command-socket audit trail was restructured from a flat
debug!stream into an operator-readable, MUX-alignedinfo!feed with full ucred attribution:2200fc2a— realign to theMUX Session(...)layout at debug level.0c2dc869— promote toinfo!so the trail is visible withoutlogs-debug.53b51e03— enrich with full ucred, fanout list, and injection-defence cleaning.6b21c9c4— dedicated audit sink, diff-before→after, requestsha256, cert-replace fingerprint.e7a5e29d— close-out: timestamp, actor_role,connect_ts,boot_generation,build_git_sha, JSON sink.Mux stability & lifecycle:
865ada38— H2 stream idle timeout now inheritsback_timeoutinstead of being capped at the old default.f0874b9e— SETTINGS_TIMEOUT detection demoted fromerror!towarn!and stops re-firing on every loop tick.040e305f— close the H1→H2 wake gap, refresh the outbound idle counter, and correctly classify chunked-EOF at stream end. Round 11 Fix C mirrors this commit for the H2-backend → H2-frontend direction.4b762c21— e2e large-asset repro suite with a newChunkedFlushH1Backendmock that exposes flush boundaries.Listener runtime-patch verb (operator ergonomics):
77ad575f—sozu listener {http,https,tcp} updateverb for patching listener config at runtime without a hot reload.dc341565— post-review follow-ups on the update verb.abd1663b— resetactiveongive_back_listenerplus repair of four e2e tests that depended on the old behaviour.Access log / correlation header:
f76c5d5b—Sozu-Idcorrelation header name is now a per-listener setting; default preserved for compat. Closes make Sozu-Id header field name configurable #1145.H2↔H1 trailer handling:
9b8f3884+5610d3d4— e2e lock-in for HTTP/1.1 chunked-trailer forwarding; the plumbing was already in place via kawa'sParsingPhase::Trailers. Closes Trailers in chunked frames #899.7f8596c6— H2→H1 translation on fixed-Content-Lengthstreams silently drops trailers (RFC 9110 §6.5). This commit adds awarn!and theh2.trailers_dropped_content_lengthcounter so operators can detect the drop; peers that omitContent-Lengthget upgraded to chunked framing and their trailers pass through.H2 protocol polish:
a585cea3— emit HPACK dynamic-table-size-update on SETTINGS change (RFC 7541 §4.2).71d77d71— e2e lock-in: response:statusmust be present and non-empty.8370b90f— raw-H2 assertion for 1xx informational forwarding (100 Continue / 103 Early Hints).9ff035d5— 30-iteration backend-disconnect stress verifies no stream-state leak.11fcdc0a— document the negotiatedmax_frame_sizecaller contract.74e0edec— document theremove_dead_streamcache-eviction invariant.Log severity & dead-code hygiene:
07a83e92— harmonise backend retry-budget-exhaustion log severity across H1 and H2 paths.9216e52a— gate the dead-codedebug!arm onlogs-debugso release builds no longer emit unused-variable warnings on this path.Ping-flood diagnostic:
ebdef01f— instrument the ping-flood write path so future CI flakes carry enough context to diagnose from stderr.defd17d7— nightly fmt on the ping-flood diagnostic.Rate-limit design (foundation; implementation pending, tracked in #890):
0031aadb— per-tenant 429 + per-source-IP cap design recorded indoc/rate-limit-design.md. Reject response carriesRetry-AfterandX-Sozu-RateLimit-Rule; counter familyrate_limit.rejected.*.Audit-findings task log (internal tracking under
tasks/):4c35c10e,8242c777,5246c80b— running record of post-merge audit findings (buckets B3-c/d/f/g/j/o/p/q/v/w/x).Round 11 — ET signal-pairing hygiene + invariant-15 canonical API (commits
66431dd1..40c9c2af)*.cleverapps.io; two concurrentpriority: u=1, iXHRs stalled 180 s with sozu-emitted 504s). Dual-pass review converged on three latentinterest.insert(Ready::WRITABLE)sites missing the pairedsignal_pending_write()— hardened in this round as defence-in-depth for LIFECYCLE invariant 15. The observed 180-s stall most likely traces to backend-side slowness (Spring Boot / Tomcat / MongoDB); themux/mod.rs:1402-142316-iter synchronous drain loop was already flushing the 504 (confirmed by thesozu-idheader visible in the HAR response).66431dd1):Readiness::arm_writable()inlib/src/lib.rspairsinterest.insert(Ready::WRITABLE)withsignal_pending_write()at a single call site. The existing H1 sites (mux/h1.rs:361-368) keep the open-coded pair to hold this refactor zero-churn — migration is opt-in, andsignal_pending_write()stayspubso no caller is forced to move.set_default_answerrearm (41bc51f2):mux/answers.rs:210now usesarm_writable()+incr!("h2.signal.writable.rearmed.default_answer"). Defence-in-depth for the backend-timeout path inmux/mod.rs:1378that synthesises 504/500/400 responses.PRIORITY_UPDATErearm (3269dd06):handle_priority_update_frame(mux/h2.rs:4349-4376) now rearmsself.readinessafter mutatingself.prioriser, so a reprioritised stream does not need an unrelated event to run under ET epoll. Observed post-PU drain latency O(100 µs) on HEAD.fead8eb0):handle_data_frame(mux/h2.rs:4126-4131) andhandle_headers_frame(mux/h2.rs:4258-4263) now pair the peerReady::WRITABLEinsert withsignal_pending_write(), mirroring the H1-backend pattern landed in040e305f. Forward-compat hardening — current Clever Cloud PaaS routing is frontal-H2/H1 ↔ backend-H1, but a cluster flipping to H2 upstream now has a working wake path.1de3faad):ready_incremental_by_urgencynow decrements mid-pass atmux/h2.rs:2481(inside the'outerloop) when a stream becomes ineligible (rst_sent, retired). Saves one unnecessary voluntary yield per pass on same-urgency-bucket peers after a stream RSTs or completes. Structural regression guard added for the saturating_sub path.e7920026): corrects theis_main_phase()/apply_incremental_rotationrationale ine2e/src/tests/h2_correctness_tests.rs:2346-2394so a future agent doesn't chase a dead hypothesis (kawa 0.6.8is_main_phase()returnstrueforTerminated; Round-4apply_incremental_rotationno longer returns the total).c0d03425): five new metric keys documented indoc/configure.md—h2.signal.writable.rearmed.{default_answer, priority_update, peer_data, peer_headers}(counters) andh2.streams.ready_incremental.by_urgency(gauge). Used as canary signals to verify rearm paths fire sanely in production.28fe3422,4e937df6,40c9c2af):e2e/src/tests/h2_priority_rearm_tests.rs(~800 LOC) runs four always-on tests —test_h2_backend_silent_triggers_504_within_back_timeout,test_h2_priority_update_rearms_writable,test_h2_backend_silent_headers_data_peer_signal,test_h2_mid_pass_rst_does_not_force_yield. The Fix C test uses a new HEADERS-then-delay-then-DATA mode onRawH2ResponseBackend(~65 LOC extension,4e937df6) to surface the H2-backend peer-rearm path deterministically.62747882): rustfmt wrap-break onsingle_read_h1_backend.Round 12 — E2E regression guards (commits
d60357fc..c1572502)d60357fc):fuzz_frame_parserandfuzz_hpack_decoder(10 s budget each; shell out tocargo +nightly fuzz run, require nightly + cargo-fuzz in PATH),e2e_session_stream_id_exhaustion_graceful(FIX-22 smoke),e2e_h2_flow_per_stream_idle_timeout(now deterministic after three fixes — split the TLS socket-read timeout, tighten the per-stream idle timeout belowSETTINGS_ACK_TIMEOUT, drop an over-specifiedno_backend_requestsassertion), andtest_h2_large_response_1gb_stress(~14 s on reference hardware; sustained flow-control + TLS write retry on a 1 GB body). Onlytest_h2spec_conformanceremains#[ignore]d — the test shells out to the externalh2specbinary (h2spec 2.0), and 18 of 145 checks currently fail, clustered in RFC 9113 §5.3 (self-dependent HEADERS), §6.9 (WINDOW_UPDATE boundary), §8.2.2 (uppercase / connection-specific /TE), §8.3 (pseudo-header uniqueness / ordering / allow-list), and §8.1.2.6 (content-length vs DATA reconciliation); tracked as#1209-h2spec-hardening(e2e/src/tests/tests.rs:3145-3150).c1572502): addstest_h2_large_gzipped_chunked_drains_fully(deterministic XorShift-128 seeded ~7.76 MB high-entropy payload, gzipped through the extendedChunkedFlushH1BackendwithContent-Encoding: gzip, Chromium-146 SETTINGS profile —INITIAL_WINDOW_SIZE=6_291_456,HEADER_TABLE_SIZE=65_536,MAX_CONCURRENT_STREAMS=1000,MAX_HEADER_LIST_SIZE=262_144,ENABLE_PUSH=0,NO_RFC7540_PRIORITIES=1; one-shot stream-0 WINDOW_UPDATE(15_663_105), per-stream WINDOW_UPDATE(sid, 32 KiB) cadence,priority: u=3, i; sha256 byte-identity within 8 s) andtest_h2_large_chunked_7mb_drains_fully(scale-only smoke, no gzip). Stream-0 WINDOW_UPDATE is issued once during the handshake only —H2FloodDetectorcaps stream-0 WUs atDEFAULT_MAX_WINDOW_UPDATE_STREAM0_PER_WINDOW = 100per sliding window (lib/src/protocol/mux/h2.rs:259, enforcement at:856); refreshing the connection window frame-by-frame would GOAWAY the connection.Round 13 — h2spec 145/145 (commits
8e07b311..50e01d2b)Closes the 18 remaining h2spec 2.0 conformance failures clustered in RFC 9113 §5.3.1, §6.9 / §6.9.1, §8.1.2, §8.1.2.1-3, §8.1.2.6.
test_h2spec_conformanceun-ignored; live run 145 tests, 145 passed, 0 skipped, 0 failed in 0.95 s.Two compounding gaps were masking every proxy-emitted RST_STREAM on malformed-stream rejections:
forcefully_terminate_answermissed the event bit (lib/src/protocol/mux/answers.rs:216-227). Under edge-triggered epoll,filter_interest() = event & interest. Settinginterestwithout raisingeventleft the filter at zero, sowritable()was never scheduled. Fix: migrate the final line fromreadiness.interest.insert(Ready::WRITABLE)toreadiness.arm_writable()— the canonical invariant-15 pair defined atlib/src/lib.rs:1010.reset_stream's callers evicted the stream beforewrite_streamscould serialise the RST bytes. Every one of the eightreset_streamcall sites is immediately followed byremove_dead_stream, which clearsself.streams.write_streamsiteratesself.priorities_bufbuilt fromself.streams.keys(), andH2BlockConverter::initializeis the only path that serialises RST bytes intokawa.out. With the stream already evicted,kawa.prepare(&mut converter)was never called — the RST bytes never reachedsocket_write_vectored. Clients saw only the SETTINGS-handshake WINDOW_UPDATE before the ~6.8 s session timeout closed the TLS connection.Fix — commit
8e07b311(fix(h2): emit RST_STREAM eagerly from reset_stream):ConnectionH2::enqueue_rst(wire_stream_id, error)on top of a free-function primitiveenqueue_rst_into(unit-testable without aConnectionH2<Front>fixture; five new tests cover the invariants in isolation). The helper is the single canonical entry point for proxy-emitted stream resets, and pins three co-invariants:self.rst_sent: HashSet<StreamId>— at most one queued RST per wire id;HashSet::insertshort-circuits on the already-present branch so the queue / counter / event bits stay in lock-step even under cascading error paths.self.total_rst_streams_queued— counter bump per fresh enqueue, policed atMAX_PENDING_RST_STREAMS = 200inflush_pending_control_frames(escalates toGOAWAY(ENHANCE_YOUR_CALM)on overflow). Orthogonal to the 500-emitted MadeYouReset lifetime cap atflood_detector.record_rst_emitted.Readiness::arm_writable— bothinterestandeventWRITABLE bits raised together for edge-triggered epoll.enqueue_rst: DATA-on-closed (h2.rs:1689—StreamClosed),refuse_stream_and_discard(h2.rs:3488— MCS / pool exhaustion), and the new call insidereset_streamitself.reset_streamsignature to accept the wireStreamIdas a parameter. Every one of the eight callers already has it in scope (data.stream_idat the DATA/CL paths; barestream_idat the HEADERS / WINDOW_UPDATE / PRIORITY paths), so the linear scan overself.streamsthe original scratch plan had in mind is unnecessary.forcefully_terminate_answertoReadiness::arm_writable— closes Gap A for themod.rs:1299-1303timeout path that calls the helper directly, not throughreset_stream. New metrich2.signal.writable.rearmed.forcefully_terminate_answer.finalize_writeagainst droppingReady::WRITABLEwhenpending_rst_streamsorflow_control.pending_window_updatesare still non-empty.flush_pending_control_framesis gated onexpect_write.is_none(), so when a prior partial write deferred the Phase-3 flush the queues stay non-empty afterexpect_writedrains — without this rearm the queued RST would stall until an unrelated event re-triggered writable. New metrich2.signal.writable.rearmed.control_queue.Five unit tests cover the new invariants:
test_enqueue_rst_into_populates_queue_and_dedupe,test_enqueue_rst_into_bumps_total_for_distinct_ids,test_enqueue_rst_into_arms_writable_in_invariant_15_form,test_enqueue_rst_into_dedupe_does_not_rearm_writable,test_forcefully_terminate_answer_arms_event_and_interest.Test tighten — commit
2e977aba(test(e2e): un-ignore test_h2spec_conformance and tighten h2-security asserts):test_h2spec_conformance; replace its.expect()on theh2specbinary with a graceful-skip so CI legs without the install step still finish the rest of the e2e suite.|| frames.is_empty()escape clause now that sozu emits RST_STREAM deterministically for every violation. Sites covered:h2_security_tests.rs:586, 664, 814, 883, 941, 1015, 1098, 2887, 2957 (kept !write_ok), 3025 (kept !write_ok),h2_security_header_injection.rs:115, 162, 238, 442, 535 (kept !wrote), 634,h2_correctness_tests.rs:96.h2_security_tests.rs:193(HPACK bomb — flood),:503/:512(connection preface corruption — connection-scope),:750(authority/host normalized 200 is RFC-compliant acceptance),:3112(DATA flood with padding).content_length_format_fuzzing(h2_security_tests.rs:1393): the three clearly dangerous CL values ("0,","0,0","-1") now require explicit rejection; silent close stays accepted for the whitespace/locale variants where rejection policy is still evolving.Docs + CI — commit
8a984391(docs(h2,ci): refresh LIFECYCLE RST path, CHANGELOG entry, install h2spec in CI):lib/src/protocol/mux/LIFECYCLE.md§8.2 describes the unifiedenqueue_rst→pending_rst_streams→flush_pending_control_framespath, distinguishingrst_sentdedupe vstotal_rst_streams_queuedqueued cap (200) vsrecord_rst_emittedMadeYouReset lifetime cap (500).doc/h2_mux_internals.mdmirrors the refresh on theflush_pending_control_framesPhase-3 flush.CHANGELOG.mdgains a ⛑️ Fixed entry underfeat/h2-mux - Unreleased..github/workflows/ci.ymlinstalls the prebuilth2specv2.6.0 binary fromgithub.com/summerwind/h2spec/releasesin every matrix leg beforecargo test, so the now-un-ignoredtest_h2spec_conformanceruns cleanly without a Go toolchain bootstrap (the test itself still gracefully skips on missing binary — belt-and-suspenders).Validation:
test_h2spec_conformance→ 145/145/0/0 in 0.95 s.cargo test -p sozu-e2e --release h2_→ 189/189 in 308 s.cargo test -p sozu-lib --lib -- protocol::mux→ 416 pass (411 existing + 5 new).cargo clippy --all-targets --locked -- -D warnings→ 0 warnings.cargo +nightly fmt --all -- --check→ clean.cargo test -p sozu-e2ewith-max_total_time=10):fuzz_frame_parser195,135 runs andfuzz_hpack_decoder20,720 runs, 0 crashes each.cargo test --workspace --locked) surfaced a single known H2 flood-family flake ontest_h2_rapid_reset_triggers_goaway(Broken piperace between the detector firing and the client's write loop finishing) — passes 5/5 in isolation oncargo test test_h2_rapid_reset_triggers_goaway, not a regression; tracked alongside thesettings_flood/ping_floodsiblings that share the same cause.Net diff of Round 13: +437/-96 lines across 10 files (LIFECYCLE.md, h2_mux_internals.md, CHANGELOG.md, ci.yml, h2.rs, answers.rs, plus the four e2e test files).
Round 14 — CI flake stabilisation (commit
1f928981)After Round 13 the feat/h2-mux CI matrix was still intermittently red — not because of the H2 mux changes but because of pre-existing test-harness race conditions that had been latent on the branch since Round 12. All affected tests passed reliably on local runs and the Codex cross-check reproduced the same local-pass / CI-fail split.
What CI actually showed (audit of failing runs 24896721675, 24896722873, 24897750687, 24897754034, 24905690253, 24909140723, 24909142701):
test_h2_large_chunked_7mb_drains_fullye2e/src/tests/h2_utils.rs:968—Result::unwrap() on Err(BrokenPipe)duringstream.flush()after a per-streamWINDOW_UPDATEwritetest_h2_large_gzipped_chunked_drains_fullytest_h2_ping_flood_triggers_goawayState::Fail; write loop sawBroken pipeafter ~N/200 frames, subsequent read picked up 0 framestest_h2_settings_flood_triggers_goawayBroken pipe+ zero-frame shapetest_h2_rapid_reset_triggers_goawaycargo test --workspace --lockedon 50e01d2e2e_session_router_connect_failure_no_leakState::Fail— backend didn't reach expected state under loade2e_session_stream_id_exhaustion_gracefulState::Fail— third smoke request returned 503 instead of 200fuzz_frame_parser/fuzz_hpack_decoder024243e2(CI nightly + cargo-fuzz install)In parallel, the CI workers' stderr showed sustained
ERROR MAXCONN: max number of session connection reached, flushing the accept queue, repeatedERROR 810-PANIC: error accepting TCPListen sockets: IoError, andERROR H1-IDLE-ZOMBIE-METRICS— strong signals that the CI runner was near its file-descriptor limit and that some tests were accumulating slow-to-reap connections. That backdrop made the real root cause easier to see: whenever sozu legitimately decided to close a connection (end-of-response, flood detected, idle teardown), the test client's next write could race intoBrokenPipeterritory and either panic or break out of a loop too early to read the GOAWAY.Codex cross-check (
codex exec --sandbox read-only, gpt-5 default) independently identified the same two root causes and recommended the same structural fix direction: batched writes for the flood tests, and END_STREAM-before-WU ordering plus graceful BrokenPipe tolerance in the streaming drain helper. There is no production mux regression explaining either class.Fix — commit
1f928981(test(e2e): stabilise drain helper + flood tests against peer-close races):drain_h2_stream_streamingine2e/src/tests/h2_utils.rs:END_STREAMon each DATA frame before emitting the WINDOW_UPDATE refresh. The final frame carries END_STREAM by definition, so refreshing credit afterwards was always pointless and raced sozu's legitimate stream close.BrokenPipe/ConnectionReset/ConnectionAborted/NotConnected/UnexpectedEofon the WU flush: break the read loop gracefully and let the caller's body-integrity assertions (body_bytes,sha256) be the source of truth. Any other error still panics loudly.Flood tests in
e2e/src/tests/h2_tests.rs(test_h2_ping_flood_triggers_goaway,test_h2_settings_flood_triggers_goaway,test_h2_rapid_reset_triggers_goaway): batch the entire flood payload into onewrite_all+flush, sized at threshold + 5 frames (105 pings vs threshold 100, 55 settings vs 50, 105 HEADERS+RST pairs vs 100). By the time the test switches to reading, sozu has seen the full flood — there is no per-frame write race left to lose.test_h2_continuation_flood_triggers_goawayalready used the batched pattern (pre-existing) and did not need a change.No test was ignored, disabled, or loosened. The flood tests still assert
contains_goaway_with_error(ENHANCE_YOUR_CALM); the large-body tests still assertbody_bytes == gzipped_lenandsha256 == expected_hex. The fix removes the race between the test's synthetic work and sozu's legitimate peer-close without affecting what we assert on the wire.Local validation (release mode, 3 iterations each via
repeat_until_error_or):test_h2_ping_flood_triggers_goawaytest_h2_settings_flood_triggers_goawaytest_h2_rapid_reset_triggers_goawaytest_h2_continuation_flood_triggers_goawaytest_h2_large_gzipped_chunked_drains_fullytest_h2_large_chunked_7mb_drains_fullycargo +nightly fmt --all -- --checkandcargo clippy --all-targets --locked -- -D warningsboth clean. CI watch: run24914367604.Test plan
cargo test --workspace— all tests pass (222 mux unit tests, +3 new MadeYouReset cases in Round 10, +4Readiness::arm_writablepair tests in Round 11; Round 10b and Round 12 add further unit + e2e coverage — see per-round bullets)cargo clippy --workspace --all-features— no warningscargo +nightly fmt— formattedtest_h2spec_conformanceshells out to the externalh2specbinary. Round 13 lands the fix; the test is now un-ignored and passes 145/145/0/0 in 0.95 s on the branch. CI installs the prebuilth2specv2.6.0 binary in each matrix leg; the test still gracefully skips when the binary is missing, so legs without the install step do not block the suite.:status/1xx assertions, backend-disconnect stress, large-asset +ChunkedFlushH1Backend; Round 12 un-ignores five previously gated tests and adds two 7.7 MB gzipped-truncation guards; Round 13 un-ignorestest_h2spec_conformanceand tightens 17 permissive stream-scope asserts + 2 partial). No e2e tests remain#[ignore]d on this branch.fmt --checkclean,clippy -D warningsclean. No test ignored, disabled, or loosened — wire assertions (GOAWAY(ENHANCE_YOUR_CALM), body sha256,body_bytes == expected) preserved.curl --http2against production-like configCredits
Original mux architecture: @Edemolis (Eloi Demolis) —
mux_v1branchH2↔H2 SETTINGS & H1→H2 upgrade: @hcaumeil (Helian Caumeil)
Earlier H2 prototype: Geoffroy Couprie (
lib/src/protocol/h2/)Closes
Closes #99, #540, #543, #858, #888, #899, #978, #979, #980, #1145, #1217