Skip to content

[CPLAT-13577] redis: close the upstream connection when a reply type does not match the pending request - #29

Open
ku524 wants to merge 6 commits into
release/v1.39.2-sendbird-customfrom
CPLAT-13577-redis-reply-type-guard
Open

ku524 wants to merge 6 commits into
release/v1.39.2-sendbird-customfrom
CPLAT-13577-redis-reply-type-guard

Conversation

@ku524

@ku524 ku524 commented Nov 17, 2026 •

Copy link
Copy Markdown

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577

Summary

A redis_proxy upstream connection whose replies no longer line up with its pending requests now closes, instead of handing each caller the reply of another request. Detection uses the reply type: for commands whose RESP2 reply type is fixed, a non-error reply of another type means the stream is out of step.

Why

  • On 2026-11-17 one us1 redis-proxy pod (redis-proxy-zone-b-85489f8767-l4k2s, image proxyv2:v1.30.2-sendbird-custom-v0.0.2) returned values of other keys for 25 minutes, 01:04:14 to 01:29:37 UTC. soda caught 4,515 of them as Incorrect Redis value. Unchecked paths got the wrong values silently.
  • ClientImpl::onRespValue pairs every reply with pending_requests_.front(). RESP has no request id, so one lost or surplus reply on a connection shifts every later reply by one.
  • Nothing closes such a connection. The op timeout is re-armed on every reply, so it never fires while traffic flows. The fault ended only when Karpenter evicted the pod.
  • Upstream states the limit in redis: test dropping an upstream reply with no pending request envoyproxy/envoy#48205 and leaves it open: "A surplus reply that arrives while another request is pending is still paired with that request; RESP gives no way to detect it."
  • The splitter already noticed the shift in that incident, but only reported it as a command error: EXISTS fragments received non-integers (command.exists.error 12k on that pod), and MGET fragments received non-bulk replies. Single-key commands passed the wrong values through.

Change

  • PendingRequest records the reply type its command always gets in RESP2: Integer (EXISTS, DEL, HSET, TTL, ...), BulkStringOrNull (GET, HGET, ...) or Array (HGETALL, SMEMBERS, ...). Every other command is Unchecked.
  • The table only lists commands whose reply type never varies with arguments or server state. For example, SET (+OK, null, or bulk with GET) and ZADD (bulk with INCR) are left out.
  • Error replies are always accepted, so MOVED/ASK/CLUSTERDOWN handling does not change.
  • Transaction clients are not checked, because the server answers +QUEUED inside MULTI.
  • On a mismatch the client takes the same path as a decoder ProtocolError, now shared in onProtocolError(): report an ExtOriginRequestFailed outlier result, increment upstream_cx_protocol_error and rq_error, and close with NoFlush. The close fails every pending request, including the one whose reply was wrong.
  • The decoder keeps parsing the buffer after the close. Well-formed frames reach the existing empty-queue guard and are dropped. onProtocolError() does nothing once the connection is closed, so malformed trailing bytes do not count the same failure twice.
  • MGET fragments reach the client as CompositeArray get requests, so they are covered through the command name.
  • The check is behind envoy.reloadable_features.redis_close_on_reply_type_mismatch (default true). If a table entry is ever wrong, operators can set it to false through the runtime layer instead of shipping a new image.
  • The warning log (rate limited to once per second) names the host, the command, the expected reply type and the actual reply type. It never logs the reply value, which can hold customer data.
  • The runtime flag is read only when a reply does not match, so the normal path does not pay for it and a flag change also applies to requests already in flight.

What this does not catch

  • A shift between two replies of the same type, for example GET answered with another GET's value, is not detected by itself.

  • In practice the mixed traffic exposes the shift quickly. In the incident, EXISTS mismatches alone ran at 5 to 12 per second on the affected pod, so with this patch the connection would have closed within the first second instead of after 25 minutes.

  • Known side effect: with AWS IAM auth, a request queued while credentials are pending sits ahead of the AUTH in pending_requests_, but makeRequestImmediate writes the AUTH to the wire first. That pre-existing ordering bug used to hand +OK to the queued request. With this patch the connection closes instead. Sendbird does not use IAM auth for redis-proxy, so this PR does not fix the ordering.

  • Redis health checker with EXISTS: a non-integer reply used to count exists_failure and fail the check as ACTIVE. It now closes the connection, so the check fails as NETWORK. A healthy server never sends that reply.

Testing

  • New tests in client_impl_test.cc:
    • ReplyTypeMismatchClosesConnection: EXISTS answered by a bulk string fails both pending requests and counts one protocol error. A later frame from the same buffer is dropped, and a decoder error on trailing bytes is not counted again.
    • ProtocolErrorAfterCallbackClosesClientIsCounted: when a response callback closes the client (the redis health checker does this without connection reuse), a decoder error on the rest of the buffer is still counted once.
    • RuntimeGuardDisablesReplyTypeCheck: the flag is turned off after the request is queued and before the reply arrives; the mismatched reply is delivered as before.
    • CanceledRequestReplyTypeMismatchClosesConnection: a canceled HGETALL answered by an integer closes the connection without calling the canceled caller.
    • FragmentedGetReplyTypeMismatchClosesConnection: a CompositeArray get fragment answered by an integer closes the connection.
    • ExpectedReplyTypesAreDelivered: matching types, error replies and unchecked commands (EVAL, SET) are delivered unchanged.
    • TransactionClientDoesNotCheckReplyTypes: +QUEUED for EXISTS on a transaction client is delivered.
  • ./ci/do_ci.sh debug //test/extensions/filters/network/common/redis:client_impl_test in envoyproxy/envoy-build (aarch64, debug) at 4950c24: Executed 1 out of 1 test: 1 test passes, [ PASSED ] 39 tests, including the 7 new cases.
  • The same target with client_impl.{h,cc} and BUILD reverted to the base branch: [ FAILED ] RedisClientImplTest.ReplyTypeMismatchClosesConnection. The new tests fail without the fix.
  • Formatted with clang-format 21.1.8 locally. The pinned format toolchain (./ci/do_ci.sh format) has not been run.

Rollout

Review

Three Codex review rounds. The last one found no blocker or major issue.

  • Round 1 (fixed in 5830947): the comma in flat_hash_map<std::string, ExpectedReply> split the CONSTRUCT_ON_FIRST_USE arguments; a decoder error after the mismatch close counted the failure twice; comment length. No false positive found in the reply type table.
  • Round 2 (fixed in eb3eb3f): the first dedup checked the connection state, which also skipped the first protocol error when a callback had already closed the client. It now uses a per-client flag.
  • Round 3: one minor suggestion to add a changelogs/current/ entry. Not applied, because this fork does not keep upstream changelog entries for its own patches ([CPLAT-12791] redis: do not crash on an upstream frame with no pending request #28 had none).

A fourth review by a second model (Claude Mythos 5.2) found no blocker and one major issue, fixed in 53ee545:

  • Major: no kill switch, so a wrong table entry could only be fixed with a new image. Added the runtime flag above.
  • Minor, fixed: the log now names the expected and actual reply types; the table comment states the RESP2 assumption.
  • Not applied: a test per table entry (it would restate the table), an integration test with a fake upstream (follow-up), and avoiding the lowercase copy (command names fit in the small-string buffer).

A second Mythos round and a fourth Codex round found no blocker or major issue. Three Mythos minor items were applied in be13075: the command name in the log, ENVOY_LOG_PERIODIC instead of a process-wide pow2 counter, and the flag check moved to the mismatch branch.

A confirmation round on be13075 (Mythos round 3, Codex round 5) found no blocker or major issue. Applied in 4950c24: the in-flight flag test above, and log wording. Not applied: per-host log throttling (the stat still counts every close) and a log-text assertion (the throttle state carries across tests).

Follow-ups, not in this PR:

  • An integration test where a fake upstream sends a mismatched reply and trailing frames in one buffer, through the real decoder.
  • An allowed-types bitmask instead of one expected type, to also check +OK commands such as SETEX and LTRIM.

AI assistance

The investigation, the change and the tests were prepared with AI assistance (Claude Code). I reviewed and understand all of it.

… the pending request

ClientImpl pairs each upstream reply with the oldest pending request. RESP
has no request id, so one lost or surplus reply shifts every later reply
onto the wrong request, and the op timeout never fires while replies keep
arriving. Upstream documents this limit in envoyproxy#48205.

Record the RESP2 reply type that each fixed-type command always gets
(EXISTS integer, GET bulk string or null, HGETALL array, ...). When a
non-error reply has another type, treat it like a decoder protocol error:
count upstream_cx_protocol_error and rq_error, report an outlier failure
and close the connection, which fails every pending request. Transaction
clients are not checked because the server answers +QUEUED inside MULTI.

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577
@ku524 ku524 self-assigned this Nov 17, 2026
@upwind-code-us

upwind-code-us Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Upwind Code Scan

Upwind code scan | ⏭️ Skipped

No scans ran: this PR changes nothing Upwind scans.

Last updated: 4950c24 · 2026-11-17 07:36 UTC

- Pass a type alias to CONSTRUCT_ON_FIRST_USE: the comma in
  flat_hash_map<std::string, ExpectedReply> split the macro arguments.
- Route the mismatch and the decoder ProtocolError through one
  onProtocolError(), which does nothing once the connection is closed.
  The decoder keeps parsing the buffer after a mismatch closes the
  connection, and malformed trailing bytes would count the same failure
  twice.
- Test a canceled request with an Array expectation, and trailing
  malformed bytes after a mismatch.
- Shorten comments to two lines.

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577
Review round 2: the early return on a closed connection also skipped the
first protocol error on an existing path. The redis health checker closes
the client from its response callback when it does not reuse
connections, and a decoder error on the rest of the buffer then went
uncounted. Track whether this client already reported a protocol error
instead, and test that path.

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577
@ku524
ku524 marked this pull request as ready for review November 17, 2026 06:41
Review by a second model (Claude Mythos 5.2):

- Guard the check with envoy.reloadable_features.redis_close_on_reply_type_mismatch
  (default true). If a table entry is ever wrong, every such command would
  close its connection, and the only fix would be a new image. The runtime
  flag lets operators turn the check off through the bootstrap runtime
  layer instead.
- Log the expected and actual reply types, so a close from a real shift can
  be told apart from a wrong table entry. The reply value is not logged.
- Note in the table comment that it assumes RESP2.

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577
…ly time

Review by Claude Mythos 5.2, second round:

- Log the command whose reply type did not match. A wrong table entry
  can then be told apart from a real shift without guessing among the
  integer commands. The name points into the never-modified table.
- Use ENVOY_LOG_PERIODIC instead of ENVOY_LOG_EVERY_POW_2. The pow2
  counter is process-wide, so after many closes a new failure on another
  host could stay silent for a long time.
- Evaluate the runtime flag only when a reply does not match. The normal
  path no longer pays for the lookup, and a flag change also applies to
  requests already in flight.

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577
Confirmation round (Codex, Claude Mythos 5.2), no blocker or major:

- RuntimeGuardDisablesReplyTypeCheck now turns the flag off after the
  request is queued and before the reply arrives, which pins that the
  flag is read at reply time.
- Log "<command> expects reply type <type>" instead of "expects a <type>
  reply", which produced "a integer" and "a array".

JIRA: https://sendbird.atlassian.net/browse/CPLAT-13577

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

Approving as a mitigation: it cuts a shifted connection off at the first wrong-typed reply instead of serving other keys' values for 25 minutes. It does not remove the trigger, and I'd like the PR text to say so explicitly.

Checked

  • Every entry in the reply-type table against RESP2 semantics: none varies with arguments or server state.
  • Closing inside the decoder callback is safe. The empty-queue guard drops trailing frames, canceled requests only bump upstream_rq_cancelled_, and client teardown is deferred. The new commits (flag checked at reply time, command name in the log, periodic log) look good. The runtime lookup only runs on a mismatch.

Where the shift came from
TCP/TLS deliver bytes faithfully, so a shift needs pending_requests_ and the commands Valkey answered to differ in count. I read release/v1.38.3-sendbird-custom (870986ce, what prod runs). Every write goes through makeRequest/makeRequestImmediate together with pending_requests_.emplace_back. AUTH, READONLY, ASKING and CompositeArray fragments all pair 1:1. I found no Envoy path that starts a shift on a well-formed stream, so the trigger is most likely on the Valkey side.

  • valkey-io/valkey#4060 (I/O-thread reply bookmark race that drops a reply's leading bytes) matches the symptom. But 0003-002 was created on 11-16 08:54 UTC with elasticache-valkey-9-patch-update-202610 (which AWS says includes envoyproxy#4060) already complete, so it is unlikely.
  • The same node's CPU spin points at the TLS partial-write path (valkey-io/valkey#4953, connTLSWritev). I asked AWS on case 179487236500129 whether a partial SSL_write retry can resend or skip reply bytes.

Non-blocking follow-ups

  1. State "trigger not identified" in the PR description and link the analysis and the AWS case.
  2. The reply decoder shares the inline-command parser (codec_impl.cc:351-354). After a misframe, a line starting with an alnum byte becomes a fake Array frame with no ProtocolError. A separate PR that makes the reply decoder reject any first byte other than + - : $ * would close the remaining same-type gap this PR can't see.
  3. Mismatches are folded into upstream_cx_protocol_error, so we can't alert on desync separately from decoder errors. A dedicated counter would help.
  4. Please run the pinned ./ci/do_ci.sh format before merging. Prod is on the v1.38.3 line, so the backport is what actually takes effect.

@jinsekim jinsekim added the auto-review/approved Auto-approved by pr-approver label Nov 24, 2026

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

LGTM!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-review/approved Auto-approved by pr-approver

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants