Repository navigation
[CPLAT-13577] redis: close the upstream connection when a reply type does not match the pending request - #29
Conversation
… 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
- 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
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
left a comment
There was a problem hiding this comment.
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-002was created on 11-16 08:54 UTC withelasticache-valkey-9-patch-update-202610(which AWS says includes envoyproxy#4060) alreadycomplete, 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 partialSSL_writeretry can resend or skip reply bytes.
Non-blocking follow-ups
- State "trigger not identified" in the PR description and link the analysis and the AWS case.
- 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 noProtocolError. 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. - Mismatches are folded into
upstream_cx_protocol_error, so we can't alert on desync separately from decoder errors. A dedicated counter would help. - Please run the pinned
./ci/do_ci.sh formatbefore merging. Prod is on the v1.38.3 line, so the backport is what actually takes effect.

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
redis-proxy-zone-b-85489f8767-l4k2s, imageproxyv2: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 asIncorrect Redis value. Unchecked paths got the wrong values silently.ClientImpl::onRespValuepairs every reply withpending_requests_.front(). RESP has no request id, so one lost or surplus reply on a connection shifts every later reply by one.command.exists.error12k on that pod), and MGET fragments received non-bulk replies. Single-key commands passed the wrong values through.Change
PendingRequestrecords the reply type its command always gets in RESP2:Integer(EXISTS, DEL, HSET, TTL, ...),BulkStringOrNull(GET, HGET, ...) orArray(HGETALL, SMEMBERS, ...). Every other command isUnchecked.+OK, null, or bulk withGET) and ZADD (bulk withINCR) are left out.+QUEUEDinside MULTI.ProtocolError, now shared inonProtocolError(): report anExtOriginRequestFailedoutlier result, incrementupstream_cx_protocol_errorandrq_error, and close withNoFlush. The close fails every pending request, including the one whose reply was wrong.onProtocolError()does nothing once the connection is closed, so malformed trailing bytes do not count the same failure twice.getrequests, so they are covered through the command name.envoy.reloadable_features.redis_close_on_reply_type_mismatch(defaulttrue). If a table entry is ever wrong, operators can set it tofalsethrough the runtime layer instead of shipping a new image.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_, butmakeRequestImmediatewrites the AUTH to the wire first. That pre-existing ordering bug used to hand+OKto 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_failureand fail the check as ACTIVE. It now closes the connection, so the check fails as NETWORK. A healthy server never sends that reply.Testing
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 CompositeArraygetfragment answered by an integer closes the connection.ExpectedReplyTypesAreDelivered: matching types, error replies and unchecked commands (EVAL, SET) are delivered unchanged.TransactionClientDoesNotCheckReplyTypes:+QUEUEDfor EXISTS on a transaction client is delivered../ci/do_ci.sh debug //test/extensions/filters/network/common/redis:client_impl_testinenvoyproxy/envoy-build(aarch64, debug) at 4950c24:Executed 1 out of 1 test: 1 test passes,[ PASSED ] 39 tests, including the 7 new cases.client_impl.{h,cc}andBUILDreverted to the base branch:[ FAILED ] RedisClientImplTest.ReplyTypeMismatchClosesConnection. The new tests fail without the fix.clang-format21.1.8 locally. The pinned format toolchain (./ci/do_ci.sh format) has not been run.Rollout
release/v1.39.2-sendbird-custom(Istio 1.31.1), the line the previous redis fix ([CPLAT-12791] redis: do not crash on an upstream frame with no pending request #28) went to.v1.30.2-sendbird-custom-v0.0.2, built fromrelease/v1.38.3-sendbird-custom. A backport PR to that branch will follow once this one is reviewed.Review
Three Codex review rounds. The last one found no blocker or major issue.
flat_hash_map<std::string, ExpectedReply>split theCONSTRUCT_ON_FIRST_USEarguments; a decoder error after the mismatch close counted the failure twice; comment length. No false positive found in the reply type table.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:
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_PERIODICinstead 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:
+OKcommands 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.