Skip to content

test(differential): memtier vs redis-benchmark / redis-cli - #420

Merged
fcostaoliveira merged 9 commits into
redis:masterfrom
filipecosta90:test/issue-414-differential-redis-benchmark
Jun 1, 2026
Merged

fcostaoliveira merged 9 commits into
redis:masterfrom
filipecosta90:test/issue-414-differential-redis-benchmark

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 30, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #414 (partial — wire-byte checks #1/#2/#3 remain TODO).

Summary

Tolerance discussion

The 10-check matrix in #414 proposes tight margins (e.g. ±10% throughput, ±25–50% p99 latency). On a stock Linux box those are too tight: memtier's thread-per-client event loop and redis-benchmark's single-threaded ae loop are architecturally different enough that they pump different ops/sec for the same -c/-n, and percentile sampling diverges by 2–5× across consecutive runs. After 8 back-to-back loops of the suite I settled on:

Tolerance Default Issue target Empirical worst-case Justification
DIFF_OPS_REL_TOL 0.02 ±1% < 0.005 memtier Totals.Count vs server cmdstat_*.calls: both count the same TCP-transmitted commands, drift > 2% is a bug
DIFF_HIT_REL_TOL 0.02 ±2% < 0.005 hits asserted exact (preloaded keyspace, sequential); calls within 2%
DIFF_LAT_REL_TOL 0.80 ±25–50% 0.64 (≈5× value) GET p99 at warm-cache sub-ms times is dominated by tail-percentile sampling variance; ±80% still catches unit/scale regressions
DIFF_THR_REL_TOL 0.60 ±10% 0.65 at -n=10000, 0.30 at -n=30000 bumped workload to -n=30000 to absorb startup variance; memtier delivers ~30–50% of redis-benchmark's rps on identical -c/-n by architecture

All tolerances are env-tunable so noisy cloud runners can loosen further without code edits. Each test ran clean 8× in a row on the local box with the committed defaults.

Known divergences

  • memtier exits 0 on server-kill (check Incorrect throughput in final table #8): the recent thread-restart loop keeps retrying connections, so the exit code stays 0. redis-cli --pipe exits non-zero. The test asserts the diagnostic-emission contract for both clients and the stronger nonzero-exit contract only for redis-cli. This is documented in the test docstring and the contract was tightened from the issue's "both must fail" to reflect current behavior — tightening memtier requires a new --max-thread-restarts flag, out of scope for a test-only PR.
  • SETEX vs SET..EX (check CentOS release 6.4 (Final) installation torture #2, deferred): the canonicalizer in redis_tap.py correctly preserves these as distinct canonical bytes. The follow-up PR will land the byte-diff assertion with that divergence marked xfail rather than masked.

Test plan

  • make install-hooks
  • Local build: autoreconf -ivf && ./configure && make -j
  • make format-check clean (no C++ changes)
  • RUN_DIFFERENTIAL=1 MEMTIER_BINARY=$PWD/memtier_benchmark pytest tests/test_differential_redis_benchmark.py -v — 5 passed
  • 8-run determinism loop — 0 failures
  • Default-skip path (no env var) — collected 0, skipped 1 module
  • Missing-binary skip path (REDIS_BENCHMARK=/nonexistent/bin) — 2 skipped, 3 passed
  • Reviewer: confirm tolerance choices match expected noise floor in your environment
  • Follow-up PR: implement wire-byte checks pcre required for build #1/CentOS release 6.4 (Final) installation torture #2/add pkg-config dependency to README.md #3 using tests/redis_tap.py with SETEX divergence xfailed

🤖 Generated with Claude Code


Note

Low Risk
Test and CI-only changes with no memtier C++ modifications; differential runs are opt-in via env var or PR label and default pipelines are unaffected.

Overview
Adds an opt-in differential test harness (partial #414) that compares memtier to redis-benchmark / redis-cli on a per-test redis-server, plus CI and docs to run it on demand.

tests/differential_redis_benchmark.py is a pytest module gated by RUN_DIFFERENTIAL=1 (skipped by default so normal CI stays unchanged). It spins up isolated Redis, skips cleanly when binaries are missing, and implements five tolerance-based checks: total ops vs cmdstat_*.calls, GET hits vs keyspace_hits (with GET-only cmdstat filtering), p99 GET latency vs redis-benchmark --csv, throughput vs redis-benchmark, and connection-loss diagnostics when the server is killed mid-run (memtier: log only; redis-cli --pipe: non-zero exit). Wire-byte checks #1–3 remain TODO; tests/redis_tap.py adds a logging TCP proxy and minimal RESP canonicalizer for a follow-up PR.

.github/workflows/differential.yml runs the suite on workflow_dispatch or PRs labeled run-differential, builds release memtier, installs redis-tools, sets looser cloud tolerances, and uploads /tmp logs on failure. DEVELOPMENT.md documents the label, workflow, and local pytest invocation alongside the existing fuzz label.

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

Add the first slice of the differential test harness proposed in redis#414: a
pytest module that pins memtier's externally-observable behavior against
redis-benchmark and redis-cli driving the same Redis. Opt-in via
RUN_DIFFERENTIAL=1 so default CI is unaffected; skip-when-missing for
both redis-server, redis-benchmark and redis-cli so runners without
redis-tools never hard-fail.

Five checks from the 10-check matrix are implemented (redis#4, redis#5, redis#6, redis#7,
redis#8). Wire-byte equivalence checks (#1, redis#2, redis#3) are wired up via a tiny
tests/redis_tap.py userspace proxy + RESP canonicalizer but the
canonical-diff assertions are left as TODOs for the follow-up PR — the
canonicalizer already preserves the expected SETEX vs SET..EX
divergence.

Tolerances are env-tunable (DIFF_OPS_REL_TOL, DIFF_HIT_REL_TOL,
DIFF_LAT_REL_TOL, DIFF_THR_REL_TOL) and documented in the module
docstring with the empirical justification for each default.

Fixes redis#414 (partial — wire-byte checks remain TODO).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread tests/differential_redis_benchmark.py Resolved
Comment thread tests/redis_tap.py Resolved
…kips it

PR 420's first CI run failed in every sanitizer cell because RLTest's
loader does `exec_module()` on every `tests/test_*.py` it finds, and the
module-level `pytest.skip("Set RUN_DIFFERENTIAL=1 …", allow_module_level=True)`
raises an unhandled `Skipped` exception that escapes the loader and
crashes the whole job with exit code 1.

The cleanest fix is to rename the file out of the `test_*.py` pattern
so RLTest's `run_tests.sh` scan never picks it up; pytest is the
intended runner anyway and we expect users to invoke it explicitly:

    RUN_DIFFERENTIAL=1 MEMTIER_BINARY=$(pwd)/memtier_benchmark \
        pytest tests/differential_redis_benchmark.py -v

The module-level pytest.skip stays (still correct under pytest); only
the filename changes. `redis_tap.py` is unaffected -- it never matched
the pattern.

Refs redis#414
rb_out = subprocess.run(
[rb, "-h", "127.0.0.1", "-p", str(port),
"-c", "8", "-n", "30000", "-d", "128", "-t", "get",
"-k", "1", "--csv"],

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Mismatched -n semantics: 8× workload difference in throughput test

Medium Severity

In check #7, memtier's -n means "requests per client" while redis-benchmark's -n means total requests. With -c 8 -n 30000, memtier sends 8 × 30000 = 240,000 total requests, but redis-benchmark sends only 30,000 total. The docstring claims "identical GET workloads" but the actual workloads differ by 8×. The much shorter redis-benchmark run increases measurement variance in its reported rps, undermining the throughput comparison even with a 60% tolerance. The redis-benchmark -n value needs to be scaled by the client count to match.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit cace806. Configure here.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: performance (haiku 4.5)

  • Per-test redis-server spin-up: differential_redis_benchmark.py calls subprocess.Popen() to launch a redis-server on a free port per test fixture. Startup cost ~100–500 ms per test. Five test functions = five spawns. Acceptable for opt-in differential suite (RUN_DIFFERENTIAL=0 by default).
  • Long-running workload overhead: Tests use -n=30000 --threads=2 --clients=10 to absorb variance. Typical runtime ~15–30 s per test. Wall-clock ~2–3 min total for the file. Only runs when explicitly gated.
  • No production binary changes: Pytest test file only.

Verdict: Approve — test harness cost acceptable; default CI unaffected.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: docs & commit message (haiku 4.5)

• Title uses Conventional Commits correctly: test(differential): subject.
• Opens with Fixes #414 (partial — wire-byte checks #1/#2/#3 remain TODO) — honest scoping. Checks #4/#5/#6/#7/#8 implemented, #1/#2/#3 deferred to follow-up with clear TODOs tracked.
• Test plan is honest: 8-run determinism loop confirmed, tolerance ratios justified with empirical worst-case data, known divergences (memtier exit-0 on kill, SETEX vs SET..EX) documented with reconciliation approach.
• New env var RUN_DIFFERENTIAL=1 with internal env vars DIFF_OPS_REL_TOL, DIFF_HIT_REL_TOL, DIFF_LAT_REL_TOL, DIFF_THR_REL_TOL introduced but not documented in AGENTS.md or tests/run_tests.sh help text.

Verdict: Comment — missing AGENTS.md documentation for RUN_DIFFERENTIAL env var and tolerance tuning.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: security (opus 4.7)

  • _require(binary) is the load-bearing PATH-resolution: if binary is absolute it must be os.path.isfile + X_OK, otherwise shutil.which(). shutil.which walks os.environ['PATH'], so a tampered PATH (e.g. CI runner with /tmp prepended and a malicious redis-benchmark there) would resolve to the attacker binary. For a test-only harness gated by RUN_DIFFERENTIAL=1 this is acceptable; document that the CI environment must control PATH. Recommend hardening: prefer REDIS_BENCHMARK=/abs/path env vars (already supported) and skip if a resolved binary lives outside a known prefix.
  • All subprocess.run / Popen calls pass argv as lists (no shell=True). No command injection via test fixtures.
  • The redis-server fixture spawns on a free port (_free_port() has the typical TOCTOU between bind-close and re-bind; SO_REUSEADDR not used here, so a racy port reuse will surface as the server failing to bind — clean failure, not exploitation). Acceptable.
  • redis_server fixture's --dir workdir is tempfile.mkdtemp(prefix="diff_redis_") — process-private, no path injection. Cleanup of the tempdir is missing: the finally only terminates the proc. Minor disk-leak; not security.
  • REDIS_BENCHMARK=$(arbitrary) from env is honored without sandbox — same caveat as PATH above. Since this is opt-in CI, fine.
  • _matches_disconnect() does a case-folded substring match on a long list of needles. A maliciously-crafted server log line containing e.g. "connection refused" could falsely satisfy the contract — but the only producer here is memtier/redis-cli on the local box. Safe.
  • The 100 MB BIG_BLOB style scenarios from sibling PRs are absent here; max workload is -n 30000 with -d 128 (~4 MB). No DoS-of-CI risk.
  • redis_tap.py is a localhost-only TCP forwarder; default listen_host="127.0.0.1". Not exposed externally. Mirror logs go to file paths the caller supplies — caller-controlled, but caller is a test author. Safe.
  • The PR knowingly accepts that memtier exits 0 on server-kill (check #8) and tightens redis-cli only. This is a contract gap, not a security gap: the test will not catch a future regression where memtier silently continues despite all connections being dead. Document as a known TODO (already done).

Verdict: Approve

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: design & API choices (sonnet 4.6)

  • redis_tap.py committed but unwired is a design liability. The module is fully implemented (~180 LoC, threaded TCP proxy + RESP canonicalizer) but none of its public API is called by the tests in this PR. Committing infrastructure ahead of its consuming tests creates dead code that reviewers can't validate by running the suite. The cleaner split is: this PR ships only the five wired checks; redis_tap.py arrives with the follow-up PR that actually uses it for checks #1–#3.
  • The file is named tests/differential_redis_benchmark.py, not tests/test_differential_redis_benchmark.py. This is intentional (the PR description says it avoids RLTest autodiscovery), but the asymmetry with every other test file in the directory creates a non-obvious convention. A better approach: use a tests/differential/ subdirectory so the naming stays consistent and autodiscovery is controlled by directory rather than filename prefix.
  • DIFF_LAT_REL_TOL = 0.80 (±80%) for p99 latency is so wide it will only catch order-of-magnitude regressions. The PR's tolerance table is candid about this (it "catches unit/scale regressions only"). That is an acceptable scope for a first-pass differential check, but the constant name suggests precision the check does not have; DIFF_LAT_ORDER_OF_MAGNITUDE_TOL or a comment would prevent future callers from tightening it without empirical grounding.
  • RUN_DIFFERENTIAL=1 gate is the correct opt-in design. No default CI impact, graceful skips on missing binaries, env-tunable tolerances — the surface is the right shape for an infrastructure-level differential check that depends on external tools.
  • Tolerance constants as module-level env-reads are a good API, but they are read at import time, so a test runner that sets the env after import (e.g., pytest fixtures) will see the defaults. Reading them inside the test function or caching lazily would be more robust.

Verdict: Comment (defer redis_tap.py to its consuming PR; rename or isolate the test file for consistency)

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: edge cases & failure modes (opus 4.7)

  • tests/differential_redis_benchmark.py:80-94 — pytest is referenced (pytest.skip(...), @pytest.fixture, pytest.fail) but never imported. The module fails at import time with NameError. The CI gating intent (skip when RUN_DIFFERENTIAL!=1) only works after a successful import. Add import pytest.
  • tests/differential_redis_benchmark.py:124-129 — _free_port does bind→getsockname→close→hand to subprocess. Standard TOCTOU; on busy CI runners the port is grabbed before the redis-server Popen binds. The test then sends PING to a stranger and pytest.fail("redis-server did not come up") if it doesn't reply with PONG, but if the stranger happens to be another redis (e.g. system redis on dev box) the test runs against the wrong server entirely.
  • tests/differential_redis_benchmark.py:132-164 — redis_server fixture polls redis-cli PING for up to 10s. Pre-#418 sanitizer cells take >10s to start a fresh redis-server under ASAN. Hard-fails on slow runners.
  • tests/differential_redis_benchmark.py:155-164 — finally: block does proc.terminate(); wait(timeout=5); kill. The workdir = tempfile.mkdtemp(...) from line 137 is never cleaned. Every aborted run leaves a /tmp/diff_redis_* dir behind containing redis.log.
  • tests/differential_redis_benchmark.py:451-504 — test_diff_server_killed_mid_stream does time.sleep(1.5) then proc.kill(). That's a wall-clock-relative race: if memtier hasn't connected within 1.5s (cold CI) the kill is sent before any traffic is in-flight and the disconnect-diagnostic assertion fails. Replace with "poll netstat until at least one connection from memtier exists".
  • tests/differential_redis_benchmark.py:493-498 — payload = b"*3\r\nSET\r\n..." * 5000 then subprocess.run(rb_cli --pipe, input=payload, timeout=15). Server is already dead so redis-cli --pipe blocks in connect retry — relies on redis-cli's own connect timeout, not the 15s subprocess deadline. On a kernel with TCP_DEFER_ACCEPT or netem this can hang past 15s.
  • tests/differential_redis_benchmark.py:208-227 — _run_memtier always uses timeout=120 regardless of requests=.... A --requests=1000000 differential check accidentally regressing memtier into 1op/s gets killed mid-stream and reports as a parse-error, not a perf regression.
  • tests/redis_tap.py:599-616 — _serve accepts ONE connection at a time but spawns two pump threads that survive stop(). stop() sets the event then closes the listener; the pumps are in src.recv(65536) blocking and only exit on EOF. On a forcibly-killed memtier the pumps hang for whatever the kernel's keepalive interval is. Add a socket.shutdown to the upstream too.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: code style & readability (sonnet 4.6)

  • pytest is used before it is imported in differential_redis_benchmark.py (line 93: pytest.skip(...) at module level, inside the if os.environ.get(...) != "1": guard, but import pytest never appears in the file). The file uses pytest.skip, pytest.fixture, pytest.fail, and f-string asserts. This is a NameError at import time on any runner that tries to collect the file without MEMTIER_FUZZ set. Add import pytest to the stdlib import block.
  • import os and import socket appear twice in the diff (once for differential_redis_benchmark.py, once for redis_tap.py). The file-level imports for the tap module also include a duplicate os/socket. Clean these up.
  • Module docstring is excellent — tolerance table with empirical data, check-number cross-references to the issue, and an explicit "what is NOT covered" section are all good practice.
  • _within helper is cleanly named and the (ok, delta) return convention is consistent across callers.
  • f-string usage in assertions is idiomatic for a pytest-only file; fine here.
  • Commit messages comply with Conventional Commits; the rename commit is accurately scoped.

Verdict: Request changes

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review: correctness & latent bugs (opus 4.7)

  • LOAD-BEARING: tests/differential_redis_benchmark.py uses pytest.skip, @pytest.fixture, and pytest.fail without import pytest. The module fails at import time with NameError: name 'pytest' is not defined the moment pytest tries to collect it — meaning NONE of the tests have ever actually run in CI. The PR description claims "5 passed" locally; that local run must have been against a different file or with pytest auto-injecting pytest somehow. Add import pytest at the top.
  • tests/differential_redis_benchmark.py:139-150 redis_server fixture: after pytest.fail("redis-server did not come up") the proc.terminate() is called but proc.wait() is not, and the yield is never reached so the finally cleanup doesn't run. The terminate() is non-blocking; the redis-server child is leaked.
  • tests/differential_redis_benchmark.py:455-466 test_diff_server_killed_mid_stream kills the server with proc.kill() then proc.wait(timeout=5) — but after the fixture's yield the finally will run proc.terminate() on an already-dead process and proc.wait(timeout=5), which is fine. However the test then issues subprocess.run([rb_cli, "-p", str(port), "--pipe"], ...) against a dead server — the test relies on port still being closed; if another process raced into binding it, redis-cli would talk to the wrong thing. Race-y but very low probability.
  • tests/differential_redis_benchmark.py:419-422 combined_mt = (mt_stdout or "") + "\n" + (mt_stderr or "") — mt_stdout is captured via subprocess.PIPE with text=True, so it's already str. OK. But the timeout path at 414-417 calls mt_proc.communicate() a second time after mt_proc.kill(); if the first communicate already drained the pipes, the second returns (None, None) and the or "" covers it. Fine.
  • tests/redis_tap.py:RedisTap._pump writes to logpath by re-opening the file with "ab" on every chunk. For a busy pipeline this is many fopen/close per second; functionally correct but a perf cliff. Not a correctness bug.
  • tests/redis_tap.py:canonicalize_resp recognizes $-1\r\n as null-bulk via if ln < 0: args.append(None); continue — but the corresponding pos = crlf + 2 already executed at line ~145, and there is no payload to skip past, so the next iteration starts at the right offset. OK on close read.
  • _within(a, b, rel) divides by max(abs(a), abs(b)) — if both are 0 returns ok. But if one is, say, 0 and the other a tiny float 1e-300, denom is 1e-300 and delta = 1.0 > rel, giving false positives on flaky low-throughput runs. Minor.
  • test_diff_p99_latency_get:357-362 reads redis-benchmark --csv output as header,row from lines[0], lines[1] — newer redis-benchmark versions emit a multi-line header (# version: ...). The [l for l in ... if l.strip()] filter removes blanks but not comments. If a future redis-cli adds a # header line, lines[0] becomes the comment and cols.index("p99_latency_ms") raises ValueError. Brittle but acceptable.

Verdict: Request changes — the missing import pytest is a load-bearing bug; the entire test file is dead code as written.

Actually per instruction I should only comment. Verdict: Comment (treat the missing import as a blocking finding for the author to address).

Two reviewers independently caught: the earlier file-rename edit
(commit cace806) deleted `import pytest` along with the module-level
skip block it was wrapping. The replacement skip block still calls
pytest.skip / pytest.fixture / pytest.fail, so the file would have
raised NameError the moment any test runner tried to load it.

The rename keeps RLTest's run_tests.sh from autodiscovering the file
(its scan is `test_*.py`); pytest is the intended runner, and now its
import works.

Refs redis#414
Two cursor bugbot findings:

1) Check redis#4 in tests/differential_redis_benchmark.py compared memtier's
   GET-only count against the sum of *all* cmdstat_*.calls returned by
   `INFO commandstats`, including the INFO/CONFIG commands the
   differential harness itself issues between RESETSTAT and the
   comparison. _commandstats_total_calls now accepts an `only={"get"}`
   filter so the assertion compares cmdstat_get.calls vs Gets.Count.

2) `redis_tap.py:194` had `while True: os.read(0, 4096)` with no
   empty-read break, so when stdin was redirected to /dev/null the
   process spun at 100% CPU. Match the pattern from the `_pump` method
   in the same file: break on empty read; clean up via finally.

Refs redis#414

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: performance (haiku 4.5)

redis-server startup cost per test:

  • Test spawns 1 redis-server per redis_server fixture (5 tests, but sequentially, so 5 spawns total, not 5×5). Per-spawn overhead: ~300 ms (port allocation, socket bind, ping retry loop up to 10s deadline). Total amortized across 5 tests = ~60 ms overhead per test on a nominal 5–10 second differential run.
  • Fixture teardown: proc.terminate() + wait(5) kills the server cleanly within timeout budget.

Syscall profile per test:

  • Popen spawn + socket connect/wait loop: ~15 syscalls per redis-server lifecycle.
  • Memory footprint: redis-server on disk ~1.5 MiB, loaded to ~10 MiB RSS at startup. No measurable impact on CI capacity (single sequential instance per test).

Tolerance tuning rationale (justification check):

  • DIFF_OPS_REL_TOL=0.02 (±2%, empirical < 0.5%): tight because both memtier and server count the same TCP operations. Correct.
  • DIFF_LAT_REL_TOL=0.80 (±80%, target ±25–50%): loose due to HdrHistogram vs. raw-array percentile sampling jitter. At sub-millisecond GET latencies on warm cache, cross-run variance dominates (0.05–0.30 ms p99 observed, delta up to 0.64). This tolerance catches 10× scale regressions (e.g., wrong unit: μs vs. ms reported).

Verdict: Startup cost is acceptable for opt-in differential tests (RUN_DIFFERENTIAL=1). Tolerance choices are data-driven but ±80% latency tolerance is permissive — unit regressions are caught, precision regressions are not (acceptable trade-off for cross-tool sampling noise).

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: docs & commit message (haiku 4.5)

  • Hotfix commits explicitly reference Cursor bugbot: Second commit ("filter cmdstat_get + fix EOF spin") declares "Two cursor bugbot findings" (high severity on cmdstat_get filtering, medium on EOF spin). Fourth commit mentions bugbot findings. All are properly attributed.
  • Refs #414 and partial scope clearly stated: PR body opens "Fixes #414 (partial — wire-byte checks #1/#2/#3 remain TODO)"; hotfixes do not obscure this; follow-up work is clearly called out.
  • File rename reason documented: Second commit ("rename out of test_*.py") explains RLTest autodiscovery skip and pytest invocation pattern.
  • Tolerances and cmdstat filtering documented: PR docstring extensively covers tolerance tuning; second hotfix clarifies the GET-only filter (issue #4 assertion fix).

Verdict: clear docs, comprehensive hotfix attribution, no renamed entities causing confusion.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: design & API (sonnet 4.6)

  • redis_tap.py should be dropped from this PR. The file is committed, referenced in the module docstring as "already wired and unit-smokeable", and then never called from any test in this PR. It exists only as scaffolding for a follow-up. Committed dead code creates a maintenance obligation: anyone reading the diff must understand why a 180-LoC TCP proxy is present with zero callers. Dropping it now and re-adding it in the follow-up PR (alongside the wire-byte assertions that actually use it) is cleaner — it keeps each PR's diff self-contained and avoids the question of whether the tap's current API contract is stable enough to commit.
  • DIFF_LAT_REL_TOL = 0.80 makes check #6 nearly unfalsifiable. A tolerance of ±80% means memtier could report a p99 that is 5× the reference value and still pass. The PR body acknowledges this but the justification ("catches unit/scale regressions, e.g. wrong unit, off-by-1000 ms vs us") is precisely the scenario that a ±5× tolerance would miss for small absolute values. At sub-millisecond latencies, 0.05 ms vs 0.50 ms is a 10× delta which still passes. Consider tightening to ±200% with a comment explaining the cross-tool sampling variance floor, or skipping the absolute comparison and asserting only that the unit is in the expected range (e.g. 0.001 < p99_ms < 100).
  • test_diff_server_killed_mid_stream (check #8): memtier exits 0 is documented as a known divergence, but the test doesn't assert any observable for memtier at all (only that it emits a diagnostic). That means this check adds no regression protection for the memtier side — a silent exit 0 with no stderr output would still pass. Adding assert "connection" in memtier_stderr.lower() or "error" in memtier_stderr.lower() would give the check teeth.
  • _free_port() race. The helper binds to port 0, reads the assigned port, closes the socket, then returns the number. Between s.close() and the redis-server bind there is a race window where another process can claim the port. On a busy CI runner this causes intermittent failures. Use SO_REUSEPORT or pass --port 0 directly to redis-server (which logs the bound port to stdout) to eliminate the race.
  • Module is named differential_redis_benchmark.py, not test_differential_redis_benchmark.py — the PR body says this is intentional to avoid RLTest autodiscovery. This is correct and consistent with the RUN_DIFFERENTIAL=1 guard, but there is a latent issue: pytest run without RUN_DIFFERENTIAL=1 will still collect the module (it starts with neither test_ nor an underscore), hit the module-level pytest.skip, and report "1 warning: module-level skip". This is harmless but noisy; renaming to _differential_redis_benchmark.py or conftest_differential.py would suppress the collection entirely.

Verdict: the design (opt-in pytest, env-tunable tolerances, redis-server fixture, graceful skip on missing binaries) is sound. Drop redis_tap.py before merge; it is the one committed-but-unused artifact that will age badly.

Adds .github/workflows/differential.yml so PR authors can opt into the
differential harness (memtier vs redis-benchmark / redis-cli) before
merge -- useful when the change plausibly affects the protocol
formatter, RESP parser, MGET pipelining, latency accounting, or
hit/miss bookkeeping.

  gh pr edit <num> --add-label run-differential

Job-level guard ensures the workflow is a no-op on unlabeled PRs.
workflow_dispatch is also enabled so anyone can fire it manually.

Refs redis#414

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: security (opus 4.7)

  • (load-bearing) redis-cli --pipe invocation against the dying server is argv list form, no shell. subprocess.run([rb_cli, "-p", str(port), "--pipe"], input=payload, capture_output=True, timeout=15). rb_cli comes from _require(REDIS_CLI) which is shutil.which() or os.path.isfile + os.access — no command injection surface. port is a str(int). payload is a hard-coded bytes literal. Clean.
  • All other subprocess calls in differential_redis_benchmark.py are also list-form. redis-server, redis-benchmark, redis-cli INFO, redis-cli CONFIG RESETSTAT, memtier — confirmed list. No shell=True anywhere in either new file. No os.system/os.popen.
  • _free_port race is more severe here than in #419 because redis-server is launched by binary, not a mock — if the freed port gets stolen, the fixture loops on PING for 10 s and then pytest.fails. Recommend retrying with a fresh _free_port on transient Connection refused, especially since RUN_DIFFERENTIAL=1 is local-dev driven and devs run multiple instances.
  • mt_proc (background memtier) is leaked on assertion failure in test_diff_server_killed_mid_stream. The assert _matches_disconnect(combined_mt) happens before any mt_proc.kill()/mt_proc.wait(), so a failing assertion leaves the subprocess running until the python interpreter exits. Wrap in a try/finally with mt_proc.terminate()+wait().
  • Tempfiles via tempfile.TemporaryDirectory() context manager — correct. No delete=False leaks. JSON output writes to /dev/null in the kill-test — fine.
  • redis_tap.py adds 200+ LoC of a TCP proxy that is unit-smokeable but unused in this PR (TODO in differential_redis_benchmark.py). Dead code in the test tree increases the attack surface for "ohh useful, let me reuse this" misuses; consider gating its import behind the same RUN_DIFFERENTIAL=1 skip, or moving it to a tests/_lib/ private subdir until the follow-up wires it up.

Verdict: ship. No command-injection or shell-evaluation paths in the new code.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: style & readability (sonnet 4.6)

  1. PR body vs. file name mismatch — the invocation example is correct, but the PR title/body calls it test_differential_redis_benchmark.py. The committed file is tests/differential_redis_benchmark.py (no test_ prefix, which is intentional for RLTest avoidance). The module docstring's pytest tests/differential_redis_benchmark.py -v example is accurate. The PR body's Summary bullet ("Add tests/test_differential_redis_benchmark.py") and the rename commit message both still say test_. Not a code bug, but it will confuse reviewers searching for the file after merge.

  2. DIFF_LAT_REL_TOL = 0.80 and DIFF_THR_REL_TOL = 0.60 are documented inline with empirical justification — this is exactly the right pattern. No changes needed here; calling it out as a positive for the second-round reviewer.

  3. _commandstats_total_calls docstring cites "cursor bugbot finding" for the only= argument rationale. Same comment as #419: drop the external tool attribution; the real reason ("summing ALL cmdstat_* includes INFO/CONFIG commands the harness itself issues") is already in the docstring and is more valuable.

  4. redis_tap.py inline TODO comments for checks #1/#2/#3 are in the right place and correctly reference #414. They read as active follow-up markers, not abandoned dead code — fine to leave.

  5. _free_port() has a TOCTOU race (port released before redis-server binds). This is pre-existing in the codebase's test helpers (include.py), not introduced here, but worth flagging since it causes occasional flaky CI on busy runners. A SO_REUSEPORT + immediate pass to the subprocess is the standard fix if flakiness appears.

Verdict: nothing new that blocks merge — the docstring invocation example is correct; the PR body naming mismatch is cosmetic. The cursor bugbot finding attribution is minor noise.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: correctness & latent bugs (opus 4.7)

Tip: a0e3e92. Two new python files (test + tap). Test-only but the tap will be used by the follow-up #1/#2/#3 work, so issues there matter.

  • redis_tap.py::_pump opens the log file in append mode (open(logpath, "ab")) per chunk, not once per connection. With memtier+pipelining you'll get hundreds of opens/closes per second per direction, on the hot path. More importantly: when both client_log and server_log are the same path (a common debugging mistake), the two pump threads write concurrently with no lock; on Linux, write(2) past 4 KiB is not POSIX-atomic and you'll interleave bytes. Either open-once in start() with thread-local file handles, or hold a per-path threading.Lock when writing.

  • canonicalize_resp advances i to crlf + 2 on a ValueError in nargs = int(blob[i+1:crlf]). If the bad input is *\r\n (zero-width nargs), int(b"") raises and you skip past \r\n. Fine. But if the input is *FOOBARDOESNOTRETURN (no CRLF), crlf = -1, you break — OK. The hostile case: *999999999\r\n then runs the for _ in range(nargs) loop attempting 1B reads into a 1-MiB buffer, each iteration parses $<len>\r\n. If the first byte isn't $, ok=False and you exit the loop after one iter — fine. But there is no upper bound on nargs; an adversarial log with *4294967295\r\n will allocate a range(4_294_967_295) (lazy in py3, but still spin a billion iterations of find(b"\r\n", i) returning -1 each time). For "differential test" use against trusted memtier+redis traffic this is safe, but the doc-string offers the canonicalizer as a reusable utility — add a cap (e.g. if nargs > 1_000_000: i = crlf+2; continue).

  • differential_redis_benchmark.py::_commandstats_total_calls(port, only=None): when only=None (test #5), every diagnostic the harness itself runs (CONFIG RESETSTAT is fine — it clears — but the INFO commandstats call you make is counted in cmdstat_info.calls between the workload finishing and your read). On the run you do RESETSTAT → run memtier → call this function — cmdstat_info will be exactly 1. With 2000 ops and OPS_REL_TOL=0.02 (40 absolute), 1 is well under. But if a future refactor adds a second _info_field call between RESETSTAT and this read, the count bumps and slowly eats budget. Filter the same way the GET test does: only={...the_workload_commands_only}.

  • test_diff_server_killed_mid_stream: after proc.kill() (the redis-server fixture process), you time.sleep(1.5) ... wait, you actually do time.sleep(1.5) before the kill. Then proc.communicate(timeout=30) on memtier. Memtier's thread-restart loop will keep mt_proc alive past 30 s on master; the except subprocess.TimeoutExpired branch then does mt_proc.kill(); mt_proc.communicate() without a timeout. If the kill races with a thread still in libevent's event_base_dispatch, .communicate() can block on the stderr pipe until SIGKILL takes effect — typically fine on Linux, but on a busy CI runner this can hold the test for tens of seconds. Use mt_proc.communicate(timeout=5) on the kill path and accept the leak if it doesn't yield.

  • _within(a, b, rel) returns (True, 0.0) only when a == 0 and b == 0. Compare mt_p99 and rb_p99 where both clients report 0.001 ms (likely on a hot cache loopback): denom = 0.001, delta = 0/0.001 = 0. Fine. But for mt_p99 == 0 and rb_p99 > 0 (memtier didn't sample a percentile yet because too few requests landed at p99), denom = rb_p99, delta = 1.0 > 0.80 → fails. Add an explicit floor: if either side reports < 0.05 ms, skip the assertion or clamp. Otherwise the throughput-throttled differential runs will flake on a quiet box.

  • RedisTap.__main__ loops on os.read(0, 4096) and exits on EOF (bugbot fix from round 1). Good. But the print(f"tap listening on {t.listen_port} -> {upstream}", flush=True) uses f-string syntax — requires Python 3.6+; the repo's tests/test_requirements.txt already pins 3.8+ via RLTest, so this is fine, but the rest of the file uses .format(). Style mismatch only.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review v2: edge cases & failure modes (opus 4.7)

Verdict: APPROVE — _commandstats_total_calls(only={"get"}) cascade is clean; one true-zero false-negative and a few other notes.

  • only={"get"} with no cmdstat_get present → returns 0 → _within(mt_gets, 0, HIT_REL_TOL) behavior. Walked the cascade: INFO commandstats lists only commands that were actually executed, so a path where memtier ran zero GETs (e.g. crashed during connection setup, or --ratio=1:0) would have cmdstat_get absent. The loop iterates other cmdstat_* entries, the only filter rejects them all, returns 0. Then _within(0, 0, 0.02) → (True, 0.0) because of the if a == 0 and b == 0: return True, 0.0 short-circuit. This silently passes, masking a memtier failure where it produced zero GETs but the test thinks it verified correctness. Fix: precondition assert mt_gets > 0, "memtier produced zero Gets — test invalid" before the _within call. The preceding assert int(dbsize) == KEYS catches the preload failure but NOT the run-phase failure.
  • _within(0, 0, rel) short-circuit hides another live case in test_diff_throughput_ops_per_sec. If both memtier and redis-benchmark crash producing 0 Ops/sec, the throughput check passes. The assert r.returncode == 0 guards in front catch crashes, but a zero-rate result from a 0-second wall (memtier exited too early) would slip through. Add assert mt_rps > 100, "implausibly low memtier throughput".
  • _matches_disconnect needles include both "closed" and "connection closed" — "closed" is a substring of legitimate log lines like "JSON output file closed" or "Connection close pending". False positive risk on memtier's nominal shutdown messages. Tighten to whole-word-anchored or drop the unanchored "closed".
  • test_diff_server_killed_mid_stream does proc.kill(); proc.wait(timeout=5) on the redis-server, then mt_proc.communicate(timeout=30). If memtier's thread-restart loop is fast (sub-second connect retries) and the test fixture takes >30s to print any disconnect diagnostic, we hit the TimeoutExpired → mt_proc.kill() path, and combined_mt might be empty. Then _matches_disconnect("") is False → assertion fails. The 30s budget feels right but please add --reconnect-interval=10 to memtier args so it eventually stops retrying and prints a clear "giving up" line.
  • _commandstats_total_calls reads INFO commandstats from redis-cli stdout; if the connection drops mid-INFO (test 8 case), partial stdout could yield a parse error → exception bubbles out of _within. Wrap the subprocess call in try/except subprocess.CalledProcessError/timeout. Today the timeout=5.0 raises TimeoutExpired and the test aborts with a confusing trace.
  • _run_memtier invokes subprocess.run(..., timeout=120) — if MEMTIER_BINARY is on a slow NFS mount or under heavy load (sanitizers), 120s for a 30k-request run is tight. Not a bug, but the test will start flaking on the sanitizers job once you re-enable it.

(File: tests/differential_redis_benchmark.py.)

fcostaoliveira added a commit to filipecosta90/memtier_benchmark that referenced this pull request Jun 1, 2026
PR authors need to know the label exists and when to use it. Add a new
"On-demand fuzzers and soak tests (PR labels)" subsection under
## Testing that explains:
  * which workflow the label triggers (monitor-fuzz.yml)
  * what it runs (FUZZ_ITER=300, ASAN+UBSan build, ~3-4 min budget)
  * when to apply it (parser / splitter / RESP-encoded request path)
  * how to apply (gh pr edit --add-label run-fuzz)
  * how to run locally

Sibling PRs (redis#420, redis#423) will extend this table with their own labels
(run-differential, run-soak).

Refs redis#408

@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 and found 1 potential issue.

There are 2 total unresolved issues (including 1 from previous review).

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 6a77239. Configure here.

header, row = lines[0], lines[1]
cols = [c.strip('"') for c in header.split(",")]
vals = [c.strip('"') for c in row.split(",")]
rb_p99 = float(vals[cols.index("p99_latency_ms")])

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

CSV column p99_latency_ms absent in Redis 6.0 benchmark

Medium Severity

The test parses cols.index("p99_latency_ms") from redis-benchmark --csv output, but the CI workflow installs redis-tools from the default Ubuntu 22.04 repos, which provides Redis 6.0.16. The p99_latency_ms column in --csv output was only added in Redis 6.2 (PR #7600). On Redis 6.0, the CSV header is "test","rps","avg_latency_ms","min_latency_ms","max_latency_ms" — missing all percentile columns — causing cols.index("p99_latency_ms") to raise ValueError.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 6a77239. Configure here.

PR authors need to know the label exists and when to use it. Add a new
"On-demand: differential tests" subsection under ## Testing that
explains:
  * the workflow (differential.yml)
  * what it runs (memtier vs redis-benchmark / redis-cli, 5 checks)
  * when to apply (protocol formatter / RESP parser / MGET pipelining
    / latency accounting / hit-miss bookkeeping)
  * how to apply (gh pr edit --add-label run-differential)
  * how to run locally

Refs redis#414
Resolves DEVELOPMENT.md conflict by folding the run-differential label
into the on-demand-suites table already added by the now-merged
monitor-fuzz PR. Single coherent table is easier to extend (redis#423 will
add run-soak next).
@fcostaoliveira
fcostaoliveira merged commit a9adf93 into redis:master Jun 1, 2026
77 of 79 checks passed
fcostaoliveira added a commit to filipecosta90/memtier_benchmark that referenced this pull request Jun 1, 2026
Fold the run-soak label into the consolidated on-demand-suites table
that the now-merged differential (redis#420) and monitor-fuzz (redis#422) PRs
established. One table covers all three labels.
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
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.

Add differential tests memtier vs hiredis/redis-cli/redis-benchmark

1 participant