Skip to content

Initialize TCP keepalive and no-delay socket options - #541

Merged
fcostaoliveira merged 13 commits into
masterfrom
fix/socket-options
Sep 21, 2026
Merged

fcostaoliveira merged 13 commits into
masterfrom
fix/socket-options

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

TCP connections pass an uninitialized integer to SO_KEEPALIVE and TCP_NODELAY, so either option can silently remain disabled. Initialize both with a dedicated constant before opening the connection; keep the fcntl flags separate. This also applies to TLS and reconnects.

Add a make check regression test that inspects real socket options through the production connection setup. It covers IPv4/IPv6, plain/TLS socket setup, Unix nonblocking setup, disconnect cleanup, and two reconnects per configuration. Checks remain active with NDEBUG.

Validation:

  • Old source compiled with diagnostic -ftrivial-auto-var-init=zero fails all 24 TCP option assertions; the fixed source passes. An ordinary unfixed build can happen to pass because an uninitialized integer can be nonzero; this diagnostic makes the regression reproducible.
  • Optimized make check: 3/3 passing; TLS-disabled, ASAN+UBSan+LSan, TSAN, and real OpenSSL 1.0.2u builds also pass the new test. Every changed executable runtime line is covered (3/3).
  • make format and make format-check pass.
  • Full local standalone/cluster × plain/TLS matrix: 896 passed, 468 expected skips, zero failures. The final standalone TLS run includes test-routing fix Keep MONITOR reproducibility tests on the configured Redis endpoint #543 (now merged into master) and a private authentication adapter for isolated password-protected fixtures; it is combined validation, not an unmodified checkout run. The adapter preserves explicit credentials and supplies URI credentials inside the URI. An independent CLI/URI authentication cleanup defect found during validation is fixed separately. Original failing logs are retained. macOS CI runs make check across four SSL/libevent configurations.

Fixes #534. This verifies socket configuration directly; it does not claim a new measurement of the reporter's TLS latency plateau.

Enabling the new socket tests on macOS exposed a pre-existing CI dependency mismatch: Homebrew libevent used default OpenSSL 3 while memtier selected 1.1 or another 3.0 installation. LLDB showed the 1.1-linked test crashing inside OpenSSL 3's SSL_CTX_free. Build libevent 2.1.13 against each selected SSL and verify transitive library prefixes. All four macOS configurations passed actual unit tests at b00b7e0, including the legacy 1.0.2 build.

The no-TLS CI job runs both normal Prometheus configurations first, then recompiles only the socket test with diagnostic zero initialization. Production objects retain their normal flags while reintroducing the original uninitialized argument fails deterministically.

Release-note text: Fixed uninitialized TCP socket options so keepalive and TCP_NODELAY are consistently enabled, including TLS and reconnects. This can remove artificial latency and change benchmark results compared with affected builds.

The macOS matrix also tests the native Homebrew libevent/default OpenSSL 3 packages. All four macOS variants share the transitive link checker; the known-good legacy libevent 2.1.12 version is retained to avoid an unrelated upgrade.

Updated onto master 830ddbe. The socket fixture now uses a real client manager and deliberately dispatches Unix connection callbacks on each reconnect with a zero-depth pipeline. Local unit checks and ASAN+LSAN+UBSan with NDEBUG pass; the NULL-manager negative control fails UBSan on that same dispatched callback. The latest CI run checks the combined branch.


Note

Medium Risk
Changes live TCP/TLS connection setup in shard_connection, which can alter latency and benchmark numbers; scope is limited to socket option initialization plus tests and CI hardening.

Overview
Fixes a bug in shard_connection::setup_socket where SO_KEEPALIVE and TCP_NODELAY were passed an uninitialized flags value, so those options could stay off. Both now use an explicit enabled = 1; fcntl non-blocking setup stays on its own flags path.

Adds socket_options_test to make check: it drives the real connection path (IPv4/IPv6, plain/TLS when built, Unix, reconnects) and asserts keepalive, Nagle off, linger, non-blocking, and cleanup. The no-TLS CI job also rebuilds that test with -ftrivial-auto-var-init=zero so the old bug fails deterministically without changing normal binaries.

macOS CI is tightened: libevent is built or selected to match each OpenSSL matrix entry, make check runs on all macOS jobs, and check-macos-tls-links.sh replaces inline otool checks so mixed Homebrew SSL/libevent ABIs are caught.

Reviewed by Cursor Bugbot for commit f8f4050. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

github-actions Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this — the core fix is clearly right. flags was never assigned before those two setsockopt() calls and the surrounding code leaves no doubt both were meant to be on, so there's no less-breaking alternative to weigh here the way there was in #212. Results will shift for anyone whose build happened to get a zero, and the release-note text in the description covers that. A few questions on the rest.

ci.yml — dropping continue-on-error: true from build-macos is the one line in here that can turn master red for reasons that have nothing to do with socket options, and it arrives alongside a new "3" matrix leg and a from-source libevent build. Was promoting that job to required intentional, or a side effect of wanting make check to run there? If intentional I think it belongs on its own, so a Homebrew-side breakage is obviously not this fix regressing.

socket_options_test.cpp, check_connections() — benchmark_config config = {} with six fields set by hand builds a config the binary can't actually produce: config_init_defaults() rewrites pipeline = 0 to 1, and a zero connection_stage_timeout means "operator disabled" rather than the real 30s default. Why not run the struct through config_init_defaults() and override from there, so the test doesn't quietly drift as fields get added?

socket_options_test.cpp, #define socket recording_socket — that applies to every header shard_connection.cpp pulls in transitively below it, not just the one call site. It works on what CI builds today; I may be wrong about the next SDK. Did you consider lifting the option setup out of setup_socket() into a small function the test calls directly? That would also let the filter-out $(memtier_benchmark_OBJECTS) in Makefile.am go away and keep make check from needing a full link of the binary.

socket_options_test.cpp, stubs — is_redis_protocol() is reimplemented here and will silently disagree with the real one if a protocol is ever added. Counting tests/fuzz/fuzz_stubs.cpp these helpers now live in three places — is a shared stub TU feasible, or is the object_generator conflict you note in the comment what blocks it?

The deterministic -ftrivial-auto-var-init=zero rebuild is a nice guard against someone reintroducing this later — worth keeping regardless of the above.

Nitpicking: Makefile.am reaching into automake's $(memtier_benchmark_OBJECTS) and filtering by per-target object prefix works, but it ties make check to the object-naming scheme; it'd break loudly rather than silently, so not blocking.

I'd mainly want the continue-on-error question answered and the test config built from the real defaults; the rest is take-it-or-leave-it.

(would file this as a comment, not a formal block)

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed in c3c4831: boolean socket options now require nonzero, supporting BSD/macOS bitmask returns; added SO_LINGER enabled/zero-timeout checks; documented the system-header ordering, main-owned helper stubs and Automake object prefixes.

The regression limitation is real: an uninitialized value can happen to be nonzero, so an ordinary unfixed build is not guaranteed to fail. The old-code diagnostic uses -ftrivial-auto-var-init=zero and fails all 24 TCP-option checks; the fixed code passes. The test inspects actual kernel options rather than replacing setsockopt. I will state this explicitly in the PR description.

Keeping real production objects gives UBSan the actual client RTTI and avoids fake types or sanitizer exclusions. A shared library conversion would broaden this socket fix substantially; the object filter is documented and a mismatch fails at link time.

The single NONBLOCK event-loop call drains all active callbacks, including libevent's deferred bufferevent finalizer. In this fixture no connection callbacks are dispatched before disconnect and no additional references are retained. The finalizer closes the descriptor on both socket and TLS paths. This was checked against libevent 2.1.12 source and passes sanitizer, plain/TLS and legacy OpenSSL tests locally.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Added a committed CI gate for the original uninitialized-read regression: the existing no-TLS job now sets CXXFLAGS=-g -O2 -ftrivial-auto-var-init=zero for both Prometheus configurations before running make check. This is a test-only build, not a release artifact. The old-code failure is now enforced by CI rather than only described as a local diagnostic.

The macOS dependency change is required to run the new test there: enabling make check exposed SIGBUS in both Homebrew-linked variants, and LLDB showed the OpenSSL 1.1-linked executable crashing inside OpenSSL 3's SSL_CTX_free. The existing Homebrew libevent was built against a different SSL installation. The change keeps libevent at 2.1.13 and aligns its dependency; all three macOS jobs now pass. The PR description includes this cause, and the dependency fix is its own commit for review/bisect.

The socket recorder avoids modifying the production API or relying on nonportable descriptor enumeration. Its header-order constraint is documented and the actual test now runs on Linux and macOS SSL variants. The purity audit only covers the unconditional metrics layer (tests/run_local_gate.sh); its existing small link is unchanged. The socket test has a separately documented full-object link to retain real UBSan RTTI.

Changed the allocation-failure path to clean up and return, allowing Unix-directory cleanup. There are no other active connection callbacks or threads opening descriptors between disconnect and the EBADF check in this fixture.

I kept existing setsockopt error-handling semantics in this focused runtime fix; changing release-build failure/retry behavior would need its own failure-injection coverage. Added release-note wording to the PR description: enabling TCP_NODELAY consistently can remove artificial latency and change benchmark results compared with affected builds.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Updated the diagnostic build to keep both normal no-TLS configurations unchanged and then rebuild only the socket test translation unit with zero initialization. This catches the original bug without zeroing unrelated production objects. The metrics-only build comment is now scoped directly to that target.

Restored native packaged coverage with an additional default OpenSSL 3/Homebrew libevent macOS cell. All four macOS variants now use the same transitive link checker. The legacy 1.0.2 job intentionally retains its already-tested libevent 2.1.12 build; the repaired 1.1/3.0 jobs retain 2.1.13, so this repair changes dependency alignment without also upgrading the legacy dependency.

Local normal and diagnostic socket tests pass. Twelve independent checker fixtures cover legacy/native prefixes and foreign/missing dependencies. Final remote checks are running. Full local validation results will be posted before calling this ready.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Removed continue-on-error from the macOS job, so its unit and linkage checks now gate CI. The preceding exact-head run already passed all four variants, including native Homebrew (3): https://github.com/redis/memtier_benchmark/actions/runs/35588389383 . That job's actual otool output and successful prefix check confirm the opt-prefix match; the legacy job also passes the shared prefix checker.

The diagnostic step now passes only SOCKET_TEST_EXTRA_CXXFLAGS; its normal flags remain defined once in Makefile.am. Detection in configure is unnecessary for this explicit diagnostic step on the known ubuntu-latest compiler, and normal builds retain no extra flag. Local normal and extra-flag checks pass.

The matrix values select actual OpenSSL installations: 3.0 is the pinned minor formula and 3 follows Homebrew's current default. The additional package/custom choice follows from whether Homebrew's libevent is built against that SSL. The legacy source-build recipe intentionally stays at its prior version; consolidation or upgrading it is not needed to repair the dependency mismatch.

The recorder/real-object test design and deferred cleanup were reviewed independently. NONBLOCK drains active callbacks until none remain in libevent2.1.12; this fixture has no retained extra bufferevent references or connection callbacks opening descriptors. Adding a retry would hide a cleanup regression rather than fix one. The main-owned helper stubs remain local to avoid a production-library refactor in a socket option fix.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit b00b7e0. Configure here.

Comment thread tests/unit/socket_options_test.cpp Resolved
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Final local suite results are now complete and included in the PR description: 896 passed, 468 expected skips, zero failures across standalone/cluster and plaintext/TLS. The final standalone TLS run included the now-merged #543 test-routing fix and a private adapter for authenticated fixtures; original failing logs were retained. This PR now contains master830ddbe directly, and makecheck3/3 passed after that merge.

The updated real-client socket fixture also passed 500 consecutive optimized runs locally (4.02 seconds), plus ASAN+LSAN+UBSan with NDEBUG. Its Unix connected callback is exercised explicitly, with no Redis requests generated. The obsolete NULL-manager assumption is removed.

The macOS CI work is retained because executing this regression test exposed the existing mixed-OpenSSL libevent crash, so aligning those dependencies is needed to run the test across the supported SSL variants. Making these checks mandatory is deliberate. The native Homebrew cell preserves packaged-dependency coverage; the existing legacy recipe stays at its known-good version. The repository has no committed changelog; the release-note text remains in the PR description for the repository's curated release workflow.

The recorder remains limited to the socket test translation unit, with socket headers included before macro substitution. This keeps real socket options and production connection setup under test across both GNU and macOS linkers without adding a production testing interface. Current-head CI and bot review are running.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Addressed the OpenSSL compatibility and optional-flag declaration points in f8f4050. The test now mirrors production's pre/post-1.1 initialization and method selection. Modern TLS, actual OpenSSL1.0.2u with matching libevent, and TLS-disabled builds each pass makecheck3/3; formatting and independent review pass. The explicit empty flag default remains overrideable from make's command line.

The fixture's coverage claim is deliberately socket setup/options and reconnect descriptor cleanup. A zero-depth pipeline prevents sending Redis requests to bare socket listeners while safely exercising the real Unix connection callback. Full production connection/protocol behavior is covered by the integration suites; this unit test does not claim a TLS handshake against its bare listeners.

The macOS gating change is deliberate under the requested cross-variation validation. Dependency fetches already retry three times and verify the pinned archive checksum; a persistent fetch or linkage failure should remain visible. Keeping the dependency repair here lets the new test actually run on the SSL variants that exposed the mismatch. This is also covered by independent review.

The test-only recorder was chosen to inspect the production socket without adding a public production accessor or a platform-specific linker wrapper. System socket declarations are included before macro substitution. Compilation across the supported toolchains makes header changes that conflict with the recorder visible immediately; a production testing interface would broaden this repair unnecessarily. The earlier reply and updated description include the full-suite results, 500-run fixture check, and release-note rationale.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

The macOS failure policy is intentional, not an accidental consequence of adding makecheck. These four configurations now validate the actual unit tests and transitive SSL linkage, and the native Homebrew leg retains package coverage. The dependency alignment is required by the crashes uncovered when enabling this test. I am retaining that repair together with its cross-platform validation.

config_init_defaults is static in the executable's main translation unit. Exporting it or linking main into this test would require a broader refactor. More importantly, applying its real defaults and then overriding them still requires pipeline0 here: these are bare socket listeners, so the fixture must not send a Redis workload. The test explicitly claims socket-option setup and reconnect cleanup, while production CLI/default behavior stays in the full integration suites. The real client manager is used so dispatched connection callbacks have correct ownership and statistics.

Extracting only the setsockopt calls would let a unit test pass even if production connect stopped invoking that helper. The current recorder tests the actual connection path and a fresh descriptor on reconnect, with real getsockopt checks. The test-only stubs are intentionally minimal; the shared fuzz stubs define object-generator implementations that conflict with the real production objects needed here. Moving process-wide helpers is a separate refactor, not necessary for this regression fix. Independent reviewers approved these choices; supported builds and current-head CI exercise their portability.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Final verification on f8f4050: all applicable CI is green, 120 successful checks and6 intentional skips. This includes the four macOS variants, eight RPM builds, full plain/TLS integration suites, sanitizer suites, coverage, Claude and Cursor. All substantive bot findings have been addressed; the Cursor thread is resolved. Independent code review approved this exact head.

The branch includes latest master830ddbe. Local evidence remains documented above: 896full-suitepasses/468expectedskips,3/3changed runtime lines covered, normal/no-TLS/legacySSL unit builds, sanitizer checks, and500consecutive socket fixture runs. No merge is performed by this update.

@fcostaoliveira
fcostaoliveira merged commit 76b2b8f into master Sep 21, 2026
126 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 6, 2026
* Test socket options across connection setup and reconnects

* Link socket regression test against real client RTTI

* Initialize TCP keepalive and no-delay socket options

* Keep socket option checks portable and verify linger policy

* Run socket regression tests in all macOS builds

* Capture macOS socket test failure diagnostics

* Build macOS libevent against each selected OpenSSL

* Make uninitialized socket regressions deterministic in CI

* Preserve normal and Homebrew builds alongside socket diagnostics

* Require macOS checks and keep diagnostic flags scoped to the test

* test: give socket connections a real client manager

* test: match production OpenSSL compatibility guards

(cherry picked from commit 76b2b8f)
@fcostaoliveira fcostaoliveira mentioned this pull request Oct 6, 2026
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
rate_limiter_test (#519) and socket_options_test (#541) were added to
check_PROGRAMS without matching .gitignore entries, so after `make check`
both binaries show up as untracked files. List them next to the other
three check programs; the five entries now match check_PROGRAMS in
Makefile.am.

Also ignore the genhtml report directory that `make code-coverage-capture`
writes (memtier_benchmark-<version>-coverage/). The .info file and the
gcov artifacts were already covered by *.info / *.gc*.

Fixes #623

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 14, 2026
rate_limiter_test (#519) and socket_options_test (#541) were added to
check_PROGRAMS without matching .gitignore entries, so after `make check`
both binaries show up as untracked files. List them next to the other
three check programs; the five entries now match check_PROGRAMS in
Makefile.am.

Also ignore the genhtml report directory that `make code-coverage-capture`
writes (memtier_benchmark-<version>-coverage/). The .info file and the
gcov artifacts were already covered by *.info / *.gc*.

Fixes #623

Co-authored-by: Claude Opus 5.5 <[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.

Uninitialized flags in setup_socket can disable TCP_NODELAY and cause ~41 ms TLS SET latency

1 participant