Repository navigation
feat: RAII splice(2) zero-copy for TCP sessions - #1194
Merged
Merged
Conversation
llenotre
approved these changes
Mar 23, 2026
FlorentinDUBOIS
force-pushed
the
feat/tcp-splicing
branch
3 times, most recently
from
April 29, 2026 10:05
10891cb to
67da9c7
Compare
Replace the bare splice helper with a RAII primitive suitable for zero-copy TCP forwarding through the Pipe protocol. - New SplicePipe struct owns two pipe2(O_NONBLOCK | O_CLOEXEC) pairs (in_pipe for frontend->backend, out_pipe for backend->frontend) plus per-direction pending byte counters that the Pipe state machine will use to keep half-closed sessions alive while data is still in kernel. - Drop impl closes all four fds; manual cleanup is no longer required. - splice_in / splice_out now return (usize, SocketResult), matching the convention used elsewhere in lib/src/socket. Transfer size moves from 2048 B per syscall to a full 64 KiB pipe, and SPLICE_F_MOVE is added so the kernel can move pages instead of copying when the source supports it. - The cfg gate becomes all(target_os = "linux", feature = "splice") to prevent accidental enablement on platforms that lack pipe2(2)/splice(2). Module visibility is bumped to pub(crate) so protocol::pipe can use it in a follow-up commit. - Replace the legacy zerocopy two-listener test with splice_roundtrip, which exercises both splice_in and splice_out against a single TcpStream. The helper is unused in this commit; the #[allow(dead_code)] markers on SplicePipe, SplicePipe::new, splice_in, and splice_out are dropped when Pipe wires it in next. Signed-off-by: Florentin Dubois <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
Wire SplicePipe into the buffered Pipe state machine. When the listener is Protocol::TCP and the splice feature is enabled, the four I/O methods take a zero-copy fast path that moves bytes between the frontend socket, two kernel pipes, and the backend socket without ever touching the userspace buffer. The splice path mirrors the buffered path's ConnectionStatus transitions and metric emissions exactly so observability and the check_connections state machine behave the same with or without the feature flag. Two new helpers, splice_in_pending and splice_out_pending, expose the kernel-pipe pending byte counts as additional in-flight predicates: check_connections counts them as request_is_inflight / response_is_inflight, and backend_hup keeps the session alive while out_pipe_pending > 0 so the kernel drains to the frontend before close. This mirrors HAProxy's design: a single half-close abstraction (ConnectionStatus on Sozu, CF_SHUTR/CF_SHUTW on HAProxy) observed by all I/O paths, with pipe-drain bytes counted as in-flight by the same predicate that handles userspace buffers. The splice_pipe field is cfg-gated and initialised lazily in Pipe::new only when Protocol::TCP is selected; WebSocket-after-upgrade paths (HTTP, HTTPS) skip allocation. If pipe2(2) fails (typically RLIMIT_NOFILE pressure) Pipe falls back to the buffered path transparently. bin/Cargo.toml gains splice = ["sozu-lib/splice"] so the binary can forward the feature flag, and the #[allow(dead_code)] markers on SplicePipe, SplicePipe::new, splice_in, and splice_out are dropped now that they have callers. Signed-off-by: Florentin Dubois <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
Add three e2e tests in tcp_tests.rs that exercise scenarios the existing TCP suite does not cover and that double as splice-vs-buffered equivalence checks: - test_tcp_proxy_concurrent_async: N concurrent clients across N backends, exercising one SplicePipe per session in parallel from the single-threaded event loop. - test_tcp_proxy_multiple_requests: many request/response cycles on one persistent TCP connection, exercising the SplicePipe lifecycle across successive splice_in/splice_out calls without recreating pipes. - test_tcp_soft_stop_with_active_sessions: graceful shutdown while a TCP session is mid-flight, validating that pending kernel-pipe bytes drain rather than leaking on close. The tests reuse tcp_tests.rs's existing helpers (setup_tcp_test, raw_connect, raw_read_all, bind_std_listener, repeat_until_error_or) and pass identically with or without the splice feature, so they serve as feature-flag equivalence checks. e2e/Cargo.toml grows a [features] table that forwards splice to sozu-lib; the existing CI test job runs `cargo test --all-features --locked --verbose`, which now exercises the splice path end-to-end without needing a separate CI step. CHANGELOG.md gains an [Unreleased] Added entry for the feature, and doc/getting_started.md updates the splice feature row from `lib` to `lib, bin` and notes the Linux-only constraint plus the 64 KiB kernel-pipe per session per direction. Signed-off-by: Florentin Dubois <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
Make the splice(2) kernel-pipe capacity per direction configurable via a new `splice_pipe_capacity_bytes` field on ServerConfig, instead of the hard-coded 64 KiB constant. The override flows through the same path as the existing `basic_auth_max_credential_bytes` knob: declared in `command/src/command.proto` (ServerConfig field 22), wired through `FileConfig`, the `ConfigBuilder` mapper, the runtime `Config`, and the proto round-trip via `From<&Config> for ServerConfig`. Linux-only storage at the lib layer: a `OnceLock<usize>` in `lib/src/splice.rs` populated once per worker boot from `Server::try_new_from_config` (cfg-gated), with a setter that no-ops on `0` so an explicit zero does not collapse the pipe to PAGE_SIZE. `SplicePipe::new` now applies the configured capacity via `fcntl(F_SETPIPE_SZ)` on each pipe and reads the realised value back with `fcntl(F_GETPIPE_SZ)`, storing the smaller of the two sizes in a new `capacity` field. This handles the kernel's behaviour: it rounds up to PAGE_SIZE and clamps at `/proc/sys/fs/pipe-max-size` (default 1 MiB unprivileged; CAP_SYS_RESOURCE goes higher). On `F_SETPIPE_SZ` failure the kernel keeps the previous capacity (typically 64 KiB), the failure is logged at `warn!`, and SplicePipe continues with that realised value — splice still works, just at the kernel default. `splice_in` gains a `len: usize` parameter so callers thread the realised capacity through; pipe.rs reads `splice_pipe.capacity` for both the per-call `len` and the "pipe is full" backpressure check (replaces the deleted `SPLICE_PIPE_CAPACITY` const). CHANGELOG, doc/getting_started.md (feature-flag table), and doc/configure.md (global parameters table) updated to document the new knob and its kernel-side limits. Signed-off-by: Florentin Dubois <[email protected]> Signed-off-by: Florentin Dubois <[email protected]>
FlorentinDUBOIS
force-pushed
the
feat/tcp-splicing
branch
from
April 29, 2026 11:26
67da9c7 to
9467b2c
Compare
FlorentinDUBOIS
added a commit
that referenced
this pull request
May 2, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks — `## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs #1162, #1191, #1192, #1193, #1194, #1196, #1202, #1223), `## feat/answer-templates-rewrite-auth - Unreleased` (answer templates, URL rewrite, basic auth), and `## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR #1209). All three feature stacks are on `main`; the per-branch dividers were release- engineering staging that no longer reflects current state. Changes: - Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and `## feat/h2-mux - Unreleased` dividers; their bodies now appear under `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`, `### Added — H2 multiplexer (PR #1209)`). - Promote the breaking changes (proto-tag renumbers, dashboard metric renames, `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of the section so operators see them first. - Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed, ✍️ → Changed, 📚 → Documentation, 🤖 → CI,⚠️ → Behaviour-affecting). Per- commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they don't conflict with Keep-a-Changelog vocabulary. - Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim; they are released and immutable. Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple `### Added`/`### Changed`/`### Fixed` sub-blocks into one each per Keep-a-Changelog strict shape; this commit is the structural collapse only. Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse). Signed-off-by: Florentin Dubois <[email protected]>
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
feat: RAII splice(2) zero-copy for TCP sessions
jrcribb
pushed a commit
to jrcribb/sozu
that referenced
this pull request
Aug 10, 2026
The CHANGELOG previously carried three concurrent Unreleased blocks — `## [Unreleased]` (main-scoped post-1.1.1 fixes from PRs sozu-proxy#1162, sozu-proxy#1191, sozu-proxy#1192, sozu-proxy#1193, sozu-proxy#1194, sozu-proxy#1196, sozu-proxy#1202, sozu-proxy#1223), `## feat/answer-templates-rewrite-auth - Unreleased` (answer templates, URL rewrite, basic auth), and `## feat/h2-mux - Unreleased` (the H2 multiplexer rewrite from PR sozu-proxy#1209). All three feature stacks are on `main`; the per-branch dividers were release- engineering staging that no longer reflects current state. Changes: - Drop the `## feat/answer-templates-rewrite-auth - Unreleased` and `## feat/h2-mux - Unreleased` dividers; their bodies now appear under `## [Unreleased]` with provenance markers (`### Added — Answer templates / ...`, `### Added — H2 multiplexer (PR sozu-proxy#1209)`). - Promote the breaking changes (proto-tag renumbers, dashboard metric renames, `http.errors` labelling, pattern-trie regex anchoring, empty-val del-header semantic, sub-16393 `buffer_size` rejection, cipher-list constant rename) to a top-level `### Breaking changes (v1.1.x → v2.0.0)` paragraph at the top of the section so operators see them first. - Drop emoji from top-level subheaders (🌟 → Added, 🔄 → Changed, ⛑️ → Fixed, ✍️ → Changed, 📚 → Documentation, 🤖 → CI,⚠️ → Behaviour-affecting). Per- commit-log subsection at depth ≥ 4 keeps minor emoji ornaments where they don't conflict with Keep-a-Changelog vocabulary. - Preserve historical release entries (`## 1.1.1`, `## 1.1.0`, …) verbatim; they are released and immutable. Net effect: a single `## [Unreleased]` block ready for the v2.0.0 release-cut in §3.4.c of `tasks/todo.md`. Future passes can de-duplicate the multiple `### Added`/`### Changed`/`### Fixed` sub-blocks into one each per Keep-a-Changelog strict shape; this commit is the structural collapse only. Refs: tasks/todo.md §3.1.a; codex M12 amendment (3-way not 2-way collapse). 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.
Summary
Zero-copy TCP forwarding for
Protocol::TCPlisteners via Linuxsplice(2), behind asplicefeature flag (Linux only). Rebased onto currentmain(e3fa1631, post-h2-mux) as four logical commits:feat(splice): RAII rewrite with SplicePipe— owns twopipe2(O_NONBLOCK | O_CLOEXEC)pairs plus per-direction pending-byte counters;Dropcloses all four fds.splice_in/splice_outreturn(usize, SocketResult)withSPLICE_F_NONBLOCK | SPLICE_F_MOVE.feat(tcp): integrate splice(2) into Pipe protocol— splice fast path inreadable/writable/backend_writable/backend_readablebehindcfg(all(target_os = "linux", feature = "splice")). Allocated lazily inPipe::newonly whenProtocol::TCP.bin/Cargo.tomlforwardssplice = ["sozu-lib/splice"].test(e2e): TCP splice coverage + docs—e2e/Cargo.tomlforwards the feature; three new tests ine2e/src/tests/tcp_tests.rs;CHANGELOG.mdanddoc/getting_started.mdupdated.feat(splice): operator-tunable kernel-pipe capacity— newsplice_pipe_capacity_bytesfield onServerConfig(proto + Rust), wired throughFileConfig→Config→ServerConfig.OnceLock-backed override (mirrorsbasic_auth_max_credential_bytes), installed once per worker boot fromServer::try_new_from_config.SplicePipe::newapplies the requested size viafcntl(F_SETPIPE_SZ)per pipe, then reads back the realised value viafcntl(F_GETPIPE_SZ)(the kernel rounds up to PAGE_SIZE and clamps at/proc/sys/fs/pipe-max-size). The realised capacity drives both the per-callsplice_inlength and the "pipe is full" backpressure check. Failures degrade gracefully — the kernel keeps the previous capacity, awarn!is logged, splice still works.Half-close design (the load-bearing choice)
Sōzu already has a per-session
ConnectionStatus4-state machine and a 4×4 transition table inPipe::check_connections. The splice path observes the same state machine and extends the in-flight predicates within_pipe_pending > 0/out_pipe_pending > 0.backend_hupkeeps the session alive whileout_pipe_pending > 0so the kernel pipe drains to the frontend before close. This mirrors HAProxy's design: a single per-channel half-close abstraction (CF_SHUTR/CF_SHUTW) observed by all I/O paths, with pipe-drain bytes counted as in-flight by the same predicate that handles userspace buffers. The earlier review-fix commit was patching this in against the older, thinnerpipe.rs; the modernpipe.rsalready carries the state machine, so the splice path just plugs in.Coverage
Three net-new tests on top of the existing TCP suite (
tcp_tests::test_tcp_proxy_basic/_large_payload/_half_close/_backend_connection_failure/_proxy_protocol_v2):test_tcp_proxy_concurrent_async— N concurrent clients × N backends round-trip in parallel (oneSplicePipeper session).test_tcp_proxy_multiple_requests— many request/response cycles on one persistent connection (SplicePipelifecycle across successive splices).test_tcp_soft_stop_with_active_sessions— soft-stop with a TCP session mid-flight (drain semantics).All three pass identically with and without
--features splice, so they double as feature-flag equivalence checks.Test plan
cargo build --all-features --locked(workspace)cargo +nightly fmt --all -- --checkcargo clippy --workspace --all-features --locked --all-targets -- -D warningscargo test -p sozu-lib --features splice --locked --lib(449/449 incl.splice::tests::splice_roundtrip)cargo test -p sozu-lib --locked --lib(448/448, no regression without the feature)cargo test -p sozu-e2e --features splice --locked tcp_tests::test_tcp_proxy_concurrent_async tcp_tests::test_tcp_proxy_multiple_requests tcp_tests::test_tcp_soft_stop_with_active_sessions(3/3)--features splice(3/3, equivalence confirmed)Operator knob
Notes
ci.ymlchange: the existingcargo test --locked --all-featuresjob already enablesspliceonce it is exposed in the workspace[features], so a duplicate splice-only step would only add CI cost.pipe2(2)andsplice(2)are Linux syscalls). FreeBSD'ssplicehas incompatible semantics; macOS lacks the syscall.