Skip to content

feat: RAII splice(2) zero-copy for TCP sessions - #1194

Merged
FlorentinDUBOIS merged 4 commits into
mainfrom
feat/tcp-splicing
Apr 29, 2026
Merged

FlorentinDUBOIS merged 4 commits into
mainfrom
feat/tcp-splicing

Conversation

@FlorentinDUBOIS

@FlorentinDUBOIS FlorentinDUBOIS commented Mar 8, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Zero-copy TCP forwarding for Protocol::TCP listeners via Linux splice(2), behind a splice feature flag (Linux only). Rebased onto current main (e3fa1631, post-h2-mux) as four logical commits:

  • feat(splice): RAII rewrite with SplicePipe — owns two pipe2(O_NONBLOCK | O_CLOEXEC) pairs plus per-direction pending-byte counters; Drop closes all four fds. splice_in / splice_out return (usize, SocketResult) with SPLICE_F_NONBLOCK | SPLICE_F_MOVE.
  • feat(tcp): integrate splice(2) into Pipe protocol — splice fast path in readable / writable / backend_writable / backend_readable behind cfg(all(target_os = "linux", feature = "splice")). Allocated lazily in Pipe::new only when Protocol::TCP. bin/Cargo.toml forwards splice = ["sozu-lib/splice"].
  • test(e2e): TCP splice coverage + docs — e2e/Cargo.toml forwards the feature; three new tests in e2e/src/tests/tcp_tests.rs; CHANGELOG.md and doc/getting_started.md updated.
  • feat(splice): operator-tunable kernel-pipe capacity — new splice_pipe_capacity_bytes field on ServerConfig (proto + Rust), wired through FileConfig → Config → ServerConfig. OnceLock-backed override (mirrors basic_auth_max_credential_bytes), installed once per worker boot from Server::try_new_from_config. SplicePipe::new applies the requested size via fcntl(F_SETPIPE_SZ) per pipe, then reads back the realised value via fcntl(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-call splice_in length and the "pipe is full" backpressure check. Failures degrade gracefully — the kernel keeps the previous capacity, a warn! is logged, splice still works.

Half-close design (the load-bearing choice)

Sōzu already has a per-session ConnectionStatus 4-state machine and a 4×4 transition table in Pipe::check_connections. The splice path observes the same state machine and extends the in-flight predicates with in_pipe_pending > 0 / out_pipe_pending > 0. backend_hup keeps the session alive while out_pipe_pending > 0 so 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, thinner pipe.rs; the modern pipe.rs already 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 (one SplicePipe per session).
  • test_tcp_proxy_multiple_requests — many request/response cycles on one persistent connection (SplicePipe lifecycle 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 -- --check
  • cargo clippy --workspace --all-features --locked --all-targets -- -D warnings
  • cargo 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)
  • Same three e2e tests pass without --features splice (3/3, equivalence confirmed)

Operator knob

# Optional. Linux-only. Requires `splice` cargo feature.
# None / unset → kernel default (64 KiB per direction per session).
# Kernel rounds up to PAGE_SIZE and clamps at /proc/sys/fs/pipe-max-size.
splice_pipe_capacity_bytes = 262144   # 256 KiB

Notes

  • No ci.yml change: the existing cargo test --locked --all-features job already enables splice once it is exposed in the workspace [features], so a duplicate splice-only step would only add CI cost.
  • All commits GPG-signed and signed-off.
  • Linux-only by design (pipe2(2) and splice(2) are Linux syscalls). FreeBSD's splice has incompatible semantics; macOS lacks the syscall.

@FlorentinDUBOIS
FlorentinDUBOIS force-pushed the feat/tcp-splicing branch 3 times, most recently from 10891cb to 67da9c7 Compare April 29, 2026 10:05
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
FlorentinDUBOIS merged commit f243296 into main Apr 29, 2026
28 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the feat/tcp-splicing branch April 29, 2026 11:56
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants