Skip to content

feat(retry): --retry-on-error with bytes-snapshot resend + failed-keys log - #381

Merged
fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:feat/retry-on-error
May 15, 2026
Merged

fcostaoliveira merged 3 commits into
redis:masterfrom
filipecosta90:feat/retry-on-error

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds --retry-on-error (opt-in) plus --max-retries, --retry-backoff-ms, --retry-backoff-factor, --retry-on=LIST, --max-retry-queue, and --failed-keys-file=PATH. Default behavior is unchanged.
  • Resends failed requests on transient server errors, cluster MOVED/ASK redirects, and socket drops. Bytes are captured at send time and replayed unmodified, so every command type (SET/GET/MGET/verify/arbitrary) works without per-type re-serialization.
  • Permanent errors (WRONGTYPE, NOAUTH, NOPERM, NOSCRIPT, NOREPLICAS, syntax / argcount / unknown-command, memcached CLIENT_ERROR) are never retried and, with --failed-keys-file, appended as CSV during the run (line-flushed per record).
  • Per-second CLI gains errors X (+Y) retries Z (+W) retried_ops V when --retry-on-error is on. JSON config block, man page, bash-completion all updated.

Notable design choices

  • Bytes-snapshot, not per-type replay. request gains m_serialized + m_first_sent_time + m_retries. Each shard_connection::send_*_command snapshots the output evbuffer before/after the protocol write and evbuffer_peeks the delta into the request — only when --retry-on-error is set, so the default hot path is unchanged.
  • Ownership handoff via m_claimed_by_retry. client::handle_response can route a request into the per-connection retry queue without process_response double-freeing it. Replay clears the flag when the request returns to the pipeline.
  • Stats reflect total latency. Each logical request is one op; latency = first-send → final-success. m_retry_attempts, m_retried_ops, and m_errors are bumped lock-free per the existing benign-race pattern and aggregated through client_group.
  • Cluster MOVED/ASK uses m_slot_to_shard[crc16(key)] to route the resend onto the slot-owning connection; falls back to same-connection retry when CLUSTER SLOTS hasn't settled. MOVED/ASK count toward --max-retries.
  • Hard-cap retry queue with --max-retry-queue (auto = max(pipeline * 4, 64)); fill_pipeline() pauses new work when full so memory can't grow unboundedly under sustained errors.

Known limitations (follow-ups)

  • Arbitrary-command failed-keys rows have an empty key field. The bytes are captured and replayed correctly; only the per-row key column for logging isn't plumbed. The status text and timestamps still let you correlate.
  • Cluster mode routes redirects via m_slot_to_shard; if the topology hasn't refreshed yet, the resend goes to the same connection and will MOVED again — converges on subsequent retries.
  • Setup commands (AUTH / SELECT / CLUSTER SLOTS / HELLO) are not retried and still abort the thread on failure, matching previous behavior.

Test plan

  • make builds clean, zero warnings.
  • make format-check passes.
  • make rebuild-man — memtier_benchmark.1 includes every new flag.
  • Smoke run (1 thread, 1 conn, 50 SETs) with --retry-on-error against running Redis — completes, stats unchanged.
  • Smoke run with LPUSH against a string-typed key — every request lands in the --failed-keys-file CSV during the run with WRONGTYPE and retries=0.
  • --max-retries=0 with the master switch on disables retry.
  • Per-second CLI line shows errors / retries / retried_ops correctly.
  • tests/test_retry_on_error.py exercises happy path, max-retries=0, WRONGTYPE-always-logged, --retry-on restrictive filter with permanent-set override, and --max-retries=-5 rejection. Needs ./tests/run_tests.sh against the CI env.
  • TSAN run against the same scenarios (not run locally; CI to confirm).
  • Cluster mode MOVED resend with a CLUSTER FAILOVER mid-run (not run locally; CI / manual to confirm).

🤖 Generated with Claude Code


Note

Medium Risk
Adds new request retry/replay paths (including reconnect replay and cluster redirect handling) that change request lifecycle, memory ownership, and stats aggregation when enabled; default behavior remains unchanged when flags are off.

Overview
Adds opt-in per-request retry support via --retry-on-error, including configurable retry budget/backoff (--max-retries, --retry-backoff-ms, --retry-backoff-factor), retry filtering (--retry-on), and a capped per-connection retry queue (--max-retry-queue). Requests now snapshot serialized command bytes at send time and can be replayed on transient server errors, MOVED/ASK redirects, or mid-flight disconnects, with backoff reset after a successful response.

Introduces --failed-keys-file plus a new retry_policy module to classify permanent vs retryable errors and to append terminal failures as CSV. Progress output and JSON config printing now include retry/error counters (errors, retries, retried_ops), and bash-completion/man page are updated; adds tests/test_retry_on_error.py coverage for basic flag behavior and failed-keys logging.

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

Adds --retry-on-error (opt-in) and accompanying knobs to resend a request
when the server returns a transient error, the cluster redirects (MOVED/ASK),
or the connection drops mid-flight. Captures the serialized command bytes
at send time so any command type can be replayed without per-type
re-serialization.

New flags:
  --retry-on-error              master switch (default off)
  --max-retries=N               -1 unlimited (default), 0 disable, N>0 bounded
  --retry-backoff-ms=X          per-retry delay (default 0)
  --retry-backoff-factor=F      exponential multiplier (default 0, constant)
  --retry-on=LIST               restrict retries to listed status prefixes
  --max-retry-queue=N           hard cap on per-conn retry queue (auto if 0)
  --failed-keys-file=PATH       append permanently-failed requests as CSV
                                during the run (line-flushed per record)

Permanent-error set (never retried, always logged): WRONGTYPE, NOAUTH,
NOPERM, NOSCRIPT, NOREPLICAS, ERR wrong number of arguments / syntax error
/ unknown (sub)command, memcached CLIENT_ERROR. Permanent set wins over
--retry-on filter.

Per-second CLI shows 'errors X (+Y) retries Z (+W) retried_ops V' when
--retry-on-error is on; otherwise existing output is unchanged.

Cluster MOVED/ASK uses the captured key to route the resend to the
slot-owning connection (m_slot_to_shard), falling back to same-connection
retry when topology refresh hasn't completed.

Socket drops move pending requests to a per-connection replay queue
instead of deleting them; the reconnect-success handler drains the queue
back into the pipeline before fill_pipeline() so replays precede fresh work.

Tests: tests/test_retry_on_error.py covers the happy path, max-retries=0
disable, WRONGTYPE always-logged-never-retried, --retry-on restrictive
filter with permanent-set override, and argument validation.

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

jit-ci Bot commented May 15, 2026 •

Copy link
Copy Markdown

🛡️ Jit Security Scan Results

CRITICAL HIGH MEDIUM

✅ No security findings were detected in this PR


Security scan by Jit

The macOS-openssl-1.0.2/1.1 CI images ship an Apple Clang that rejects
C++11 lambdas with capture lists (rdar://-Wc++11-extensions becomes an
error in their default mode). Rewrite csv_escape with plain control
flow; behavior and CSV output are byte-identical (verified by re-running
the LPUSH-against-string-key smoke test).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread shard_connection.cpp Resolved
Comment thread client.cpp Resolved
Comment thread cluster_client.cpp Resolved
Comment thread client.cpp Resolved
Four findings from Cursor Bugbot on the initial retry-on-error commit
(7eefe3e). All four are legitimate and addressed below.

1. [HIGH] m_retry_queue orphaned on disconnect

   disconnect() moved m_pipeline into m_replay_queue but ignored
   m_retry_queue (requests waiting for backoff). After reconnect,
   drain_replay_queue_after_reconnect() only handled m_replay_queue, so
   those requests were stranded. Fix: in disconnect(), also drain
   m_retry_queue into m_replay_queue and cancel any pending drain timer.

2. [MEDIUM] inc_retry_attempt() bumped before enqueue success check

   m_stats.inc_retry_attempt() was called before sc->enqueue_retry(req),
   inflating the counter when the retry was refused (max_retries
   exhausted, queue full, no captured bytes). Same bug existed in
   verify_client::handle_response and cluster_client::retry_after_redirect.
   Fix: move the increment inside the success branch in all three
   places.

3. [MEDIUM] MOVED/ASK silent-drop when retry_after_redirect fails

   cluster_client::handle_response returned immediately after calling
   retry_after_redirect, regardless of whether the retry was accepted.
   With bounded --max-retries, a request that hits its retry budget via
   repeated MOVEDs disappeared from all accounting. Fix: new
   finalize_dropped_redirect() helper that logs to --failed-keys-file
   and bumps the error counter on the fall-through path.

4. [LOW] verify_client missing reset_retry_backoff() on success

   verify_client::handle_response gained the retry-enqueue path in the
   initial commit but never reset the per-connection backoff after a
   successful verified response. A transient error burst would inflate
   the backoff indefinitely. Fix: reset on any non-error protocol
   response (both verified-success and value-mismatch are successful
   round-trips from the server's perspective).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Comment thread memtier_benchmark.h
Comment on lines +105 to +106
// retry_on_error master switch (default: off)
// max_retries -1 = unlimited (default), 0 = disabled even with switch on, N>0 = bounded

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

isn't retry_on_error redundant?
from the comments max_retries = 0 seems to disable retry_on_error

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.

Good question — they're technically not redundant under the current dual-gate design:

  • bool retry_on_error is the master switch. It guards the queue allocation in shard_connection (we don't allocate m_retry_queue/m_replay_queue, don't capture serialized bytes per request, and don't render the extra periodic-output columns unless this is true). That keeps the default hot path identical to today — zero overhead when retry is off.
  • int max_retries is the budget once retry is on. -1 = unlimited (default), 0 = disable retries even with the master switch on (useful for measurement: "enable the accounting infrastructure but never resend"), N>0 = bounded.

So --retry-on-error --max-retries=0 is a meaningful combination (capture stats + log to --failed-keys-file without resending), distinct from omitting --retry-on-error entirely (zero overhead, no failed-keys file).

That said, you're right that the user-facing model would be simpler with a single knob:

  • max_retries=0 → off (default), max_retries=-1 → unlimited, max_retries=N → bounded
  • --retry-on-error becomes shorthand for --max-retries=-1

I'd like to keep the current shape in this PR to preserve your approval and avoid invalidating the green CI matrix, and open a follow-up to do the simplification cleanly with its own tests. WDYT?

@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 3 potential issues.

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 4855f8e. Configure here.

Comment thread shard_connection.cpp
// case the retry queue / replay path is responsible for freeing it.
if (!req->m_claimed_by_retry) {
delete req;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Retried requests double-count in reqs_processed causing early termination

High Severity

When a request is retried, inc_reqs_processed() in process_response is called for BOTH the failed attempt (that triggered the retry) and the eventual successful retry response. This inflates m_reqs_processed, which is compared against --requests in finished(). A benchmark with retries will terminate early because the processed-request counter advances on every response including error responses that triggered retries, not just terminal outcomes. The handle_response early return does not prevent inc_reqs_processed() from executing afterward.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4855f8e. Configure here.

Comment thread shard_connection.cpp
if (!m_serialized) return; // best-effort capture; replay just won't work
memcpy(m_serialized, data, len);
m_serialized_len = len;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unused set_serialized method never called anywhere

Low Severity

request::set_serialized is defined and declared but never called anywhere in the codebase. capture_serialized_bytes directly assigns to req->m_serialized instead of using this method. This is dead code that adds maintenance burden with no benefit.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4855f8e. Configure here.

Comment thread shard_connection.cpp
// Exponential backoff for the *next* retry on this connection.
if (m_config->retry_backoff_factor > 0.0) {
m_current_retry_backoff_ms *= m_config->retry_backoff_factor;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Exponential backoff starts at zero when factor specified alone

Medium Severity

When --retry-backoff-ms=0 (default) but --retry-backoff-factor is set, m_current_retry_backoff_ms starts at 0.0 and 0.0 * factor remains 0.0 forever. The exponential backoff never grows, silently ignoring the user's --retry-backoff-factor setting. The factor is only meaningful when a nonzero base delay is also provided, but this isn't validated or documented as an error.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4855f8e. Configure here.

@fcostaoliveira
fcostaoliveira merged commit 08cfc24 into redis:master May 15, 2026
65 checks passed
@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
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.

2 participants