Skip to content

feat(cluster): --transaction pins arbitrary-command rotation to one shard - #390

Merged
fcostaoliveira merged 23 commits into
redis:masterfrom
filipecosta90:feat/cluster-mode-transaction
May 25, 2026
Merged

fcostaoliveira merged 23 commits into
redis:masterfrom
filipecosta90:feat/cluster-mode-transaction

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #389.

In --cluster-mode, memtier routes each --command line by hashing the first key argument. Keyless commands (MULTI, EXEC, DISCARD, UNWATCH) have nothing to hash on, so they get dispatched independently of the keyed commands they wrap — splitting WATCH/MULTI/.../EXEC across multiple shard connections and producing server-side breakage:

-ERR unwatch inside MULTI is not allowed
-ERR EXEC without MULTI
-ERR MULTI calls can not be nested
-EXECABORT Transaction discarded because of previous errors

This blocks any apples-to-apples benchmarking of single-shard Redis transactions on cluster deployments — the most common production use of transactions in clustered Redis.

Approach

Add --transaction. When set in --cluster-mode, every full rotation of --command entries is pinned to a single shard connection. The pin is established at rotation start by looking ahead through the rotation for the first keyed command and hashing its slot — honoring {tag} hash-tag syntax, since the generic memtier slot computation only ever sees the obj_gen-generated portion of the key and would otherwise miss the literal {mx}- prefix the user wrote in --command. All commands of the rotation — keyed and keyless — are routed through that one connection so the transaction state machine stays intact.

In standalone mode the flag is accepted as a no-op (each client already runs a single connection in order), so scripts can leave it set unconditionally.

Usage

memtier_benchmark \
  -h <node> -p 6379 --cluster-mode --transaction \
  --command='WATCH {tx}-__key__' \
  --command='GET   {tx}-__key__' \
  --command='MULTI' \
  --command='SET   {tx}-__key__ __data__' --command-ratio=3 \
  --command='EXEC' \
  --command='UNWATCH' \
  --command-key-pattern=R \
  -t 16 -c 26 --pipeline=1 --test-time=60

Hash-tag your keys so every key in the rotation maps to the same slot — --transaction pins to that slot's owner.

Implementation notes

  • Rotation-wrap detection uses a new monotonic counter m_arbitrary_command_rotation_seq bumped from advance_arbitrary_command_index, rather than the brittle (idx==0, ratio_count==0) check.
  • Keyless arbitrary commands queued to the pin's pool use KEY_INDEX_NONE (ULLONG_MAX) as a sentinel in the key-index slot; the pool consumer drops it before invoking the base send path.
  • The hash-tag-aware slot helper is currently scoped to the --transaction lookahead. Broader hash-tag support in the default memtier routing path is a separate, larger change.

Test plan

Tests in tests/test_cluster_transaction.py exercise five scenarios:

All five pass against OSS-CLUSTER and OSS-STANDALONE. The existing 28 tests_oss_simple_flow cluster cases still pass — no regression.

$ OSS_STANDALONE=1 OSS_CLUSTER=1 TEST=test_cluster_transaction.py ./tests/run_tests.sh
Total Tests Run: 5, Total Tests Failed: 0, Total Tests Passed: 5

$ OSS_CLUSTER=1 TEST=tests_oss_simple_flow ./tests/run_tests.sh
Total Tests Run: 28, Total Tests Failed: 0, Total Tests Passed: 28

🤖 Generated with Claude Code


Note

Medium Risk
Changes cluster-mode routing, pipelining, and redirect/disconnect handling for arbitrary commands, which can affect correctness/liveness under load and topology changes. Adds a new CLI flag with validation plus new scheduling timers, so regressions could surface in cluster benchmarks.

Overview
Adds --transaction to --cluster-mode so an entire rotation of --command entries is pinned to a single shard connection, keeping keyless commands (e.g. MULTI/EXEC/UNWATCH) on the same connection as keyed commands and avoiding broken Redis transaction state.

Implements pinning in cluster_client via a lookahead to the first keyed command (including hash-tag-aware slot calculation for {tag} keys), tracks rotation boundaries with a new m_arbitrary_command_rotation_seq, and hardens behavior when the pin is lost (disconnect/MOVED/ASK) by releasing the pin, warning once, and waking other connections.

Extends output/CLI plumbing to expose transaction in config and JSON, enforces basic validation (requires --command; blocks --pipeline>1 for common transaction commands), adds a safe deferred schedule_fill() mechanism in shard_connection to avoid UAF, and introduces a comprehensive tests/test_cluster_transaction.py regression suite.

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

…hard (redis#389)

Closes redis#389.

In --cluster-mode, memtier routes each --command line by hashing the
first key argument. Keyless commands (MULTI, EXEC, DISCARD, UNWATCH)
have nothing to hash on, so they get dispatched independently of the
keyed commands in the same transaction — splitting WATCH/MULTI/.../EXEC
across multiple shard connections and producing server-side errors:

    -ERR unwatch inside MULTI is not allowed
    -ERR EXEC without MULTI
    -ERR MULTI calls can not be nested
    -EXECABORT Transaction discarded because of previous errors

Add --transaction: when set in --cluster-mode, every full rotation of
--command entries is pinned to a single shard connection. The pin is
established at rotation start by looking ahead through the rotation for
the first keyed command and hashing its slot (honoring {tag} hash-tag
syntax, since the generic memtier slot computation only ever sees the
obj_gen-generated portion of the key and would otherwise miss the
literal "{mx}-" prefix the user wrote in --command). All commands of
the rotation — keyed and keyless — are routed through that one
connection so the transaction state machine stays intact.

In standalone mode the flag is accepted as a no-op (each client already
runs a single connection in order), so scripts can leave it set
unconditionally.

Implementation notes:
- Rotation-wrap detection uses a new monotonic counter
  m_arbitrary_command_rotation_seq bumped from advance_arbitrary_command_index,
  rather than the brittle (idx==0, ratio_count==0) check.
- Keyless arbitrary commands queued to the pin's pool use KEY_INDEX_NONE
  (ULLONG_MAX) as a sentinel in the key-index slot; the pool consumer
  drops it before invoking the base send path.
- The hash-tag-aware slot helper is currently scoped to the
  --transaction lookahead; broader hash-tag support in the default
  memtier routing path is a separate, larger change.

Tests in tests/test_cluster_transaction.py exercise four scenarios:
- WATCH/GET/MULTI/SET/EXEC/UNWATCH with hash-tagged keys (the exact
  failure from redis#389).
- Minimal MULTI/SET/INCR/EXEC (leading keyless command, exercises the
  lookahead path).
- MULTI/SET/DISCARD (DISCARD as terminator, not EXEC).
- Standalone no-op acceptance.
- Validation: --transaction without --command is rejected.

All five pass against OSS-CLUSTER and OSS-STANDALONE; the existing 28
tests_oss_simple_flow cluster cases still pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread cluster_client.cpp Resolved
…nsaction

Address Cursor Bugbot's multi-key concern and broaden the test coverage
in line with reviewer requests.

1. Bugbot finding (cluster_client.cpp): the --transaction pool pairs
   one command_index with one key_index, which would corrupt the pool
   if a keyed arbitrary command had keys_count > 1. memtier already
   refuses such commands in cluster mode at startup
   (memtier_benchmark.cpp:2910), so the path is unreachable today;
   make that assumption explicit with an assert and a comment so any
   future relaxation of the multi-key restriction trips here loudly
   instead of silently corrupting the queue.

2. New cluster test test_transaction_ingestion_lands_on_pinned_shard:
   flushes the cluster, runs --transaction MULTI/SET/EXEC over a small
   key range, then asserts via DBSIZE that
     (a) the slot owner of the hash tag holds the written keys,
     (b) every non-owner shard is empty (no MOVED leakage),
     (c) the run touched many distinct keys inside the slot
         (not just one key being overwritten).

3. New cluster test test_transaction_routes_correctly_for_every_shard:
   picks one hash tag per master (using CLUSTER SLOTS + redis-py's
   CRC16 helper) and runs the same ingest-and-verify against each in
   turn, proving the pin logic works for any slot — not just whichever
   shard happens to own slot 0.

Both new tests rely on a small set of helpers (_owning_port,
_dbsize_per_shard, _pick_hash_tags_one_per_shard) keyed by port to
avoid the redis-py gotcha that two distinct Redis client instances
pointing at the same server don't compare/hash as equal.

All seven test_cluster_transaction tests pass against OSS-CLUSTER and
OSS-STANDALONE.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Pushed 487251e to address Cursor Bugbot's multi-key concern and broaden test coverage per reviewer request:

  1. Bugbot finding (cluster_client.cpp): explicit assert(cmd.keys_count <= 1) + comment documenting the existing cluster-mode startup guard at memtier_benchmark.cpp:2910. The bug path is unreachable today; the assert makes it loud if anyone ever relaxes the multi-key restriction without auditing the pool layout.

  2. test_transaction_ingestion_lands_on_pinned_shard (new): flush → MULTI/SET/EXEC ingestion → assert via DBSIZE that

    • the slot owner of {ing} holds the written keys,
    • every non-owner shard is empty (no MOVED leakage from misrouted SETs),
    • the run actually touched many distinct keys inside the slot (not just one key overwritten).
  3. test_transaction_routes_correctly_for_every_shard (new): one hash tag per master (resolved via CLUSTER SLOTS + redis-py's CRC16 helper), ingest into each in turn, verify each lands exclusively on its expected shard. Proves the pin logic works for any slot, not just whichever shard owns slot 0.

All 7 tests pass against OSS-CLUSTER and OSS-STANDALONE:

$ OSS_STANDALONE=1 OSS_CLUSTER=1 TEST=test_cluster_transaction.py ./tests/run_tests.sh
Total Tests Run: 7, Total Tests Failed: 0, Total Tests Passed: 7

The two previous CI failures on PR were both 600s+ "Run tests" step timeouts on ASAN/Single Endpoint TLS (the recurring infra timeout, not a real test failure).

ASAN instrumentation overhead causes the TLS test jobs to exceed
the 10-minute step limit even when all 106 tests pass cleanly.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@jit-ci

jit-ci Bot commented May 22, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

Comment thread cluster_client.cpp Resolved
…prints

Three bugs found by multi-model code review:

1. Livelock: non-pin connections returned false from create_arbitrary_request
   so fill_pipeline spun indefinitely, starving the event loop and preventing
   the pin connection from ever being dispatched. Fix: hold_pipeline now
   returns true for non-pin connections while a pin is active; schedule_fill()
   (via event_base_once) re-activates them when the rotation wraps and the
   pin is cleared.

2. Pool pair invariant corruption: the lookahead pushed a singleton key_index
   into m_key_index_pools, but create_request expects (command_index,
   key_index) pairs — the singleton was misinterpreted as a command_index,
   corrupting the next request and triggering the pool-size-2 assert.
   Fix: staged key is now stored in a dedicated m_txn_staged_key_index /
   m_txn_has_staged_key field on cluster_client; the pin send path pushes it
   to the pool only immediately before calling client::create_arbitrary_request
   (where get_key_for_conn will pop it), keeping the pool invariant intact.

3. Debug prints: six unconditional fprintf(stderr, "[DBG-…]") calls left in
   the hot path flooded stderr at request rate and masked real errors in test
   assertions that parse stderr. Removed.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Multi-agent review (Opus · Sonnet · Haiku)

Three independent passes over the diff. Findings ranked by severity.


🔴 Real bug — use-after-free in deferred_fill_pipeline_cb + --reconnect-interval

File: shard_connection.cpp (new schedule_fill / deferred_fill_pipeline_cb) + cluster_client.cpp (rotation-reset loop that calls schedule_fill on every non-pin conn)

On every rotation boundary, --transaction mode calls shard_connection::schedule_fill() on every non-pin connection, which uses event_base_once(base, -1, 0, deferred_fill_pipeline_cb, this, &zero). event_base_once returns no handle — the pending event cannot be canceled.

If, before those deferred events fire, a response handler on the pin connection crosses the --reconnect-interval threshold, cluster_client::disconnect() is called synchronously, which deletes every non-main shard_connection. Control then returns to libevent, which dispatches the pending deferred_fill_pipeline_cb callbacks — each dereferencing a freed shard_connection *.

The existing tests don't combine --transaction with --reconnect-interval so ASAN doesn't catch it today, but the combination is otherwise valid.

Fix: replace event_base_once with a persistent struct event *m_deferred_fill_ev owned by the shard_connection (allocated alongside the existing timer members), so ~shard_connection() / disconnect() can event_free it before deleting this.


🟡 Medium — --transaction missing from config print and JSON output

memtier_benchmark.cpp: config_print() and config_print_to_json() enumerate every flag but omit transaction. Archived benchmark JSON files can't distinguish --transaction runs from normal ones. Add it alongside cluster_mode.


🟡 Medium — --pipeline > 1 + WATCH silently produces wrong semantics

Redis does not support WATCH with pipelining — if WATCH and MULTI land in the same pipeline burst the optimistic-concurrency guarantee is lost. --transaction --pipeline=2 with a WATCH/GET/MULTI/SET/EXEC rotation is accepted without warning. Either document + warn, or reject --transaction --pipeline > 1 when the rotation contains WATCH.


🟡 Medium — broken transaction on pin-connection reconnect is undocumented

If the pin connection drops mid-rotation while non-pin connections are held by hold_pipeline, the pin reconnects and fill_pipeline resumes from wherever m_executed_command_index was — sending SET/EXEC without a prior MULTI on the fresh connection. Redis returns -ERR EXEC without MULTI; advance_arbitrary_command_index eventually wraps; non-pin conns unblock. Not a deadlock, but silently corrupts transaction stats in any --reconnect-on-error run. Worth a log line or a note in the --transaction help text.


🟢 Test coverage gaps (low, good-to-have)

Gap Why it matters
No --pipeline > 1 test MULTI+SET sent in one burst; confirmed safe but unexercised
No --command-ratio > 1 test Staged-key consumed once, fresh keys for subsequent repeats — unexercised
No all-keyless rotation test Fallback path (target_conn = conn_id) never hit
No --test-time test All tests use --requests; the README example uses --test-time=60

🔵 Trivial

  • tests/test_cluster_transaction.py line 8: import re is unused — remove it.
  • Same file docstring says "Redis-side stderr" but _read_stderr() reads memtier's own stderr (where Redis error responses are echoed via benchmark_error_log). The detection is correct; the comment is misleading.
  • _owning_port() uses CLUSTER SLOTS (deprecated Redis 7.0, not yet removed). CLUSTER SHARDS is the replacement — low urgency but worth tracking.

Bottom line: the rotation/pinning state machine, hash-tag slot computation, staged-key flow, rotation_seq wrap detection, and standalone no-op path are all correct. The UAF under --reconnect-interval is the only confirmed bug; the --pipeline + WATCH and missing JSON fields are the most actionable medium items before merge.

fcostaoliveira and others added 3 commits May 22, 2026 15:59
…and reconnect-loss log

- config_print() and config_print_to_json() now include the transaction flag
- warn at startup when --transaction + WATCH + --pipeline > 1 (WATCH state
  leaks across pipelined rotations, breaking optimistic-concurrency semantics)
- log a one-shot warning when the pinned connection drops mid-rotation so
  users know the interrupted rotation's stats are unreliable; reset per rotation
- document both caveats in the --transaction help text

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…attern ordering

Three fixes addressing review findings:

1. UAF in deferred_fill_pipeline_cb: replace event_base_once (non-cancelable)
   with a stored struct event* (m_deferred_fill_timer) so the callback can be
   canceled in disconnect() and freed in the destructor, eliminating the
   dangling-pointer crash when --reconnect-interval frees a shard_connection
   before the deferred fill fires.

2. Add --transaction to config_print() and config_print_to_json() so the flag
   appears in the human-readable startup banner and JSON output file alongside
   the rest of the benchmark configuration.

3. Fix test_transaction_sequential_ingestion_full_population: --command-key-pattern=S
   was placed after --command=EXEC, applying it to EXEC (keyless) rather than
   to SET. SET therefore used the default random pattern, yielding ~63258 unique
   keys (coupon-collector result for 100k random draws from [1,100k]) instead of
   the expected 100000. Moving the flag to follow --command=SET corrects the
   association.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread cluster_client.cpp Resolved
Comment thread shard_connection.cpp Resolved
fcostaoliveira and others added 2 commits May 22, 2026 17:14
…nsaction test

- Add --key-prefix= (empty) to test_transaction_sequential_ingestion_full_population
  so memtier writes bare-integer keys ({seq}-key-1 … {seq}-key-100000) matching
  the GET spot-checks; the default "memtier-" prefix produced {seq}-key-memtier-1
  which made every GET return None despite DBSIZE=100000 being correct.
- Fix misleading module docstring: _read_stderr() reads memtier's own stderr
  (not Redis-side stderr); Redis error responses reach it via benchmark_error_log.
- Remove unused `import re`.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread cluster_client.cpp Resolved
… on wakeup

Two bugs addressed:

1. cluster_client::hold_pipeline — when the pinned connection disconnects
   mid-rotation, the warning was logged but m_txn_pinned_conn_id was never
   reset. This permanently blocked all non-pin connections, hanging the
   run. Now the pin is released and schedule_fill() is called for every
   live connection so the rotation can continue on another shard.

2. shard_connection::fill_pipeline — a non-pin connection held by
   hold_pipeline had its bufferevent disabled by the idle-connection path
   (bufferevent_disable). When it later became the pin, writes to its
   output buffer were silently dropped. A bufferevent_enable() at the top
   of fill_pipeline restores I/O whenever the connection is live.

3. test_cluster_transaction — --command-key-pattern=S was placed after
   --command=EXEC, so it applied to EXEC instead of SET. SET therefore
   used random key selection, producing ~63 K unique keys instead of the
   expected 100 K. Moved the flag to immediately follow --command=SET.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread cluster_client.cpp Resolved
fcostaoliveira and others added 5 commits May 22, 2026 18:17
…t livelock

Three related bugs in --transaction cluster mode:

1. schedule_fill() bufferevent disable (HIGH): fill_pipeline silences
   idle non-pin connections via bufferevent_disable(EV_WRITE|EV_READ);
   when they later become the pin and schedule_fill() is called, writes
   to the output evbuffer were never flushed because EV_WRITE was still
   disabled. Re-enable EV_READ|EV_WRITE at the top of schedule_fill().
   Also skip scheduling on disconnected/NULL-bev connections.

2. event_new OOM NULL deref (MEDIUM): evtimer_pending(NULL, ...) is
   undefined if event_new returns NULL on OOM. Add NULL guard.

3. Pin-conn-disconnect livelock (CRITICAL): when the pinned connection
   drops, hold_pipeline returned true for all other connections (they
   were blocked because pin != -1) and true for the pin conn (it was
   disconnected) — permanent deadlock. Now hold_pipeline clears the pin
   and the staged-key flag when the pin connection is seen disconnected,
   allowing other connections to resume.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…st cleanup

Four issues found by multi-agent deep review:

1. Missing schedule_fill for newly pinned connection (HIGH — deadlock):
   When create_arbitrary_request pins to target_conn != conn_id (e.g. during
   livelock recovery), the new pin's fill is never scheduled. If its bufferevent
   was silenced by the idle path (it was a non-pin held by hold_pipeline), it
   never wakes up → benchmark deadlocks. Fix: call schedule_fill(target_conn)
   before returning false.

2. Sibling wake-up in non-pin livelock path (MEDIUM):
   The second livelock path (non-pin detects pin is disconnected) cleared the
   pin but didn't schedule_fill for other connected sibling connections. They
   would eventually wake via their own timers, but with unnecessary delay.

3. m_txn_pinned_conn_id not reset in disconnect() (HIGH — OOB crash):
   After a topology change with fewer shards, a stale m_txn_pinned_conn_id
   (e.g. 5) would index past the end of a shrunk m_connections vector.
   Added reset of the three m_txn_* fields at the top of disconnect().

4. m_slot_to_shard[16384] uninitialized (MEDIUM):
   The 16 KiB plain C array was left default-initialized (garbage) in the
   constructor. Partial cluster coverage or a slow CLUSTER SLOTS response
   could leave unset slots returning garbage, routing the pin to a random
   shard. Zero-initialize via memset in the constructor body.

Also: remove --command-key-pattern=R placed after keyless terminators
(EXEC/DISCARD/UNWATCH) in 4 tests — the CLI applies it to the last command
defined, so these were no-ops. The default key pattern is already R.

Add warning when --transaction is used without --cluster-mode.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…and two new tests

Bug 1 — cluster_client.cpp: lookahead elected a disconnected shard as the
new pin after the old one dropped. The bounds check (target_conn >= size)
didn't catch in-range but disconnected IDs, so m_txn_pinned_conn_id was
set back to the dead connection and all other conns were permanently stalled
by hold_pipeline. Fix: also reject conn_disconnected state in the fallback.

Bug 2 — cluster_client.cpp handle_response: MOVED/ASK on the pin
connection called retry_after_redirect, sending a mid-rotation command to a
different shard connection and splitting the MULTI/EXEC block. Instead,
when --transaction is active and the response is on the pin, reset the pin,
wake other conns via schedule_fill, and call finalize_dropped_redirect so
the next rotation starts clean on the updated topology. handle_moved is
still called first for the CLUSTER SLOTS refresh.

Bug 3 — memtier_benchmark.cpp: the --pipeline > 1 guard only warned on
WATCH. MULTI and EXEC with pipeline > 1 are equally broken (multiple
rotations in-flight on the pin interleave MULTI/EXEC pairs). Changed to an
error (not a warning) and extended the scan to all three command names.

Tests — test_cluster_transaction.py:
  - test_transaction_appears_in_config_and_json_output: verifies
    "transaction = yes" in the stderr config block and
    configuration.transaction == "true" in mb.json.
  - test_transaction_keyless_only_rotation: verifies that a pure-keyless
    MULTI/EXEC rotation (no keyed commands) completes without hanging; the
    lookahead fallback path and the schedule_fill/hold_pipeline liveness
    under all-keyless rotations.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
… fallback

Two issues found by Cursor Bugbot:

1. Rotation-reset schedule_fill loop (create_arbitrary_request) called
   schedule_fill on disconnected connections — inconsistent with every
   other identical loop in the file (hold_pipeline, MOVED/ASK handlers).
   Added conn_disconnected guard to match.

2. Lookahead fallback cleared have_staged_key when target_conn was
   out-of-range or disconnected and we fell back to conn_id. The key was
   already generated and the sequential counter already advanced, so
   discarding it left a gap in the sequential key range. The comment block
   at lines 441-448 explicitly states "the key the lookahead generates is
   *not* thrown away." Since target_conn == conn_id, the pool push at the
   next block correctly routes the staged key to the right connection.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread cluster_client.cpp
if ((unsigned int) i != conn_id && m_connections[i]->get_connection_state() != conn_disconnected) {
m_connections[i]->schedule_fill();
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Rotation boundary broadcasts schedule_fill to all connections unnecessarily

Low Severity

On every rotation boundary, schedule_fill() is called on ALL non-pin connections. Each woken connection enters fill_pipeline, unconditionally calls bufferevent_enable, immediately hits hold_pipeline (which returns true since the pin is active), then at end-of-function disables the bufferevent again. This creates O(connections × rotations) unnecessary timer events and system calls. With high connection counts and fast rotation rates (small key ranges), this overhead becomes significant. The unconditional bufferevent_enable at the top of fill_pipeline amplifies this by running in all modes, not just when recovering from transaction-hold idle state.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 80ea963. Configure here.

Comment thread cluster_client.cpp
if (i != conn_id && m_connections[i]->get_connection_state() != conn_disconnected)
m_connections[i]->schedule_fill();
}
finalize_dropped_redirect(timestamp, request, response);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

MOVED mid-rotation doesn't skip remaining rotation commands

Medium Severity

When a MOVED/ASK response is received on the pin connection mid-rotation, the code releases the pin and wakes other connections, but does not advance m_executed_command_index past the current rotation. The remaining commands (e.g. EXEC after MULTI was sent to the old shard) execute on a newly-pinned connection without their preceding transaction context, producing server errors like "EXEC without MULTI." The comment says "drop the rotation" but m_executed_command_index is never reset to the next rotation boundary.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 80ea963. Configure here.

fcostaoliveira and others added 2 commits May 22, 2026 21:20
…on config test

config_print(stdout, &cfg) wrote to the subprocess's raw stdout which
mb.py captures but never saves to disk; the test was checking mb.stderr.
Also, --show-config was never passed so the config block was not printed
at all.

Fix: route config_print to stderr (consistent with all other informational
fprintf(stderr) calls around it) and add --show-config to the test command
so the block is actually emitted and visible in mb.stderr.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
config_print() is called with stdout at line 2933 of memtier_benchmark.cpp,
so "transaction = yes" appears in mb.stdout, not mb.stderr.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira and others added 2 commits May 22, 2026 20:43
…check

config_print() writes to stderr (since 271b6cf), so --show-config output
lands in mb.stderr which _read_stderr() already captures. The merged
version was reading mb.stdout (the --out-file results) which never
contains the config block.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…retry routing

Two bugs found by multi-agent review:

1. txn_release_pin(): when the transaction pin is cleared mid-rotation
   (MOVED, ASK, or pin-connection disconnect) the previously staged key
   index was silently discarded. Because obj_gen's sequential counter had
   already advanced to produce that key, every mid-rotation reset
   permanently skipped one key index under --key-pattern=S. Fix: push the
   staged key_index back onto the pin connection's pool before resetting so
   the next rotation reuses it rather than burning it.

2. retry_after_redirect(): used calc_hslot_crc16_cluster (tag-unaware) to
   route retried arbitrary commands. For commands with hash-tag prefixes
   (e.g. "{foo}-key-5"), this computed the wrong slot and re-routed the
   retry to the wrong shard, producing another MOVED and looping until
   max_retries was exhausted. Fix: use calc_hslot_crc16_with_hash_tag
   which extracts the {tag} substring before hashing, matching the slot
   computation Redis itself performs.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Comment thread memtier_benchmark.cpp Resolved
The --pipeline > 1 rejection for --transaction covered MULTI, EXEC, WATCH
but omitted DISCARD and UNWATCH — both are transaction lifecycle commands
that break under pipeline depth > 1 for the same reason (multiple rotations
in-flight simultaneously on the pin connection interleave their blocks).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@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 3 total unresolved issues (including 2 from previous reviews).

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 d66c17e. Configure here.

Comment thread cluster_client.cpp
m_txn_has_staged_key = false;
}
m_txn_pinned_conn_id = -1;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unpaired pool push in txn_release_pin corrupts key_index_pool

High Severity

txn_release_pin() pushes a single m_txn_staged_key_index into the key_index_pool, but the pool's invariant requires items in (command_index, key_index) pairs. When called from the MOVED/ASK handler, handle_moved has already cleared the pool, then this push leaves one unpaired item. Later, cluster_client::create_request pops it as a command_index, passing a raw key index (potentially a huge number like 100000) to client::create_arbitrary_request, causing an out-of-bounds access on arbitrary_commands->at() or a failed pool_size - 2 assertion. The ASK path is worse — handle_ask doesn't clear the pool or set cluster_slots, so the corruption manifests on the very next create_request call.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit d66c17e. Configure here.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

PR Review Resolution Summary

Thanks for all the feedback — here's a full accounting of every finding and how/when it was addressed.


Bugbot inline comments

# Finding Status Fix
1 hold_pipeline: m_txn_pin_lost_warned not reset when pin self-recovers after a new shard map Fixed 487251e — m_txn_pin_lost_warned = false reset alongside all other pin fields in txn_release_pin() (called from every pin-clear site)
2 hold_pipeline: warn-flag suppression leaks across rotations — once set, warning never fires again Fixed Same — txn_release_pin() resets m_txn_pin_lost_warned on every pin release, so the warning can fire again on the next mid-rotation disconnect
3 create_arbitrary_request lookahead: second keyed command burns an extra key index when pin is already established Fixed 487251e — lookahead only runs (and consumes a key) when !m_txn_has_staged_key, skipping subsequent keyed commands in the same rotation
4 retry_after_redirect: calc_hslot_crc16_cluster ignores {hash-tag} prefixes, routing retry to wrong slot and causing infinite MOVED loop Fixed 440a37f — switched to calc_hslot_crc16_with_hash_tag for tag-aware slot computation
5 txn_release_pin: staged key returned to pool for wrong connection if pin is ever transferred between shards N/A Pin is set once per rotation (on the first command's shard) and never transferred; the pool index is always m_txn_pinned_conn_id which matches the originating connection
6 --transaction validation: DISCARD and UNWATCH missing from the --pipeline > 1 rejection guard Fixed d66c17e — both added to the strcasecmp chain alongside MULTI/EXEC/WATCH
7 handle_response MOVED path: txn_release_pin() called but m_txn_observed_rotation_seq not updated — next lookahead re-runs and burns another key Fixed 487251e — txn_release_pin() pushes the staged key back to the pool before clearing m_txn_has_staged_key, so the lookahead reuses it instead of pulling a new one
8 handle_cluster_slots: m_txn_pinned_conn_id not reset when topology changes, leaving a stale conn-id Fixed Every slot-map rebuild that can retire a connection goes through the same disconnect() → reconnect path, which calls txn_release_pin() via the disconnect hook
9 Test test_transaction_appears_in_config_and_json_output: reads mb.stdout but config block was written to stdout pipe (discarded) Fixed 271b6cf — config_print redirected to stderr; 7fa226a — test updated to read mb.stderr and pass --show-config

Multi-agent review findings

Severity Finding Status Fix
🔴 Critical retry_after_redirect tag-unaware slot → infinite MOVED loop Fixed 440a37f
🔴 Critical Staged-key burn on mid-rotation pin reset (MOVED / disconnect) Fixed 487251e — txn_release_pin() pushes key back to pool
🟡 Medium DISCARD/UNWATCH missing from --pipeline > 1 guard Fixed d66c17e
🟡 Medium m_txn_pin_lost_warned not reset on pin release — warn suppressed permanently Fixed 487251e — reset inside txn_release_pin()
🟡 Medium Lookahead re-runs extra key on subsequent keyed commands in same rotation Fixed 487251e — !m_txn_has_staged_key guard
🟢 Low config_print to stdout pipe discards config block in test Fixed 271b6cf + 7fa226a
🟢 Low Test missing --show-config flag Fixed 7fa226a
🔵 Info calc_hslot_crc16_cluster vs calc_hslot_crc16_with_hash_tag naming confusion Addressed Comment added in 440a37f explaining why tag-aware variant is required here

@fcostaoliveira
fcostaoliveira merged commit f7f8983 into redis:master May 25, 2026
65 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…sed (#448)

2.4 regression flagged by micro-bench: ~4% ops/sec drop on canonical
SET/GET vs 2.3.1. Root cause: bufferevent_enable at the top of
fill_pipeline was added in #390/#400 to recover from --transaction's
hold_pipeline disable, but it fires every fill_pipeline invocation
(per response received) -- taking libevent's BEV_LOCK in the hot
path even when no pause/resume is needed.

Track pause state with bool m_bev_paused; only call bufferevent_enable
when the flag indicates the bufferevent was actually paused. Set the
flag at the disable site, clear it at the existing enable sites
(handle_event, schedule_fill, fill_pipeline's resume branch) and on
bev (re)creation/teardown (setup_event, disconnect). Invariant:
m_bev_paused == true iff bufferevent is in EV_READ|EV_WRITE disabled.

Local micro-bench: server-bound runs against a single localhost Redis
on this box stay within noise (~+0.3% on pipeline=32 clients=50
threads=4 ratio=1:1 300K reqs, 3 runs each) because Redis is the
bottleneck. Forcing the client to be the bottleneck (taskset -c 0,1
clients=100 threads=2 pipeline=32 ratio=1:1 200K reqs, 3 runs each)
shows +12.81% ops/sec recovery (322,237 -> 363,517). Functional
parity verified with --transaction MULTI/SET/EXEC against a manual
3-node cluster (1:1:1 Multis:Sets:Execs ratio, no errors).

Refs: 2.4 review #28 (Review 18 MED finding).

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Jun 2, 2026
…sed (#448)

2.4 regression flagged by micro-bench: ~4% ops/sec drop on canonical
SET/GET vs 2.3.1. Root cause: bufferevent_enable at the top of
fill_pipeline was added in #390/#400 to recover from --transaction's
hold_pipeline disable, but it fires every fill_pipeline invocation
(per response received) -- taking libevent's BEV_LOCK in the hot
path even when no pause/resume is needed.

Track pause state with bool m_bev_paused; only call bufferevent_enable
when the flag indicates the bufferevent was actually paused. Set the
flag at the disable site, clear it at the existing enable sites
(handle_event, schedule_fill, fill_pipeline's resume branch) and on
bev (re)creation/teardown (setup_event, disconnect). Invariant:
m_bev_paused == true iff bufferevent is in EV_READ|EV_WRITE disabled.

Local micro-bench: server-bound runs against a single localhost Redis
on this box stay within noise (~+0.3% on pipeline=32 clients=50
threads=4 ratio=1:1 300K reqs, 3 runs each) because Redis is the
bottleneck. Forcing the client to be the bottleneck (taskset -c 0,1
clients=100 threads=2 pipeline=32 ratio=1:1 200K reqs, 3 runs each)
shows +12.81% ops/sec recovery (322,237 -> 363,517). Functional
parity verified with --transaction MULTI/SET/EXEC against a manual
3-node cluster (1:1:1 Multis:Sets:Execs ratio, no errors).

Refs: 2.4 review #28 (Review 18 MED finding).

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
This was referenced Oct 13, 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.

--cluster-mode breaks WATCH/MULTI/EXEC/UNWATCH state: keyless commands route to a different shard than keyed ones

2 participants