Skip to content

feat(cluster): support --monitor-input with --cluster-mode - #395

Merged
fcostaoliveira merged 5 commits into
masterfrom
feat/monitor-input-cluster-mode
May 27, 2026
Merged

fcostaoliveira merged 5 commits into
masterfrom
feat/monitor-input-cluster-mode

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 25, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Removes the hard block on --monitor-input + --cluster-mode being used together
  • Adds slot-aware routing for monitor-replayed commands in cluster mode: each command's first key is parsed before RESP-formatting, CRC16-hashed, and routed to the owning shard connection
  • Commands destined for another shard are staged (pre-split arbitrary_command + enqueue timestamp) in a per-shard queue; the target shard is woken via schedule_fill() and drains one command per create_request() call
  • Enqueue timestamp is carried through so latency stats measure selection→response, not queue-drain→response

Design decisions

Why store arbitrary_command (pre-split) in the staged struct instead of the raw string?
split_command_to_args() only needs to run once (at routing time, to extract the key). Storing the parsed struct avoids a second parse at drain. format_arbitrary_command() is still deferred to drain time because it mutates arg->data in-place with RESP framing and must run on the receiving connection's protocol.

Why command_args[1] for key extraction?
Correct for the primary use case (GET, SET, MGET with hash-tagged keys). Known limitation: commands where the routing key is not at position 1 (OBJECT ENCODING key, EVAL, subcommand-style) fall back to the local shard and may get MOVED. Documented as a known limitation.

Invariants fixed after 7-model code review

Bug Fix
handle_moved() didn't clear staged queue → stale commands sent to wrong shard after topology change Clear m_staged_monitor_commands[conn_id] alongside key pool in handle_moved()
disconnect() shrank m_connections but not m_staged_monitor_commands → index desync on reconnect pop_back() both vectors in lockstep in disconnect()
hold_pipeline request-limit gate ignored staged queue → commands staged but never drained at --requests limit Add && m_staged_monitor_commands[conn_id].empty() to the gate
Staged queue had no size cap → OOM on skewed workloads Cap at STAGED_MONITOR_QUEUE_MAX_SIZE (1M), drop + inc_error() when full
Error messages in process_staged_monitor_command had no line number Carry source_line in staged_monitor_cmd

Known limitations (acceptable for quick-and-dirty MGET latency measurement)

  • Routing uses command_args[1] as the key; commands with the key at a different position fall back to local shard + MOVED
  • All keys in a multi-key command (MGET) must hash to the same slot — use {hashtag} keys, as Redis cluster requires anyway
  • Sequential replay order is not preserved across shards (inherent to multi-shard staging)
  • retry_after_redirect for MOVED on monitor commands always retries on the same shard (m_key not set on arbitrary_request)

Test plan

  • make — clean build ✅
  • Run with single-shard cluster and a monitor file containing MGET {tag}:f1 {tag}:f2 — verify commands reach the correct shard with no MOVED errors after topology warmup
  • Run with --requests N — verify benchmark exits cleanly without stranding staged commands
  • Run with topology change mid-run — verify no crash and no stale-slot commands after CLUSTER SLOTS refresh

🤖 Generated with Claude Code


Note

Medium Risk
Adds cross-shard staging, slot routing from the first key only, and m_reqs_generated bookkeeping on topology changes—moderate complexity in cluster_client request lifecycle with edge cases (wrong-key position, full queue → MOVED).

Overview
Enables --monitor-input together with --cluster-mode by removing the startup error that previously rejected that combination.

Cluster monitor routing parses each replayed command’s first key (with hash-tag-aware slot calculation), sends on the owning shard when possible, and otherwise stages a pre-split arbitrary_command on that shard’s queue and wakes it with schedule_fill(). Staged work is drained before normal create_request traffic; RESP framing runs at drain time on the target connection. Latency uses the selection/enqueue timestamp, not drain time.

Lifecycle fixes keep --requests runs from hanging: hold_pipeline keeps draining staged queues past the request cap; m_reqs_generated is decremented when staged commands are flushed (topology refresh, shard retire, reconnect, format/send failures). Staged queues are cleared on -MOVED like the key-index pools. .clang-format sets Standard: Cpp03 so nested templates stay > > for the macOS C++03 build.

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

@jit-ci

jit-ci Bot commented May 25, 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

@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.

test review

@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.

test

Comment thread cluster_client.cpp Outdated
return true;
}
staged_monitor_cmd staged{std::move(temp_cmd), stats_index, timestamp, selected_index + 1};
m_staged_monitor_commands[target_conn].push(std::move(staged));

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.

Bug: Routing connection's pipeline is never consumed by staged commands — fill_pipeline spins unthrottled

When create_monitor_request_cluster stages a command to another shard's queue it returns true without calling push_req, so m_pipeline->size() on the routing connection (conn_A) stays 0. The fill_pipeline while-loop exits only when hold_pipeline fires (request limit reached) or finished() returns true.

In a skewed workload where all (or most) keys hash to shard 0, conn_1 … conn_N will each loop through their entire request budget in a single fill_pipeline call, staging millions of entries into m_staged_monitor_commands[0] before any of them are sent on the wire. The 1M STAGED_MONITOR_QUEUE_MAX_SIZE cap is the only backstop; once it is hit every further command is silently counted as an error and dropped.

Failure scenario: 3-shard cluster where all monitor-file keys hash to shard 0. Connections 1 and 2 each run fill_pipeline to exhaustion, staging up to 1M commands each. Shard 0's queue fills instantly; all subsequent routings increment the error counter and are discarded. Effective throughput on shard 0 is capped at one pipeline-depth worth of commands per RTT while shards 1 and 2 sit idle.

Fix: after staging a command, call push_req (or a lightweight placeholder request) on the routing connection so the pipeline depth counter is consumed, or add a per-call staging limit (e.g. return false from create_arbitrary_request instead of true when the target queue already has >= pipeline-depth entries queued).

Comment thread cluster_client.cpp
}
}
// Use the enqueue timestamp so latency reflects selection→response, not drain→response.
m_connections[conn_id]->send_arbitrary_command_end(staged.stats_index, &staged.enqueue_time, cmd_size);

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.

Bug: pipeline desync — send_arbitrary_command_end called when bytes were skipped

process_staged_monitor_command only sends const_type args (lines 681–685). After format_arbitrary_command runs, any arg that contains the __key__ placeholder is reclassified to key_type, and any arg containing __data__ becomes data_type. Both are silently skipped by the send loop. But send_arbitrary_command_end is called unconditionally at line 688, which push_reqs an arbitrary_request and increments m_pending_resp. If zero bytes were actually written (all payload args got reclassified), the connection waits indefinitely for a Redis response that was never sent — hanging the benchmark.

The same issue is present in the inline-send path at line 761 of this PR.

Suggested fix: check cmd_size > 0 before calling send_arbitrary_command_end, or assert that no non-first arg is non-const_type after format (real MONITOR output never contains __key__/__data__ placeholders, so hitting that branch signals a bug).

// guard before line 688 / 761:
if (cmd_size == 0) {
    benchmark_error_log("warning: monitor command produced zero bytes after format, skipping\n");
    return;
}

Comment thread cluster_client.cpp
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
}
}
m_connections[conn_id]->send_arbitrary_command_end(stats_index, &timestamp, cmd_size);

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.

Bug: same pipeline desync as staged path — inline-send also skips non-const_type args but calls send_arbitrary_command_end

Lines 754–760 iterate over temp_cmd.command_args and only send const_type args. If format_arbitrary_command reclassified any arg (e.g., a monitor-file value that happens to contain the __key__ or __data__ string), those bytes are skipped, cmd_size stays at less than the full RESP frame, and the subsequent send_arbitrary_command_end at line 761 pushes a pending response onto the pipeline. Redis will respond to what was sent, which will be misinterpreted (or the connection will deadlock if nothing was sent at all).

Same fix applies: guard with if (cmd_size > 0) or assert all args are const_type after format.

Comment thread cluster_client.cpp
unsigned int target_conn = conn_id;
if (temp_cmd.command_args.size() >= 2) {
const std::string &key = temp_cmd.command_args[1].data;
if (!key.empty()) {

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.

Bug: command_args[1] assumes the key is always the first argument, which is wrong for subcommand-style commands

The code unconditionally treats command_args[1] as the routing key. This assumption breaks for any Redis command where argument 1 is a subcommand rather than a key:

  • "OBJECT" "ENCODING" "mykey" → hashes "ENCODING", not "mykey" (key is at index 2)
  • "OBJECT" "FREQ" "mykey" → same
  • "XREAD" "COUNT" "1" "STREAMS" "streamkey" "0" → hashes "1" (key is after STREAMS keyword)
  • "LMPOP" "2" "key1" "key2" "LEFT" → hashes the count "2", not a key
  • "BITPOS" "key" "1" "0" "8" → this one is fine (key IS at index 1)

A real MONITOR dump — the primary expected input format — will contain a mix of these. Hashing "ENCODING" gives a different slot than the slot owning "mykey", so the command is routed to the wrong shard. The shard will respond with -MOVED, which triggers a topology refresh and drops the command.

Fix: Maintain a table of commands where the key is not at args[1] (e.g. OBJECT→2, XREAD→after STREAMS token). At minimum, fall back to target_conn = conn_id (safe: sends to current shard which will MOVED-redirect if needed) for commands whose args[1] is a known subcommand keyword like ENCODING, FREQ, REFCOUNT, IDLETIME, HELP.

Comment thread cluster_client.cpp
for (unsigned int i = 0; i < staged.parsed_cmd.command_args.size(); i++) {
const command_arg *arg = &staged.parsed_cmd.command_args[i];
if (arg->type == const_type) {
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);

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.

Bug: process_staged_monitor_command silently drops key and value bytes for commands with key/data placeholders

Both process_staged_monitor_command (here) and the inline send path in create_monitor_request_cluster iterate only const_type args after calling format_arbitrary_command. The base-class client::create_arbitrary_request handles all three types (const_type, key_type, data_type).

format_arbitrary_command (redis_protocol) sets a token's type to key_type if its data string contains the __key__ substring, and to data_type if it contains __data__. A monitor file that includes a command with a dynamic key or value placeholder (e.g. SET __key__ __data__) will hit this path.

Failure scenario: user creates a monitor file that mixes literal commands with a SET __key__ __data__ template (a supported pattern per the existing codebase). In cluster mode, after format_arbitrary_command, the arg for __key__ becomes key_type and the arg for __data__ becomes data_type. Both are skipped by the const_type-only loop. send_arbitrary_command_end then calls push_req with cmd_size reflecting only the command-name bulk (e.g. *3\r\n$3\r\nSET\r\n), leaving the RESP array expecting 2 more bulks that are never written. The connection's TCP stream is permanently desynchronised; every subsequent response is misinterpreted.

Comment thread cluster_client.cpp
if (!m_connections[conn_id]->get_protocol()->format_arbitrary_command(staged.parsed_cmd)) {
benchmark_error_log("warning: skipping unformattable staged monitor command at line %zu\n",
staged.source_line);
return;

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.

Bug: early return on format failure causes m_reqs_processed to fall short — benchmark never terminates under --requests

When format_arbitrary_command fails for a staged command, this function returns without calling send_arbitrary_command_end, so no arbitrary_request is pushed and m_pending_resp is not incremented. But m_reqs_generated was already incremented by the routing connection (via client::create_request → create_arbitrary_request → create_monitor_request_cluster returning true). Since client::finished() checks m_reqs_processed >= m_config->requests and m_reqs_processed is only incremented on received responses, each silently-dropped format failure creates a permanent gap. If even one staged command fails format, the run never completes naturally in --requests mode.

The same gap exists for the non-staged (inline-send) path at line 750 — returning true there also over-counts m_reqs_generated.

Fix options:

  1. Call m_stats.inc_error() and explicitly call m_conns_manager->inc_reqs_processed() (or a dedicated counter) for each silently skipped command so the processed count stays in sync.
  2. Return false from create_monitor_request_cluster on format failure so the caller does not advance m_reqs_generated.

Comment thread cluster_client.cpp
int cmd_size = 0;
for (unsigned int i = 0; i < temp_cmd.command_args.size(); i++) {
const command_arg *arg = &temp_cmd.command_args[i];
if (arg->type == const_type) {

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.

Bug: Same const_type-only send path in inline (non-staged) branch also drops key/data args

The inline send path when target_conn == conn_id has the same const_type-only loop as the staged drain path. If a monitor-file command produces a key_type or data_type arg after format_arbitrary_command, those bytes are silently omitted and send_arbitrary_command_end sends a truncated RESP frame, desynchronising the connection.

The base-class client::create_arbitrary_request correctly handles all three arg types with separate branches. Both the staged and inline cluster paths should mirror that logic.

Comment thread cluster_client.cpp
unsigned int target_conn = conn_id;
if (temp_cmd.command_args.size() >= 2) {
const std::string &key = temp_cmd.command_args[1].data;
if (!key.empty()) {

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.

Bug: MGET key1 key2 ... routes by the first key only — all remaining keys are silently sent to the wrong shard

For MGET (and any other multi-key command like DEL key1 key2, SUNIONSTORE dest key1 key2, etc.), the routing uses only command_args[1] (key1). The other keys may hash to different slots/shards. Redis Cluster will reject a cross-slot MGET with:

CROSSSLOT Keys in request do not hash to the same slot

This means any MGET in the monitor file with keys on different shards will always error, and the benchmark will misreport this as a server error rather than a client routing problem.

Fix: Either:

  1. Reject multi-key commands at load time when --cluster-mode is active (similar to how cmd.keys_count > 1 is already rejected for --command args at line 2958 of memtier_benchmark.cpp), or
  2. Route each sub-key independently and split the command into per-shard requests (complex).

Option 1 is the safe choice. The monitor input file could validate that MGET-style commands only use keys with the same hash tag during load_from_file when --cluster-mode is set.

Comment thread cluster_client.cpp Outdated
if (!temp_cmd.split_command_to_args()) {
benchmark_error_log("warning: skipping malformed monitor command at line %zu: %s\n", selected_index + 1,
raw_cmd.c_str());
return true;

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.

Bug: split_command_to_args failure returns true, over-counting m_reqs_generated

When split_command_to_args fails at line 709, this early return at line 712 returns true. The caller (client::create_request, line 596–598) treats true as a successfully generated request and increments m_reqs_generated. No command is sent, no response is expected, but m_reqs_generated advances. In --requests mode, the routing connection can exhaust the requests budget with parse-failed commands, while far fewer real requests are delivered. Worse, if sequential mode is in use (monitor_pattern != 'R'), each parse failure still advances the sequential cursor, silently skipping that position in the file.

The same over-count happens in the inline-send path at lines 749–751.

Consider returning false (no request generated) on parse and format failures, consistent with how get_key_for_conn returning not_available results in returning false elsewhere in create_arbitrary_request.

Comment thread cluster_client.cpp
// Fall back to the current connection if topology isn't ready yet or there is no key.
unsigned int target_conn = conn_id;
if (temp_cmd.command_args.size() >= 2) {
const std::string &key = temp_cmd.command_args[1].data;

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.

Bug: Key routing always reads command_args[1] — wrong for multi-token Redis subcommands

The routing code unconditionally treats command_args[1].data as the key. For single-word commands (SET key val, GET key, HGET key field) this is correct. For multi-word subcommands common in MONITOR output the key is at a different position:

  • OBJECT ENCODING key → key at index 2
  • OBJECT FREQ key → key at index 2
  • XREAD COUNT 1 STREAMS key id → key at index 4
  • CLIENT GETNAME → no key at all

Failure scenario: a monitor file contains OBJECT ENCODING mykey. command_args[0]="OBJECT", command_args[1]="ENCODING", command_args[2]="mykey". The routing code hashes the string "ENCODING" and sends the command to whatever shard owns that slot. The Redis server that receives it returns -MOVED, triggering a topology refresh and stat inaccuracy for every such command. With many such commands the benchmark spends most of its time handling MOVED redirects instead of measuring throughput.

The fix needs a command-specific key-position table or a fallback that detects placeholder keywords (ENCODING, FREQ, IDLETIME, REFCOUNT, STREAMS, …) and advances the argument index accordingly.

Comment thread cluster_client.cpp
{
std::queue<staged_monitor_cmd> empty_staged;
std::swap(m_staged_monitor_commands[conn_id], empty_staged);
}

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.

Bug: dropping the staged queue on MOVED leaves m_reqs_processed permanently short of --requests N, causing the benchmark to hang

When a -MOVED response arrives, handle_moved flushes m_staged_monitor_commands[conn_id] (this line and the surrounding block). Those staged commands had already been counted toward m_reqs_generated by the routing connection that staged them, but they will now never be sent and will never produce a response. Consequently m_reqs_processed can never reach m_config->requests.

client::finished() checks m_reqs_processed >= m_config->requests. If any staged commands were in the flushed queue, m_reqs_processed will be permanently short. The benchmark loops in event_base_dispatch indefinitely — a hang that is silent and requires a SIGINT to stop.

Failure scenario: --cluster-mode --monitor-input workload.txt --requests 1000 with a 3-shard cluster. After 500 requests, a slot migration triggers a MOVED on connection 1. Connection 1 has 50 staged commands queued. They are dropped here. m_reqs_processed tops out at 950, never reaching 1000. Benchmark hangs.

Fix: Instead of silently dropping the flushed staged commands, account for them:

// For each dropped staged command, ensure m_reqs_processed is adjusted
// or explicitly send them on the (new) owning shard after topology refresh.
m_reqs_generated -= m_staged_monitor_commands[conn_id].size();

Or re-queue them for routing after the new CLUSTER SLOTS response is processed.

Comment thread cluster_client.cpp Outdated
// in-place with RESP framing and must be called per-connection at send time.
// Cap the queue to prevent unbounded memory growth under skewed workloads.
if (m_staged_monitor_commands[target_conn].size() >= STAGED_MONITOR_QUEUE_MAX_SIZE) {
benchmark_debug_log("staged monitor queue for conn %u full, dropping command\n", target_conn);

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.

Bug: queue-full drop silently over-counts m_reqs_generated and never completes the run

When the staged queue for target_conn is at capacity (line 737), the command is dropped with m_stats.inc_error() and return true. The caller increments m_reqs_generated for a command that was neither sent nor will produce a response. In --requests mode, each dropped command creates a permanent gap between m_reqs_generated and m_reqs_processed, preventing finished() from returning true.

Under a heavily skewed key distribution (e.g., all keys map to shard 0 but requests arrive on shard 1's connection), this cap is reachable and the run can hang indefinitely even after the queue is eventually drained, because the saturating drops already consumed the requests budget.

Fix: return false so the caller does not count this as a generated request, consistent with how key_index_pool overflow returns not_available / false in get_key_for_conn.

Comment thread cluster_client.cpp
#include "shard_connection.h"

#define KEY_INDEX_QUEUE_MAX_SIZE 1000000
#define STAGED_MONITOR_QUEUE_MAX_SIZE 1000000

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.

Bug: STAGED_MONITOR_QUEUE_MAX_SIZE is dangerously large for struct-sized entries

STAGED_MONITOR_QUEUE_MAX_SIZE is 1,000,000 — copied from KEY_INDEX_QUEUE_MAX_SIZE. But the two queues hold very different data:

  • key_index_pool stores unsigned long long (8 bytes/entry) → ~8 MB at the cap
  • m_staged_monitor_commands stores staged_monitor_cmd structs, each containing an arbitrary_command with a std::vector<command_arg> where every token includes a std::string data field. A typical 3-token monitor command (SET key value) uses ~300–600 bytes. At 1M entries that is 300–600 MB per shard connection that is the target of skewed routing.

With N shard connections all staging to shard 0, and N × 1M entries in-flight, the process can exhaust available memory before the cap on any individual queue is reached (each queue caps independently).

Fix: set STAGED_MONITOR_QUEUE_MAX_SIZE to a small multiple of --pipeline depth (e.g. 2× or 4×) rather than inheriting the key-index pool limit. This also naturally bounds the latency jitter introduced by deep staging.

Comment thread cluster_client.cpp Outdated
// in-place with RESP framing and must be called per-connection at send time.
// Cap the queue to prevent unbounded memory growth under skewed workloads.
if (m_staged_monitor_commands[target_conn].size() >= STAGED_MONITOR_QUEUE_MAX_SIZE) {
benchmark_debug_log("staged monitor queue for conn %u full, dropping command\n", target_conn);

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.

Bug: queue-full drop increments m_reqs_generated but never m_reqs_processed, causing benchmark hang under -n

When the staged-command queue is full (>= STAGED_MONITOR_QUEUE_MAX_SIZE), the command is dropped and this function returns true. The caller create_arbitrary_request propagates true to client::create_request, which then calls advance_arbitrary_command_index() and increments m_reqs_generated. But since no request was ever sent and no response will arrive, m_reqs_processed is never incremented for this slot.

With --requests N, client::finished() checks m_reqs_processed >= N. Each dropped-and-counted command widens the gap between m_reqs_generated and m_reqs_processed by one, permanently. The benchmark will loop forever once m_reqs_generated has reached N but m_reqs_processed is short by the number of dropped commands.

Failure scenario: --requests 1000000 --threads 8 --clients 50 on a skewed 3-shard workload where 95% of keys hash to shard 0. Shard 0's staged queue (fed by shards 1 and 2) saturates at 1,000,000. Each subsequent command routed to shard 0 is dropped, m_reqs_generated keeps ticking but m_reqs_processed stalls. Benchmark never terminates.

Fix: Do not return true on drop (which tells the caller to count this as a generated request). Return false to indicate no request was produced, or compensate with m_reqs_generated-- after the drop, or subtract from m_reqs_generated before returning.

Comment thread cluster_client.cpp Outdated
}
staged_monitor_cmd staged{std::move(temp_cmd), stats_index, timestamp, selected_index + 1};
m_staged_monitor_commands[target_conn].push(std::move(staged));
m_connections[target_conn]->schedule_fill();

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.

Race: staged command silently lost if target shard disconnects between the state check and schedule_fill()

The shard's connection state is checked at line 723–725 before setting target_conn. If the shard disconnects in the narrow window between that check and the schedule_fill() call at line 744, schedule_fill returns immediately (guarded by m_connection_state != conn_connected in shard_connection::schedule_fill). The command is now staged in m_staged_monitor_commands[target_conn] but nothing will wake up that shard to drain it — until the shard reconnects (which calls fill_pipeline()) or another command happens to route through it.

This is a correctness window rather than a guaranteed hang (reconnect drains the queue), but under no-reconnect configurations or high-disconnect rates, staged commands can accumulate without forward progress and the queue cap may be hit, causing additional drops.

Mitigation: after staging, check the connection state again; if it is now conn_disconnected, send the command on the fallback connection instead of staging it.

Comment thread cluster_client.cpp Outdated
delete sc;
// m_key_index_pools entries are intentionally kept (owned heap objects reused on reconnect)
// m_staged_monitor_commands must shrink to match m_connections so indices stay valid
m_staged_monitor_commands.pop_back();

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.

Bug: disconnect() shrinks m_staged_monitor_commands but NOT m_key_index_pools — vector sizes diverge after reconnect

In disconnect(), the loop at lines 201–208 calls m_connections.pop_back() and m_staged_monitor_commands.pop_back() together — keeping both in sync. However m_key_index_pools is intentionally NOT shrunk (heap objects reused on reconnect).

After a full disconnect (N shards → 1), the sizes are:

  • m_connections.size() = 1
  • m_staged_monitor_commands.size() = 1
  • m_key_index_pools.size() = N

On the very next call to connect(), the guard if (m_key_index_pools.empty()) at line 155 is false, so nothing is pushed, and the assertion assert(m_connections.size() == m_key_index_pools.size()) at line 160 fires: 1 == N → assertion failure / abort.

This regression is introduced by this PR: before the PR, the assertion at line 160 was already in the code for m_key_index_pools, but since the PR adds a second parallel vector with different shrink behaviour, the asymmetry between the two is now encoded permanently in disconnect() and made structural.

Fix: either shrink m_key_index_pools in disconnect() (delete the heap objects rather than keeping them), or do NOT shrink m_staged_monitor_commands in disconnect() — just swap-clear each entry in-place instead of popping.

Comment thread cluster_client.cpp
benchmark_error_log("warning: skipping unformattable staged monitor command at line %zu\n",
staged.source_line);
return;
}

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.

Bug: process_staged_monitor_command skips send_arbitrary_command_end on format failure, leaving m_reqs_processed short

When format_arbitrary_command fails for a staged command (line 120), the function returns early without calling send_arbitrary_command_end. No arbitrary_request is pushed to the pipeline. No response will arrive. But m_reqs_generated was already incremented when the command was first selected and staged by the routing connection.

The result is the same hang as with queue-full drops: m_reqs_processed will never reach m_config->requests when any staged command fails to format.

This cannot happen with the current split_command_to_args() + format_arbitrary_command() pair for a typical RESP-format monitor file, but it is a latent correctness issue if the protocol changes or if a malformed line slips through.

Fix: Track the skip so m_reqs_generated is corrected:

if (!m_connections[conn_id]->get_protocol()->format_arbitrary_command(staged.parsed_cmd)) {
    benchmark_error_log(...);
    m_reqs_generated--;   // undo the count from the routing side
    return;
}

Alternatively, call send_arbitrary_command_end with cmd_size = 0 and let the response handler treat it as an error, which maintains symmetry with the malformed-command path in client::create_arbitrary_request.

Comment thread cluster_client.cpp Outdated
delete sc;
// m_key_index_pools entries are intentionally kept (owned heap objects reused on reconnect)
// m_staged_monitor_commands must shrink to match m_connections so indices stay valid
m_staged_monitor_commands.pop_back();

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.

Asymmetry: m_staged_monitor_commands is shrunk in disconnect() but m_key_index_pools is intentionally kept — invariant inconsistency

The comment says m_key_index_pools entries are intentionally retained across disconnect/reconnect. But m_staged_monitor_commands is popped here to match m_connections. This means after a disconnect+reconnect cycle, the two vectors are managed differently: m_key_index_pools holds stale entries from the old topology (with sizes surviving the shrink), while m_staged_monitor_commands is cleared for those same slots.

The assertion at connect() (line 161) guards m_connections.size() == m_staged_monitor_commands.size() but there is no guard that m_staged_monitor_commands.size() == m_key_index_pools.size(). After a topology change where the cluster shrinks to fewer shards and then grows again via create_shard_connection, the two parallel vectors can diverge silently if the connect() guard path (the m_key_index_pools.empty() branch) is taken inconsistently.

Consider documenting this explicitly, or aligning the management so both vectors are either shrunk together or both kept. Mismatched management is a future source of index-out-of-bounds bugs.

Comment thread cluster_client.cpp Outdated
}
staged_monitor_cmd staged{std::move(temp_cmd), stats_index, timestamp, selected_index + 1};
m_staged_monitor_commands[target_conn].push(std::move(staged));
m_connections[target_conn]->schedule_fill();

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.

Bug: schedule_fill() called while target shard may be in setup state — commands staged before setup_done are lost on next MOVED flush

In create_monitor_request_cluster, before staging the command the code correctly checks m_connections[shard]->get_cluster_slots_state() == setup_done. If that check fails, target_conn falls back to conn_id — good.

However, between the time schedule_fill() is called and the time the deferred timer fires, the target shard's connection state can transition from setup_done to receiving a MOVED response. handle_moved then calls std::swap(m_staged_monitor_commands[conn_id], empty_staged) — flushing all queued staged commands for that connection, including those staged after the state appeared valid.

This is a TOCTOU window: the state is checked at staging time (line 723–726), but the flush happens asynchronously when MOVED arrives. The commands are silently lost (no error counter increment, no log line) because the staged-queue flush in handle_moved does not account for how many commands it discarded.

Fix: increment m_stats.inc_error() (or a dedicated dropped-staged counter) once per command flushed from m_staged_monitor_commands inside handle_moved and connect_shard_connection, so dropped staged commands are visible in the output statistics.

Comment thread cluster_client.cpp
/* --monitor-input in cluster mode: select the command, parse its first key, and route
* to the shard that owns that slot. Commands for other shards are staged and that shard
* is woken up via schedule_fill(); this connection returns immediately without sending. */
if (cmd.command_args.size() == 1 && cmd.command_args[0].type == monitor_random_type) {

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.

Design concern: MOVED/ASK responses for monitor-replayed commands are not retried on the correct shard

When a monitor command is sent via create_monitor_request_cluster (either inline or via drain), a MOVED or ASK error means the key actually lives on a different shard than the one computed from m_slot_to_shard. The existing handle_response path calls retry_after_redirect, which requires req->m_serialized to be populated (set by capture_serialized_bytes inside send_arbitrary_command_end). Capture only happens when retry_on_error is enabled.

Without --retry-on-error, a MOVED/ASK for a monitor command is silently counted as a redirect error and dropped via finalize_dropped_redirect, which calls m_stats.inc_error(). The monitor command is not replayed. This is the same behavior as other arbitrary commands, but the user may not expect it when feeding a MONITOR file — the cluster map provided by MONITOR output should already be consistent with CLUSTER SLOTS, so a MOVED response suggests a topology lag.

Consider logging a warning the first time a monitor-replayed command receives MOVED/ASK, to alert users that the MONITOR file was captured from a different topology snapshot.

Comment thread cluster_client.cpp
if (m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_reqs_generated >= m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_staged_monitor_commands[conn_id].empty() &&
m_reqs_generated >= m_config->requests) {

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.

Bug: hold_pipeline allows draining staged commands past the -n request limit, but the drain connection has no corresponding m_reqs_generated increment

The hold_pipeline modification correctly checks m_staged_monitor_commands[conn_id].empty() before holding the drain connection. However, the drain path (process_staged_monitor_command → send_arbitrary_command_end) does not increment m_reqs_generated, and does not call advance_arbitrary_command_index().

For the request-counting logic to stay balanced, each request that produces a response (i.e., each send_arbitrary_command_end call) must correspond to exactly one m_reqs_generated++. The routing side increments it, the drain side does not — which is the stated design. But hold_pipeline gates on m_reqs_generated >= m_config->requests to throttle the routing connection. Once the routing connection is held, it can no longer route any new commands to the drain connections. However, if the drain connection's staged queue still has entries, it will keep draining them (the m_staged_monitor_commands[conn_id].empty() bypass prevents hold). This is intentional.

The subtle correctness issue: if --requests 1000 is set and exactly 1000 commands are selected (routing side), some of those may be in staged queues. The routing connection hits m_reqs_generated = 1000 and stops. Drain connections process what's in their queues. This is correct.

But — advance_arbitrary_command_index() is also NOT called on the drain path. For sequential monitor pattern (-P S), the global next_index counter was already advanced by get_next_sequential_command at routing time. For random pattern this is immaterial. This is fine.

This is more of a documentation gap than a bug, but worth noting: the "already counted by the routing side" comment (line 71) is correct for m_reqs_generated but incorrect for m_reqs_processed — responses come from the drain connection, not the routing one. The net result is still correct since m_reqs_processed is incremented per-response regardless of which connection sent the request.

Comment thread cluster_client.cpp
* is reached, since those were already counted by the routing side. */
if (m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_reqs_generated >= m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_staged_monitor_commands[conn_id].empty() &&

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.

Bug: hold_pipeline bypass for staged drain does not fire when finished() returns true — staged commands are silently abandoned at benchmark end

fill_pipeline's while-loop condition is !m_conns_manager->finished() && m_pipeline->size() < m_config->pipeline. Once finished() returns true (m_reqs_processed >= m_config->requests), the loop body — including the hold_pipeline bypass that was added to allow staged drain — is never reached.

The hold_pipeline change at lines 370–375 correctly allows a connection to keep draining its staged queue after the request limit is hit, but it only guards the hold_pipeline break inside the loop. It has no effect on the outer finished() guard that prevents the loop from running at all.

Failure scenario: with --requests=10000 and a skewed key space, shard 0 accumulates staged commands from shards 1–N. Responses arrive on shards 1–N quickly, m_reqs_processed reaches 10000, finished() fires, and shard 0's fill_pipeline loop exits without draining its staged queue. Those commands are never sent; the benchmark exits with silent loss of all unprocessed staged entries. The --requests count appears satisfied but the actual number of commands executed on each shard will be far less than expected.

Fix: add a separate drain path that runs even when finished() is true — e.g. loop over non-empty staged queues after the main while-loop, or change the loop condition to also check !any_staged_queue_non_empty().

Comment thread cluster_client.cpp Outdated
uint32_t slot = calc_hslot_crc16_with_hash_tag(key.c_str(), key.size());
uint32_t shard = m_slot_to_shard[slot];
if (shard < m_connections.size() &&
m_connections[shard]->get_connection_state() != conn_disconnected &&

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.

Bug: keyless commands (e.g. PING, INFO, CLIENT LIST) are routed to target_conn = conn_id (correct fallback), but if the monitor file is a real MONITOR dump, these commands will still arrive here and be sent on an arbitrary shard — which is fine for stateless commands but silently wrong for connection-scoped commands like CLIENT SETNAME, SELECT, or AUTH

For keyless commands (command_args.size() < 2 or the key field is empty), target_conn stays as conn_id and the command is sent on whichever shard happens to call create_arbitrary_request first. For stateless commands (PING, INFO) this is harmless. For connection-scoped commands seen in MONITOR output (CLIENT SETNAME "foo", AUTH password, SELECT 0), sending them on a random shard modifies per-connection state on that shard. In a benchmark context this is likely benign (no one inspects connection names), but AUTH and SELECT could break subsequent commands on that connection.

More critically, "CLIENT" "SETNAME" "myname" has command_args.size() == 3 with command_args[1].data = "SETNAME". The routing code will compute the CRC16 of "SETNAME" and route to whatever shard owns that slot — sending a connection-management command to a potentially different shard than intended.

Recommendation: Add a startup-time filter in memtier_benchmark.cpp that, when --cluster-mode and --monitor-input are both set, warns about (or rejects) commands that are connection-scoped or have non-standard key positions. This would catch CLIENT, AUTH, SELECT, OBJECT, XREAD, LMPOP, etc.

Comment thread cluster_client.cpp Resolved
Comment thread cluster_client.cpp
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
}
}
m_connections[conn_id]->send_arbitrary_command_end(stats_index, &timestamp, cmd_size);

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.

Accounting asymmetry + --requests hang risk: inline send has no cmd_size == 0 guard.

The staged-drain path in process_staged_monitor_command rolls back the generated-count when a formatted command produces no sendable bytes:

if (cmd_size == 0) {
    m_reqs_generated--;   // line 694
    return;
}

But this inline path unconditionally calls send_arbitrary_command_end(stats_index, &timestamp, cmd_size) even when cmd_size == 0, then returns true so client::create_request (client.cpp:598) does m_reqs_generated++. send_arbitrary_command_end always push_req()s a request (shard_connection.cpp:1375), but zero bytes are written to the socket, so the server never replies and m_reqs_processed never increments for it. Under --requests N, m_reqs_generated reaches the cap while m_reqs_processed lags by one forever -> hang.

The exact same degenerate command (one whose args all reclassify to key/data/cursor placeholders, leaving no const_type) is handled correctly when it's staged for another shard but hangs when its slot happens to belong to conn_id. Behavior should not depend on routing. Mirror the staged guard here: if cmd_size == 0, skip send_arbitrary_command_end and return false.

Comment thread cluster_client.cpp
shard_connection *sc = m_connections.back();
m_connections.pop_back();
delete sc;
// m_key_index_pools and m_staged_monitor_commands are intentionally NOT shrunk:

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.

Completeness audit — disconnect() (verified OK, no compensation needed here).

This PR's fix makes disconnect() no longer pop/clear m_staged_monitor_commands — it deliberately leaves the parallel vectors at full size and lets connect_shard_connection() (clear site 1) or handle_cluster_slots() (clear site 2) do the clear+decrement on reconnect/retirement. That is the correct call:

  • No m_reqs_generated decrement belongs here, because no entry is discarded here.
  • No double-compensation risk vs the destructor: ~cluster_client() (lines 133-140) only frees m_key_index_pools and never touches the staged queues, so they are destroyed implicitly with no decrement. Since the benchmark has ended by then, the leftover m_reqs_generated bookkeeping is irrelevant.
  • The pending in-flight requests dropped in shard_connection::disconnect() (m_pending_resp/pop_req) are a separate set from the never-sent staged commands, so there is no overlap or double-count between the two.

Comment thread cluster_client.cpp
* is reached, since those were already counted by the routing side. */
if (m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_reqs_generated >= m_config->requests) {
if (m_key_index_pools[conn_id]->empty() && m_staged_monitor_commands[conn_id].empty() &&

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.

Completeness audit — hold_pipeline() gate (verified OK, read-only).

Adding && m_staged_monitor_commands[conn_id].empty() to the request-limit gate is necessary and correct: it lets a connection keep being filled past the --requests limit only to drain already-staged (already-counted) commands. Without it, commands staged near the limit would be stranded and a --requests run would hang. This is a read of the queue, no enqueue/dequeue/clear, so no m_reqs_generated change — consistent with the invariant.

Comment thread cluster_client.cpp
// commands route correctly. Sending here is safe and avoids a --requests hang
// that would result from silently dropping a counted request.
benchmark_debug_log("staged monitor queue for conn %u full, sending directly on conn %u (expect MOVED)\n",
target_conn, conn_id);

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.

Potential m_reqs_generated double-decrement when queue-full fallback triggers handle_moved

There is an accounting edge case in the queue-full fallback path in create_monitor_request_cluster (lines 767-772):

When m_staged_monitor_commands[target_conn].size() >= STAGED_MONITOR_QUEUE_MAX_SIZE, the code falls through and sends the command directly on conn_id instead. The command is sent and m_reqs_generated is incremented via send_arbitrary_command_end. So far correct.

Redis responds with -MOVED, which triggers handle_moved(conn_id, ...). Inside handle_moved, the code flushes m_staged_monitor_commands[conn_id] and decrements m_reqs_generated -= empty_staged.size() for those staged entries. This is also correct for those staged entries.

However: the original queue-full command that just got -MOVED was already accounted for by update_moved_arbitrary_op in the stats path at the top of handle_moved. It does not touch m_reqs_generated. So the queue-full command's response handling is separate from the staged-queue flush, and there is no double-decrement for that specific command. That part is fine.

The concern is more subtle: after the queue-full fallback fires on conn A and MOVED comes back, handle_moved flushes all of A's staged queue. But A's staged queue was populated by other connections routing to A — not by the queue-full command itself (which was sent to the wrong shard, conn B's queue was full, so it went directly on A). The staged queue being flushed is A's own inbound queue (commands FROM others TO A), not B's queue. m_reqs_generated is decremented by A's staged queue size, which is correct and unrelated to the queue-full event.

This is not a bug, but the comment on the queue-full fallback path (line 768: «Redis will issue -MOVED; handle_moved() refreshes topology so future commands route correctly») could mention the side-effect: handle_moved will also flush A's staged queue and adjust m_reqs_generated. A reader could otherwise wonder whether the queue-full path creates any accounting asymmetry.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Completeness audit — m_staged_monitor_commands / m_reqs_generated invariant

I did an exhaustive audit of every site touching m_staged_monitor_commands across the whole repo (grep -rn → only cluster_client.cpp/cluster_client.h). The invariant holds at all sites. Inline comments document each one; summary below.

Line Site Category Accounting Verdict
158 connect() emplace_back() vector grow n/a OK
224 create_shard_connection() emplace_back() vector grow n/a OK
240/244 connect_shard_connection() swap Clear -= size OK
352-355 handle_cluster_slots() slotless retire Clear -= size OK
384 hold_pipeline() gate read n/a OK
650 create_request() drain trigger read n/a OK
682-710 process_staged_monitor_command() Dequeue send→m_reqs_processed++ OR m_reqs_generated-- (both skip paths) OK
761-765 create_monitor_request_cluster() push Enqueue return true → m_reqs_generated++ OK
824-827 handle_moved() swap Clear -= size OK

Specific points raised in the review brief

  1. ~cluster_client() destructor (lines 133-140): does NOT clear the staged queues — only frees m_key_index_pools; the staged-queue vector is destroyed implicitly with no decrement. Correct: the benchmark is over, so m_reqs_generated bookkeeping is moot. No leak, no compensation needed.

  2. disconnect() no longer pops (this PR's fix): leaves the parallel vectors at full size; the clear+decrement happens later in connect_shard_connection() or handle_cluster_slots(). No double-compensation with the destructor (destructor never decrements). The in-flight m_pending_resp requests dropped in shard_connection::disconnect() are a separate set from the never-sent staged commands — no overlap.

  3. shard_connection.cpp / elsewhere: no code outside cluster_client.cpp references m_staged_monitor_commands. The only cross-file interaction is inc_reqs_processed() (shard_connection.cpp:915), called only on response receipt — which closes the loop for successfully-drained staged commands.

  4. handle_ask() vs handle_moved() — handle_ask (lines 835-852) does not clear the staged queue, and that is correct, not a gap. ASK is a transient single-key redirect that does not transfer slot ownership; conn_id still owns the slot, so its staged commands remain validly routed and will drain → produce responses. Clearing on ASK would wrongly discount commands that are still going to be sent, under-counting m_reqs_generated and breaking the invariant in the opposite direction. A real topology change is signalled by MOVED, which does the clear+decrement. (Couldn't post this inline — handle_ask is entirely outside the PR diff.)

Conclusion

Every enqueue is counted, every clear decrements by the discarded size, every dequeue either yields one response or decrements. No leaks, no double-counts, no --requests hang vector found. All sites audited — invariant maintained.

Comment thread cluster_client.cpp
std::swap(*m_key_index_pools[conn_id], empty_queue);
{
std::queue<staged_monitor_cmd> empty_staged;
std::swap(m_staged_monitor_commands[conn_id], empty_staged);

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.

Design choice / Missing re-route: staged monitor commands are dropped on MOVED instead of re-routed after topology refresh

After handle_moved calls set_cluster_slots(), the new topology will be populated by handle_cluster_slots. At that point, m_slot_to_shard is authoritative. The staged commands that were just flushed still have their parsed keys — if they had been saved rather than destroyed, they could be re-routed to the correct new shard.

Compare with the non-monitor path: m_key_index_pools[conn_id] is flushed on MOVED, and key indices are simply regenerated fresh on the next fill cycle. Key generation is cheap (just advancing a counter or RNG). Monitor commands, by contrast, consume from a fixed corpus via get_next_sequential_command or get_random_command. Flushing them:

  • Under sequential pattern (-m S): permanently skips those commands in the file, potentially skewing the replay distribution.
  • Under random pattern (-m R): loses those specific selections (though the distribution is maintained statistically).

For a benchmark that is trying to replay a real-world workload exactly (the stated goal of --monitor-input), silently skipping commands on each topology change is a fidelity defect, not just an efficiency concern.

A more correct approach would be to defer the staged-queue flush to after handle_cluster_slots has updated m_slot_to_shard, and then re-queue each command to the new owner:

0 ""

0 ""

0 ""

1 "/usr/include/stdc-predef.h" 1 3 4

0 "" 2

1 ""

This is architecturally more complex (handle_cluster_slots would need to re-route per-command, and the staged queue can't be held in the old slot ownership), but it preserves workload fidelity.

Short-term fix: at minimum, document the fidelity tradeoff explicitly in the comment. The current comment only mentions m_reqs_generated correctness, not workload replay accuracy.

Comment thread cluster_client.cpp
std::swap(m_staged_monitor_commands[conn_id], empty_staged);
// Staged commands were already counted in m_reqs_generated at staging time.
// Compensate so a --requests run does not hang waiting for phantom responses.
m_reqs_generated -= empty_staged.size();

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.

Acceptable tradeoff: m_reqs_generated compensation is correct but asymmetric with key_index_pool

The accounting logic here is correct: m_reqs_generated is incremented when a monitor command is staged (because create_monitor_request_cluster returns true and fill_pipeline counts it), and it is decremented when the staged entry is flushed without being sent. No phantom responses, no --requests hang. Good.

What is worth noting for future readers is the asymmetry with m_key_index_pools: key pool entries are flushed at line 821 without a m_reqs_generated adjustment, because key pool entries are pre-staged before counting (the request is only counted when create_request/create_arbitrary_request actually calls send_arbitrary_command_end). Staged monitor commands, by contrast, are counted at staging time (the routing connection's return-true path increments the counter immediately), so they require the compensating decrement on flush.

This difference in when counting happens is a correctness constraint that is easy to violate in future changes. Consider adding a comment to the staged_monitor_cmd struct in cluster_client.h that documents this invariant: «commands are counted in m_reqs_generated at staging time (not drain time); any flush that does not result in a sent command must decrement m_reqs_generated by the number of flushed entries.»

Comment thread cluster_client.cpp
cmd_size += m_connections[conn_id]->send_arbitrary_command(arg);
}
}
if (cmd_size == 0) {

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.

cmd_size == 0 guard: reachability analysis and spin risk

Is this path reachable for valid monitor commands?

Tracing the full call chain: format_arbitrary_command (redis_protocol) sets every arg that has no placeholder to const_type, then prepends RESP framing (*N\r\n$L\r\n) and appends \r\n to arg->data in-place. write_arbitrary_command(arg) returns arg->data.length() which is always positive after formatting, even for an empty-token arg like "". So cmd_size == 0 cannot be triggered by any command that split_command_to_args() tokenised into at least one arg.

The only way to reach this guard is if command_args is empty after a successful split_command_to_args() call. That happens when the string passed to the arbitrary_command constructor is all-whitespace (the tokeniser skips whitespace, finds *p == 0, returns true with zero tokens). load_from_file never stores such strings — it only records lines that contain a " character, starting from that quote — so in practice this guard is unreachable for the current file loader.

What happens if the guard IS triggered despite the above?

create_monitor_request_cluster returns false. Back in client::create_request (client.cpp line 596), a false return means m_reqs_generated is not incremented and advance_arbitrary_command_index is not called. fill_pipeline's loop condition (m_pipeline->size() < m_config->pipeline) is still true because the pipeline grew by zero, so the next iteration calls create_request again with the same command index. If the same command continues to produce zero bytes on every call, the loop spins indefinitely at 100% CPU with no forward progress or termination.

Comparison with the staged-path guard at line 703

The staged-path guard is structurally correct: it decrements m_reqs_generated (compensating the increment done at staging time) and returns void, which is fine because fill_pipeline on that connection did advance the pipeline when the command was first staged.

This inline-send path is different. m_reqs_generated has NOT been incremented yet when create_monitor_request_cluster is entered — the increment only happens in client::create_request on a true return. So returning false here does the right accounting (no phantom count), but it leaves fill_pipeline free to loop on the same command index indefinitely.

Recommendation

Because the guard is unreachable given current load_from_file invariants, this is not an active bug. To harden it against future regressions:

  1. Add an assertion immediately after split_command_to_args() succeeds: assert(!temp_cmd.command_args.empty()). This turns the silent spin into a loud crash during development/testing.
  2. If a runtime check is preferred over an assert, add a benchmark_error_log and return false (already present), but also add a comment explicitly warning about the spin risk so future readers can evaluate whether return true (skipping without counting) would be safer.

Returning true here is not straightforwardly safe either — it would cause client::create_request to increment m_reqs_generated and advance the command index for a request that was never sent, producing an off-by-one undercount and a response hang. So return false remains correct; it just needs the spin risk called out.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

CI is fully green (69/70 checks — only Cursor Bugbot bot analysis pending, not a required check, commit c98d946). macOS build fixed with -std=c++11. Independent code review confirmed no correctness bugs. Ready for approval @paulorsousa

@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.

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

Comment thread cluster_client.cpp Resolved
fcostaoliveira and others added 5 commits May 28, 2026 00:21
Allow replaying a Redis MONITOR capture file (--monitor-input) against
an OSS cluster (--cluster-mode). Previously the two flags were hard
blocked from being used together.

Design: when create_arbitrary_request sees a monitor_random_type
placeholder in cluster mode, it calls create_monitor_request_cluster
instead of the base-class path. That method:

  1. Selects a command from the monitor file (sequential or random).
  2. Calls split_command_to_args to parse; reads command_args[1].data
     (the raw key, before format_arbitrary_command RESP-frames it) to
     compute the CRC16 slot via calc_hslot_crc16_with_hash_tag.
  3. If the slot belongs to this connection: format_arbitrary_command +
     send inline, using the selection timestamp for latency accuracy.
  4. If the slot belongs to another shard: stash the already-split
     arbitrary_command in m_staged_monitor_commands[target] (avoids
     re-parsing at drain), record the enqueue timestamp, and call
     schedule_fill to wake that shard.

create_request checks m_staged_monitor_commands[conn_id] first; when
non-empty it calls process_staged_monitor_command which formats and
sends using the enqueue timestamp so latency measures selection to
response, not drain to response.

Invariant maintenance fixed after 7-model code review:
- handle_moved() clears staged commands for the affected connection
  alongside the key pool flush (stale topology → wrong-shard sends).
- disconnect() pops m_staged_monitor_commands in lockstep with
  m_connections to prevent index desync after topology changes.
- hold_pipeline request-limit gate checks the staged queue so commands
  already counted by the routing side are never stranded.
- Staged queue is capped at STAGED_MONITOR_QUEUE_MAX_SIZE (1 M) to
  match KEY_INDEX_QUEUE_MAX_SIZE; excess commands are dropped and
  counted as errors.
- source_line is carried in staged_monitor_cmd so error messages
  in process_staged_monitor_command show the monitor file line.

Known limitations (quick-and-dirty):
- Routing uses command_args[1] as the key; commands where the routing
  key is not at position 1 (OBJECT ENCODING, EVAL, etc.) fall back to
  the local shard and may receive MOVED.
- All keys in a multi-key command (MGET) must hash to the same slot
  (use {hashtag} keys); cross-slot MGET produces CROSSSLOT errors.
- Sequential replay order is not preserved across shards.
- retry_after_redirect for MOVED on monitor commands always retries on
  the same shard (m_key not set on arbitrary_request).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Three bugs found in round-2 review of the --monitor-input + --cluster-mode
implementation:

1. disconnect() shrunk m_staged_monitor_commands via pop_back while
   m_key_index_pools was intentionally kept, creating a vector size divergence
   that would fire the create_shard_connection assertion on re-connect.
   Fix: remove the pop_back; both parallel vectors now follow the same
   "keep-on-disconnect, clear-on-reconnect" policy.

2. Error paths in create_monitor_request_cluster() returned true on
   split/format failure, causing m_reqs_generated to increment without a
   matching response, hanging any --requests run.
   Fix: return false for split and format failures (no request was sent, so
   don't count it); for a full staged queue, fall through to direct send on
   the routing connection instead of dropping silently (Redis issues -MOVED
   which handle_moved() handles gracefully).

3. process_staged_monitor_command() returned early on format failure without
   undoing the m_reqs_generated increment that occurred at staging time, also
   causing a --requests hang.
   Fix: decrement m_reqs_generated on format failure and on the cmd_size==0
   defensive guard so the accounting stays balanced.

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

Every time a staged monitor command is discarded without being sent,
m_reqs_generated must be decremented to match — otherwise a --requests run
hangs waiting for responses that will never arrive.

Three sites were clearing m_staged_monitor_commands without the compensating
decrement:

- connect_shard_connection(): clears the queue on shard reconnect.
- handle_cluster_slots() retire path: retires shards that lost all slots by
  calling disconnect() without flushing staged queues; hold_pipeline() then
  blocks those connections permanently so they can never drain.
- handle_moved(): flushes the routing connection's staged queue on topology
  change.

Fix: capture the old queue size before each swap-with-empty and subtract it
from m_reqs_generated.

Also add a cmd_size == 0 defensive guard to the inline send path in
create_monitor_request_cluster() to match the guard already present in
process_staged_monitor_command() — if format_arbitrary_command somehow
produced no sendable bytes, return false rather than pushing a phantom
request that the server would never respond to.

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

The conn_disconnected guard on the retire loop in handle_cluster_slots() was
gating both the staged-queue flush and the disconnect() call together. A shard
can be already disconnected (TCP dropped mid-run before handle_cluster_slots is
called) while still holding staged monitor commands that were counted in
m_reqs_generated at staging time.

With the old code: close_sc[i]==true but get_connection_state()==conn_disconnected
→ entire if-body skipped → staged queue never flushed → m_reqs_generated never
compensated → hold_pipeline returns true for the dead connection forever →
--requests run hangs indefinitely.

Fix: decouple the two operations. The staged-queue flush and m_reqs_generated
compensation now run unconditionally for any retired shard (close_sc[i]==true).
The disconnect() call remains guarded by the != conn_disconnected check to avoid
double-disconnecting an already-down shard.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add Standard: Cpp03 to .clang-format so nested templates keep '> >'
spacing (not '>>'), which is required for the macOS C++03-compatible
build (clang -std=c++03 rejects '>>' inside template argument lists).

Fix cluster_client.h:43 (m_staged_monitor_commands) to use '> >' and
reformat cluster_client.cpp / cluster_client.h to satisfy the
clang-format check.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@fcostaoliveira
fcostaoliveira force-pushed the feat/monitor-input-cluster-mode branch from c98d946 to 887d1e1 Compare May 27, 2026 23:21
@fcostaoliveira
fcostaoliveira merged commit 41f8166 into master May 27, 2026
29 checks passed
fcostaoliveira added a commit that referenced this pull request May 29, 2026
…-then-stage

Closes the biggest open test gap from the 2.3.1->master coverage audit: every
test in tests/test_monitor_input.py is env.skipOnCluster(), so the cluster
route-then-stage path (#395) shipped with zero automated cluster CI.

Adds tests/test_monitor_cluster.py (OSS-CLUSTER only) with deterministic
assertions on the staged-routing path:
- specific __monitor_line1__ SET commits to its slot owner and nowhere else
  (exactly one copy cluster-wide);
- sequential __monitor_line@__ over N distinct keys routes and commits every
  one (total DBSIZE == N across >=2 shards) -- proves no command is lost to a
  wrong-shard send and the staged-queue accounting nets out (run terminates);
- random __monitor_line@__ completes without hang and distributes across shards;
- mixed SET+GET stream attributes per-type stats correctly after cross-shard
  staging (Sets+Gets counts sum to Totals).

Topology-churn-during-replay (slot migration mid-run) is intentionally NOT
covered here -- it is inherently racy in this harness and remains a tracked gap.

Validated against a local 3-node cluster; skips cleanly on standalone.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
fcostaoliveira added a commit that referenced this pull request Oct 15, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 15, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 16, 2026
A --monitor-input line replayed through --command=__monitor_line@__ is
parsed at runtime, and the @ send loops had their own copy of the
argument-writing logic instead of the --command path's:

- Single endpoint (client.cpp): the key_type case sent only the generated
  key and ignored has_key_affixes, so user:__key__ or {tag}__key__ was
  written as a bare memtier-NNN key (#655).
- Cluster mode (cluster_client.cpp, inline and staged sends): only
  const_type arguments were written, so a line with __key__ or __data__
  went out one argument short of its *N header. The server waited for
  the missing bulk string and the run hung or desynced (#654). Routing
  also hashed the literal "user:__key__" text, not the key that would be
  sent.

Add client::resolve_monitor_placeholders(), called right after
split_command_to_args() in both monitor paths. It replaces __key__ with
a generated key, keeping the text around it (the same prefix + key +
suffix as the --command path), and a bare __data__ with a generated
value. Every argument is then a constant, so the existing const-only
send loops write the whole command, the staged cluster queue carries a
complete command, and the cluster slot is computed from the key that is
actually sent. __data__ mixed with other text is left alone and still
rejected by format_arbitrary_command(), as before.

Also drop the outdated README sentence saying monitor input is single
endpoint only (cluster support landed in #395).

Fixes #654
Fixes #655

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.

1 participant