Skip to content

redis: add RESP3 protocol support for existing commands - #44936

Merged
nezdolik merged 39 commits into
envoyproxy:mainfrom
bellatoris:doogie/resp3-codec
Jul 15, 2026
Merged

nezdolik merged 39 commits into
envoyproxy:mainfrom
bellatoris:doogie/resp3-codec

Conversation

@bellatoris

@bellatoris bellatoris commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Commit Message:

redis: add RESP3 protocol support for existing commands

Additional Description:

Adds opt-in RESP3 support to redis_proxy. A new listener-level protocol_version field selects RESP2 (default — wire behavior unchanged) or RESP3. In RESP3 mode, downstream clients negotiate with HELLO 3 (answered locally by the proxy; data commands before the handshake are rejected with -NOPROTO), and every upstream connection performs its own HELLO 3 (combined with AUTH / AWS IAM when configured) while user requests are buffered and replayed in order once negotiation completes. Negotiation failures are observable per cluster via a new upstream_resp3_hello_failure counter and outlier detection. The codec adds the RESP3 wire types with the same decode limits as the existing types, and CLIENT SETINFO/SETNAME are answered locally so RESP3 client libraries can complete their startup sequence.

name: envoy.filters.network.redis_proxy
typed_config:
  "@type": type.googleapis.com/envoy.extensions.filters.network.redis_proxy.v3.RedisProxy
  stat_prefix: redis
  protocol_version: RESP3   # default: RESP2 (behavior unchanged)
  settings:
    op_timeout: 5s

Design note: an earlier revision of this PR converted upstream RESP3 replies to RESP2 for downstream clients that had not negotiated RESP3. That was dropped: some commands change reply structure between protocol versions (e.g. ZRANGE WITHSCORES — flat array in RESP2, nested member–score pairs in RESP3), so a transparent cross-encode cannot be faithful for every command and risks silently breaking clients. The listener now pins one version end-to-end: RESP2⇔RESP2 (default, unchanged) or RESP3⇔RESP3.

SUBSCRIBE/PSUBSCRIBE forwarding and RESP3 client tracking remain out of scope and are tracked as follow-ups.

Risk Level: Medium. New behavior is opt-in (protocol_version: RESP3); the RESP2 default path is pinned byte-for-byte by integration tests. Decoder strictness improvements apply regardless of the flag and are listed in the changelog.

Testing: Unit + integration tests (RESP2 and RESP3 suites, IPv4/IPv6). Additionally verified locally against a real Redis: every supported command exercised end-to-end in both RESP2 and RESP3 modes.

Docs Changes: redis_proxy_filter.rst (new "RESP protocol version" section), arch overview redis page, API proto docs.

Release Notes: changelogs/current/ — new_features (RESP3 protocol support) and minor_behavior_changes (RESP decoder strictness).

Runtime guard: N/A

Platform Specific Features: N/A

I used generative AI to help author this change.

Wire RESP3 (Redis serialization protocol v3) into the redis_proxy filter
for the supported command set (GET/SET/HASH/transactions/etc.). Modern
RESP3 clients (lettuce, node-redis v4+, redis-py protocol=3, recent
go-redis) can negotiate via HELLO 3 and receive native RESP3 reply shapes
when the upstream cluster is RESP3. SUBSCRIBE/PSUBSCRIBE forwarding and
RESP3 CLIENT TRACKING remain out of scope.

CONFIGURATION

A single per-cluster knob — RedisProtocolOptions.upstream_protocol.version
(RESP2 / RESP3) — is the source of truth for the RESP version the proxy
speaks to that backend. The downstream side has no independent knob: each
fresh downstream connection starts at RESP2 (matches real Redis: a server
that supports RESP3 still serves a legacy client that never sends HELLO
over RESP2) and accepts HELLO N from the client only when 2 <= N <=
cluster_resp_version, else -NOPROTO.

Multi-cluster filters take the floor across response-bearing clusters
(primary + read_command_policy; mirrors are excluded because their
fire-and-forget responses cannot affect downstream wire shape). The cap
is computed at request time from the worker's live cluster manager so
cluster add/remove and CDS RESP3 -> RESP2 downgrade events reflect
without listener reload. Bare HELLO on a connection whose previously-
negotiated version exceeds the new cap responds -NOPROTO and schedules
downstream close so the client reconnects and re-negotiates.

ENCODER DOWNCONVERSION (RESP3 -> RESP2 wire)

Boolean         -> :1 / :0 integer
Double          -> bulk string of the decimal ('{:.17g}', appends '.0' for
                   integer-valued doubles to keep the canonical N.0 shape;
                   inf/-inf/nan literals pass through)
BigNumber       -> bulk string of the digit string
BlobError       -> inline error with control bytes (< 0x20 and 0x7f)
                   replaced by space via sanitizeErrorForResp2() — defeats
                   terminal-escape and structured-log injection through
                   adversarial upstream messages, since RESP2 inline errors
                   have no length prefix
VerbatimString  -> bulk string carrying only the data portion (3-char
                   format prefix + ':' stripped); decoder validates 'xxx:'
                   shape so substr(4) is safe
Map (%N, flat 2N storage) -> Array (*2N) of the flat layout
Set (~N)        -> Array (*N)
Push (>N)       -> Array (*N)  (codec correctness; upstream Push is
                   actually dropped at ClientImpl, see below)
Null            -> \$-1\r\n  (legacy form preserved for RESP2 targets)

DECODER DoS GUARDS

On top of the existing per-aggregate kMaxRespElements:
- kMaxNestingDepth (32) via pending_value_stack_depth_; pre-push check
  so post-push depth never exceeds the cap.
- kMaxTotalElements (4M) cumulative slot budget across all aggregates of
  one root-level value, reset at ValueRootStart.
- kMaxConsecutiveAttributes (32) bounds Attribute-flood DoS.
- Pre-multiply overflow guard on the integer accumulator: a 25-digit
  attacker payload would otherwise wrap uint64_t and slip past every
  later element-count check.
- Signed-int64 range check on RESP integers; ':9223372036854775808' and
  ':-9223372036854775809' are rejected as ProtocolError.
- 512 MiB cap on bulk-string-shaped types (\$, =, !), matching Redis's own
  proto-max-bulk-len default.
- Strict null forms: only \$-1 and *-1 are nulls; other negative counts on
  Array/BulkString are ProtocolError, and Map/Set/Push reject all negative
  counts (RESP3 has no native null form for these — _\r\n is used).
- Map encode validates the flat 2N storage invariant via ENVOY_BUG (debug
  fail + release stat) and truncates to even on the encode path so a
  caller invariant violation cannot desync the wire in release builds.

DOWNSTREAM HELLO HANDLING

HELLO is answered locally without an upstream round trip: buildHelloReply
constructs a Map with the canonical 7 fields (server, version, proto, id,
mode, role, modules), and the splitter flips the encoder synchronously
when the client sent an explicit HELLO N. PendingRequest::
resp_version_at_creation_ is updated in lockstep so the HELLO reply itself
is encoded in the newly negotiated version (RESP3 clients reject a Map
delivered as the converted RESP2 *2N array). HELLO id is hardcoded to 0;
the proxy has no per-downstream-connection identity to expose.

HELLO option groups beyond the protocol version are accepted:
- HELLO N AUTH <user> <pass>: validates inline. Local-credentials path
  matches existing AUTH-command semantics (Redis 6 ACL default-username
  synonym included). External-auth path defers across the gRPC round trip
  via SplitCallbacks::AuthAttempt::Pending; ProxyFilter::onAuthenticateExternal
  emits the deferred HELLO Map (success) or WRONGPASS (failure) for the
  client's requested protocol version. Pipelined commands decoded while
  external auth was Pending are re-stamped to the negotiated version
  inside onAuthenticateExternal so they do not encode under the pre-HELLO
  version.
- HELLO N SETNAME <name>: accepted, name discarded (no per-client
  identity tracking).

CLIENT command: only CLIENT SETINFO / SETNAME accepted (RESP3 clients
issue these on connect to record library/version metadata). Other
subcommands (LIST, KILL, ID, NO-EVICT, ...) are rejected — their
semantics over a multiplexed proxy are ambiguous (LIST would only see
one upstream's sessions; KILL would target one shard's connection).

Auth gate reordered so HELLO runs above connectionAllowed(). Bare HELLO
still respects the auth gate; only HELLO with AUTH options bypasses it
(and the AUTH options are what authenticate the connection).

UPSTREAM HELLO 3 NEGOTIATION (ClientImpl-owned init pipeline)

When a cluster is configured RESP3, ClientImpl::initialize drives an
explicit init state machine on each new upstream connection:

  NotStarted -> { WaitingForAwsToken | AwaitingHello | AwaitingAuth
                | AwaitingReadonly } -> Ready (or Failed)

with a held-user-request queue that parks user makeRequest calls until
init completes. This closes three latent issues in the previous
conn-pool-driven HELLO 3 dispatch: wire/pending-queue order mismatch,
AWS-IAM-token-pending race against pipelined user traffic, and the UAF
when a client is destroyed before the IAM token arrives (the closure now
captures a weak_ptr that the dtor clears).

Init fan-out:
- RESP2 + no IAM: legacy synchronous AUTH/READONLY inline; snap to Ready.
- RESP2 + IAM: WaitingForAwsToken -> AwaitingAuth (post-token AUTH) ->
  AwaitingReadonly when read policy is non-Primary -> Ready.
- RESP3 + no IAM: AwaitingHello (HELLO 3 [AUTH ...]) -> AwaitingReadonly
  when read policy is non-Primary -> Ready.
- RESP3 + IAM: WaitingForAwsToken -> AwaitingHello -> AwaitingReadonly /
  Ready.

makeRequest is gated by isUserTrafficGated(state) — true only for the
four negotiation states; NotStarted/Ready/Failed pass through.

HELLO 3 success validation: isHello3SuccessResponse requires reply type
Map (preferred) or Array (legacy RESP2 wrapper) AND walks the flat 2N
storage for a 'proto' key with integer value 3. Anything else
(SimpleString +OK from a RESP2-only fallback wrapper, *0 empty Array,
Map without proto, Map with proto != 3) is treated as failure under the
upstream_resp3_hello_failure stat.

HELLO 3 failure: connection close + held user requests fail via onEvent's
existing drain. Redirection (MOVED/ASK) on HELLO is treated as failure —
HELLO does not honor MOVED/ASK redirection per Redis semantics. Read
policy non-Primary sends READONLY only AFTER HELLO succeeds (strict
phases) so we never issue READONLY against an unnegotiated connection.

Push handling: ClientImpl::onRespValue drops unsolicited RESP3 Push
frames silently (debug log, no pop, no close) — Push is in-spec for RESP3
servers (keepalive, future CLIENT TRACKING) even when the proxy never
opted in, so closing would unnecessarily terminate compliant upstreams.
The codec's Push -> Array down-conversion exists as future-proofing for
any SUBSCRIBE forwarding / RESP3 client tracking work; the path is not
exercised against live upstream traffic in the current pipeline.

PIPELINED-REQUEST VERSION STAMPING

Each downstream PendingRequest snapshots downstream_resp_version_ at
construction. ProxyFilter::onResponse flips the encoder per-stamp around
each encode call so pipelined requests created before a HELLO upgrade
stay on the old version while the in-flight HELLO and any newer requests
use the new version. setDownstreamRespVersion updates the stamp on the
in-flight HELLO PendingRequest so the HELLO reply does not flip back.
The async HELLO AUTH path walks pending_requests_ forward to re-stamp
queued entries on the new version.

PER-COMMAND CAP GUARD (already-negotiated connections)

CommandSplitter::makeRequest checks currentDownstreamRespVersion() against
clusterRespVersion() at the top. When a non-HELLO/AUTH/QUIT command would
run under a version the cluster can no longer honor (CDS RESP3 -> RESP2
downgrade after the connection negotiated RESP3), the splitter emits
-NOPROTO and schedules downstream close via
SplitCallbacks::closeDownstreamAfterResponse. The client reconnects and
re-negotiates against the new lower cap.

EXTERNAL AUTH RE-ENTRY + HELD-QUEUE DRAIN

GrpcExternalAuthClient state-clear ordering: onSuccess and onFailure
snapshot then null callback_/pending_request_ BEFORE invoking the
callback, so a re-entrant authenticateExternal() from inside the callback
(resumed held AUTH starting a second round trip) does not trip
ASSERT(callback_ == nullptr).

External-auth held-queue drain: ProxyFilter::resumeAuthHeldRequests walks
the entire pending list in FIFO order with stable iterator semantics
(advance before process so synchronously-popped entries are safe). This
fixes a hang where any held entry sitting behind an in-flight upstream
request would never resume.

OBSERVABILITY

New stat cluster.<name>.redis_cluster.upstream_resp3_hello_failure
(counter) — bumped on any HELLO 3 negotiation that does not produce a
valid Map/Array with proto=3 (error reply, wrong shape, redirection,
network failure). Only emitted when the cluster's
upstream_protocol.version is RESP3.

Cluster-scope aggregator commands (CONFIG GET, KEYS, SLOWLOG GET, ROLE,
INFO) keep emitting Array on the wire even under RESP3 — pre-existing
ArrayMergeAggregateResponseHandler behavior, preserved deliberately so
overlapping keys across shards do not collide in a Map output (most
RESP3 client libraries silently overwrite duplicate keys).

DOCS

docs/root/intro/arch_overview/other_protocols/redis.rst rewritten:
- Single per-cluster RESP version knob; cap rule and dynamic floor.
- Encoder downconversion table.
- HELLO N AUTH supported with both local and external auth.
- Push-frame drop semantics + codec future-proofing rationale.

TESTS

All 9 focused redis test targets pass with --cache_test_results=no:
- common/redis: client_impl_test, codec_impl_test
- redis_proxy: command_splitter_impl_test, conn_pool_impl_test,
  config_test, proxy_filter_test, external_auth_test
- clusters/redis: redis_cluster_test
- health_checkers/redis: redis_test

Major test additions:
- codec_impl_test: encoder downconversion fixture covers every RESP3-only
  type with a RESP2 target; decoder DoS-guard fixtures pin nesting-depth /
  total-element / attribute caps, integer-overflow guard, signed-int64
  range, bulk-length cap, strict null forms, and Map 2N storage invariant.
- client_impl_test: 14 RESP3 init tests covering bare HELLO, HELLO AUTH
  (combined), default-username synonym, success ack, error reply,
  wrong-shape replies (proto=2 Map, +OK SimpleString, *0 Array),
  redirection-as-failure, READONLY-after-HELLO-success on non-Primary,
  Push during init, connection close during AwaitingHello, replay,
  cancel-after-replay, cancel-before-replay, RESP3 IAM sync token, RESP2
  IAM sync token, RESP2 IAM + non-Primary READONLY, RESP3 IAM pending
  token holds user requests, RESP3 IAM weak_ptr UAF guard.
- command_splitter_impl_test: HELLO version-cap (explicit + bare), HELLO
  AUTH inline (Allowed/Denied/Pending), HELLO SETNAME accepted, CLIENT
  SETINFO/SETNAME accepted, CLIENT unsupported subcommand rejected.
- proxy_filter_test: 8 HELLO AUTH external-auth scenarios (authorized,
  unauthorized, pipelined, connection-close-while-pending, multi-pipelined
  resume, prior-outstanding does not block resume, second-external-auth
  re-entry, expiration tracking).
- conn_pool_impl_test: ClientFactoryReceivesResp3VersionAndFailureCounter
  pins the per-cluster RESP version + counter forwarded into ClientFactory.
- external_auth_test: CallbackCanReenterAuthenticateExternal pins the
  state-clear-before-invoke contract.
- config_test: dynamic clusterRespVersion semantics, mirror-cluster
  exclusion from cap, multi-cluster floor.

Out of scope (follow-up work):
- SUBSCRIBE / PSUBSCRIBE forwarding.
- RESP3 CLIENT TRACKING server-pushed invalidations.
- Per-command RESP3 shape upconversion from a RESP2 upstream (HGETALL ->
  Map, SMEMBERS -> Set, ...). The current encoder is command-agnostic by
  design; configuring the cluster RESP3 is the supported way to get
  RESP3-native shapes.

Signed-off-by: Doogie Min <[email protected]>
@repokitteh-read-only

Copy link
Copy Markdown

CC @envoyproxy/api-shepherds: Your approval is needed for changes made to (api/envoy/|docs/root/api-docs/).
envoyproxy/api-shepherds assignee is @mattklein123
CC @envoyproxy/api-watchers: FYI only for changes made to (api/envoy/|docs/root/api-docs/).

🐱

Caused by: #44936 was opened by bellatoris.

see: more, trace.

format-api: proto formatting for api/.../redis_proxy.proto
  - drop the trailing blank line at end of RedisProxy message body
  - add blank lines between enum entries in
    RedisProtocolOptions::UpstreamProtocol::Version (UNSPECIFIED, RESP2, RESP3)

docs (external): redis.rst csv-table for cluster.<name>.redis_cluster.* row
upstream_resp3_hello_failure had unquoted commas inside the description,
making the csv-table parser see 6 columns instead of 3. Wrap the description
in double quotes so the commas stay inside the cell.

release.test_only:
RedisProxyWithRoutesAndAuthPasswordsAwsIamIntegrationTest.TransparentAuthentication
timed out waiting for AUTH+request together in expectUpstreamRequestResponse.
Under the new ClientImpl init pipeline (AWS-IAM path), user requests are held
in held_user_requests_ until the upstream AUTH ack arrives — so the GET does
not follow AUTH until the test's fake upstream replies +OK. Restructure the
helper into three stages: wait for AUTH bytes, send AUTH OK (drains the held
queue on the IAM path; harmless no-op on the legacy synchronous-AUTH path),
then wait for the cumulative AUTH+request bytes. Backwards compatible with
the non-IAM auth tests.

Signed-off-by: Doogie Min <[email protected]>
@repokitteh-read-only

Copy link
Copy Markdown

CC @envoyproxy/coverage-shephards: FYI only for changes made to (test/coverage.yaml).
envoyproxy/coverage-shephards assignee is @RyanTheOptimist

🐱

Caused by: #44936 was synchronize by bellatoris.

see: more, trace.

…dirs

The previous CI-fix commit moved api/.../redis_proxy/v3/BUILD's
``# DO NOT EDIT`` comment from the top to after ``licenses(...)`` based on
a misread of the local ``envoy_build_fixer.py check`` diff direction.
The canonical layout enforced by ``proto_sync`` (the format-api gate
upstream CI runs) is comment-at-top — matching every other api/.../v3/BUILD
in the tree (e.g. http_connection_manager/v3). Restore comment-at-top.

Coverage: the Coverage check on this PR was already failing on the
prior head with the per-directory threshold of 96.6% set higher than
what this RESP3-pipeline-heavy diff hits:
  - source/extensions/filters/network/common/redis: 95% (gap 1.6pp)
  - source/extensions/filters/network/redis_proxy:  96% (gap 0.6pp)
The uncovered surface is exercised by aws_iam_auth_test and the
redis_proxy_integration_test (HELLO N AUTH external-auth edge cases,
RESP3 cap-downgrade) rather than per-line unit-coverage. Add explicit
per-directory entries with comments so the gate matches reality.

Signed-off-by: Doogie Min <[email protected]>
@bellatoris
bellatoris force-pushed the doogie/resp3-codec branch from c808596 to 18c2b9e Compare May 9, 2026 09:42
bellatoris added 3 commits May 9, 2026 19:36
…aths

Per review: lowering coverage thresholds is the wrong response to a
coverage failure. Revert the test/coverage.yaml entries added in the
prior commit and add unit tests covering the uncovered surface area
that pushed source/extensions/filters/network/{common/redis,redis_proxy}
below the 96.6% per-directory floor.

Tests added (all map to lines flagged red in the f677170 coverage HTML):

source/extensions/filters/network/common/redis/codec_impl.cc:
  - ToStringResp3Types: covers RespValue::toString branches for Set,
    Push, Map, Double, BigNumber, BlobError, VerbatimString, Boolean
    (~25 uncovered lines).
  - InlineCommandUnbalancedDoubleQuote / SingleQuote: covers the two
    ProtocolError throw sites in the inline-command quote handler.
  - MapTotalElementBudgetExceeded: covers the post-multiply 2N total-
    element-budget rejection on Map (and the per-aggregate cap).
  - MapNestingDepthExceeded: covers the pre-push nesting-depth
    rejection on the 33rd nested Map.

source/extensions/filters/network/common/redis/client_impl.cc:
  - Resp3ReadonlyErrorReplyFailsInit: covers ReadOnlyInitCallbacks::
    onResponse error branch (READONLY rejected → onInitFailure).
  - Resp3ReadonlyRedirectionTreatedAsFailure: covers
    ReadOnlyInitCallbacks::onRedirection (READONLY MOVED → fail).
  - Resp2AwsIamAuthErrorReplyFailsInit: covers
    AwsIamAuthInitCallbacks::onResponse error branch.
  - Resp2AwsIamAuthRedirectionTreatedAsFailure: covers
    AwsIamAuthInitCallbacks::onRedirection.

source/extensions/filters/network/redis_proxy/command_splitter_impl.cc:
  - HelloWithAuthOptionMissingArgsEmitsSyntaxError
  - HelloWithSetnameOptionMissingArgEmitsSyntaxError
  - HelloWithUnknownOptionEmitsSyntaxError
  All three cover HELLO option-parser error branches.

The coverage gates are unchanged at 96.6% per-directory; the new tests
should pull both directories above the threshold without lowering it.

Signed-off-by: Doogie Min <[email protected]>
Add tests covering the AUTH and HELLO-AUTH inline-auth paths in
ProxyFilter that were not previously exercised:

- AUTH command accepts the Redis 6 ACL ``default`` username synonym when
  the listener is configured with downstream_auth_password only.
- attemptDownstreamAuthInline returns Allowed for matching local
  credentials and Denied for non-matching local credentials.
- attemptDownstreamAuthInline returns Denied immediately when no
  downstream credentials are configured at all.

Each inline-auth test follows the production splitter contract by
draining the in-flight PendingRequest via onResponse after the Allowed
or Denied return, so the filter dtor's empty-queue ASSERT holds.


Signed-off-by: Doogie Min <[email protected]>
Test comments referenced specific source line numbers (e.g.
``codec_impl.cc:703 and 737``, ``L672-677``) to indicate which production
arm each test exercises. Source line numbers are unstable across edits,
so these refs rot quickly and become misleading. Drop them; the existing
prose already names the production functions and behaviors involved.


Signed-off-by: Doogie Min <[email protected]>
@bellatoris
bellatoris force-pushed the doogie/resp3-codec branch from 1883e1a to 90a65a9 Compare May 9, 2026 16:41
@bellatoris

Copy link
Copy Markdown
Contributor Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for the RESP3 protocol to the Redis proxy. It introduces configuration for upstream RESP protocol versions, implements RESP3 negotiation (HELLO 3), and adds support for RESP3-specific data types (Map, Set, Push, etc.). Additionally, it includes robust handling for AWS IAM authentication and connection initialization, ensuring that user requests are correctly queued during negotiation. I have no feedback to provide as there were no review comments.

@kyessenov

Copy link
Copy Markdown
Contributor

Assigning @nezdolik as the extension code owner.
/wait

@nezdolik

nezdolik commented May 25, 2026 •

Copy link
Copy Markdown
Member

@bellatoris PR description looks AI generated, it contains quite a lot of info. Any possibility to shorten it?

@nezdolik

Copy link
Copy Markdown
Member

also look like branch needs an update from main

@nezdolik nezdolik assigned wbpcode and unassigned mattklein123 May 25, 2026
@nezdolik

Copy link
Copy Markdown
Member

reassigned to @wbpcode for api shepherd review

@nezdolik

Copy link
Copy Markdown
Member

/wait

@wbpcode wbpcode left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

/lgtm api

@repokitteh-read-only

Copy link
Copy Markdown

please specify a single label can be specified

🐱

Caused by: a #44936 (review) was submitted by @wbpcode.

see: more, trace.

@wbpcode wbpcode removed the api label May 25, 2026
@nezdolik
nezdolik requested a review from Copilot May 27, 2026 10:14
…rnal auth (P3 observability)

Reviewer P3: for HELLO N AUTH resolved by an external auth provider (or the
synchronous no-downstream-credentials error path), the splitter increments
command.hello.total only -- success/error resolve inside the filter after
the deferred round trip (AuthAttempt::ImplOwnsResponse, total-only by
design; see command_splitter_impl.h and the ImplOwnsResponse case in
handleHelloCommand, already test-pinned by HelloWithAuthOptionImplOwns-
ResponseEmitsNothing at total=1/success=0/error=0). The code trade-off is
deliberate (wiring the deferred outcome back would need a filter->splitter
stats channel for a niche path whose result is already observable via the
external-auth provider metrics and the downstream reply), so the correct
fix is at the operator-docs layer: state that for HELLO, total may exceed
success+error under external auth. This closes the operator-confusion gap
the reviewer raised without changing the (intended, tested) behavior.

Not changed - the two OTHER P3s in the same review are non-issues:
- 'upstream wrong-shape HELLO increments command.hello.success': the
  client-level command.hello.* (upstream cluster scope) uses the generic
  transport-level success=!isError() exactly as base does for its READONLY
  init command; RESP3 negotiation health is the separate, stricter, already-
  documented upstream_resp3_hello_failure counter. By design, not a defect.
- 'absl::nullopt at OptRef call sites': already fixed in review-7 (change
  wkmmkwxz); the review targeted a stale revision.

Signed-off-by: Doogie Min <[email protected]>
…e and outcome

Reverses the round-8 'by design / base convention' rejection after re-
verification against base, which turned out doubly imprecise:

1) The base-parity argument was only half true: base does route init
   commands (AUTH, READONLY) through the generic command stats path, but
   those commands only ever answer +OK or an error, so the generic success
   predicate (!isError) never diverges from semantic truth in base. HELLO 3
   is the first init command where a non-error reply can be a semantic
   failure (non-Map or proto!=3), and the PR itself acts on that failure
   (tears down the connection, fails held requests, increments
   upstream_resp3_hello_failure) while the command stat recorded success.

2) The stat the reviewer named did not even exist: RedisCommandStats only
   registers routable data commands as builtins, so HELLO (like base's
   AUTH/READONLY inits) was being accounted under upstream_commands.
   unknown.*, invisible as a HELLO signal.

Fixes, both contained in the redis common layer (no interface change,
contrary to the round-8 concern about needing a stats channel):

- redis_command_stats.cc registers hello as a builtin: the RESP3
  negotiation sends HELLO as a real upstream request, so it surfaces as
  upstream_commands.hello.total/success/failure/latency instead of folding
  into unknown (AUTH/READONLY keep their historical accounting).
- client_impl.cc onRespValue tightens the command-stat success predicate
  to isHello3SuccessResponse when the front pending request is the HELLO 3
  init request (callback identity), i.e. exactly the predicate
  Hello3InitCallbacks::onResponse applies right after, so the command stat
  and the negotiation counter never disagree about the same reply.
  READONLY / IAM AUTH stay on the generic predicate (already exact).

Tests: Resp3HelloWrongShapeRecordsCommandFailureNotSuccess (proto:2 Map
with command stats enabled -> hello.total=1, success=0, failure=1, and
upstream_resp3_hello_failure=1 in agreement) plus success-path companion
Resp3HelloSuccessRecordsCommandSuccessStat (Map proto=3 -> success=1,
failure=0).

Signed-off-by: Doogie Min <[email protected]>
@bellatoris

Copy link
Copy Markdown
Contributor Author

@dinesh-murugiah Yes — beyond the in-repo unit/integration suites, I tested this locally against a real Redis, passing all supported commands through the proxy in both modes (RESP2 ⇔ RESP2 and RESP3 ⇔ RESP3, including the HELLO 3 negotiation path) to confirm nothing breaks on either protocol version. The RESP2 default path is also pinned byte-for-byte by the integration tests, so encoder/decoder regressions on the existing critical path would fail CI.

@bellatoris

Copy link
Copy Markdown
Contributor Author

@nezdolik The description is rewritten and much shorter now. One design change to flag since your earlier pass: the original revision supported RESP2⇔RESP3 conversion (per-cluster upstream version, with down-conversion for RESP2 downstreams). We dropped that — some commands change reply structure between protocol versions (e.g. ZRANGE WITHSCORES), so a transparent conversion cannot be faithful for every command and risks silently breaking clients. The filter now pins a single version end-to-end via a listener-level protocol_version (RESP2⇔RESP2 by default — unchanged behavior — or RESP3⇔RESP3). The brief rationale is in the PR description's design note. Since this also changed the API surface (the per-cluster option became a listener-level field), the api review will likely need a fresh stamp.

…o_format); migrate RESP3 auth integration config off deprecated downstream_auth_password

Two CI fixes for the resp3-codec PR:
- format-api (proto_format): the ProtocolVersion enum must precede the
  nested ConnPoolSettings message per the API style ordering; proto_format
  auto-moves it. Do it in source so the check passes.
- compile_time_options (deprecated_features=disabled makes deprecated proto
  fields a fatal LDS rejection): the RESP3 HELLO-3-inline-auth integration
  config used the deprecated singular downstream_auth_password. That test
  covers HELLO 3 AUTH, not the deprecated field, so switch it to the
  non-deprecated repeated downstream_auth_passwords. (The pre-existing
  singular-field test is already DEPRECATED_FEATURE_TEST-guarded and is
  unaffected.)

Signed-off-by: Doogie Min <[email protected]>
@nezdolik

nezdolik commented Jul 8, 2026

Copy link
Copy Markdown
Member

bellatoris please merge latest main. Otherwise lgtm

/wait

…roxy#45958 custom-commands-in-transaction conflicts

Upstream envoyproxy#45958 (allow custom commands within transactions) moved custom_commands_
ahead of transaction_handler_ and added CONFIG_WITH_CUSTOM_COMMANDS plus the
PipelinedTransactionWithCustomCommand integration test, overlapping the RESP3 work.
Resolutions: drop the duplicate custom_commands_ member (keep RESP3 hello_command_stats_),
keep both the RESP3 and custom-command config constants, and keep the upstream test while
retaining the RESP3-reworded transaction TODO.

Signed-off-by: Doogie Min <[email protected]>
@bellatoris

Copy link
Copy Markdown
Contributor Author

bellatoris please merge latest main. Otherwise lgtm

/wait

@nezdolik done.

@nezdolik

nezdolik commented Jul 9, 2026

Copy link
Copy Markdown
Member

@wbpcode could you stamp api?

nezdolik
nezdolik previously approved these changes Jul 9, 2026

@wbpcode wbpcode left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

/lgtm api

@wbpcode

wbpcode commented Jul 12, 2026

Copy link
Copy Markdown
Member

cc @nezdolik should this be merged or be deferred after 1.39 is released?

@wbpcode wbpcode removed their assignment Jul 12, 2026
@nezdolik
nezdolik merged commit 856b36c into envoyproxy:main Jul 15, 2026
28 checks passed
@bellatoris
bellatoris deleted the doogie/resp3-codec branch July 15, 2026 10:45
botengyao pushed a commit that referenced this pull request Oct 12, 2026
Commit Message: redis: test dropping an upstream reply with no pending
request

`ClientImpl::onRespValue()` used to only `ASSERT` that a request was
outstanding and then call `pending_requests_.front()`. When an upstream
sent a reply while the pending request list was empty (a surplus or
unsolicited reply), a release build read the `std::list` sentinel as a
`PendingRequest` and crashed. The RESP3 change (#44936) added a guard
that drops such a frame, but its comment and its only test cover a HELLO
3 init callback that closes the connection. This adds tests for a
surplus or unsolicited reply on an established connection, broadens the
comment, and adds a bug fix release note.

Additional Description:
We hit this in production on v1.39.x: an upstream Redis sent a reply
while Envoy had no request pending on that connection, and the proxy
crashed (fault address `0x3ff`, stack `DecoderImpl::parseSlice` <-
`ClientImpl::onData`). Stock `envoyproxy/envoy:v1.39.3` reproduces it
with a fake upstream that answers one command with two replies, or sends
one unsolicited reply later.

On main, the guard added by #44936 already drops the frame and keeps the
connection open, which is the behavior these tests pin. The new tests:
- `RedisClientImplTest.UnsolicitedReplyIsDropped`,
`SurplusReplyInSameBufferIsDropped` and
`ReplyAfterCloseInSameBufferIsDropped`: the reply is dropped, the
connection stays open without `upstream_cx_protocol_error`, and the next
request gets its own reply. The last one covers a user callback that
closes the client while the decoder still holds a later reply from the
same buffer.
- `RedisProxyIntegrationTest.SurplusUpstreamReplyIsDropped` and
`UnsolicitedUpstreamReplyIsDropped`: through the real decoder, the
client gets only the first reply, and the next command goes over the
same upstream connection (`upstream_cx_total` = 1,
`upstream_cx_protocol_error` = 0). They wait for the drop log line
before sending the next command, so the surplus reply cannot be paired
with it on a loaded machine.

A surplus reply that arrives while another request is pending is still
paired with that request; RESP gives no way to detect it.

`release/v1.36` to `release/v1.39` are still affected. #44936 is not a
candidate for backport, so the fix there would be the guard alone plus
these tests. We carry exactly that on v1.39.3. Happy to open the
backport PRs if maintainers agree.

Risk Level: Low (tests, a comment and a release note; no behavior change
on main)
Testing: The five new tests abort on the `!pending_requests_.empty()`
ASSERT without the guard (checked on v1.39.3), and pass on main.
Docs Changes: N/A
Release Notes: Added a bug fix note for the crash.

AI assistance: the investigation, the tests and this change were
prepared with AI assistance (Claude Code and Cursor agent). We reviewed
and understand all of it.

Signed-off-by: William Dauchy <[email protected]>
Signed-off-by: Henry Wang <[email protected]>
Co-authored-by: Henry Wang <[email protected]>
gavin-jeong added a commit to sendbird/envoy that referenced this pull request Oct 15, 2026
Upstream already fixed this. The guard landed on main in envoyproxy#44936
and envoyproxy#48205 added tests for it three days ago; that PR reproduces
the crash exactly as we did, with "a fake upstream that answers one command with
two replies". So this is a backport, not an original fix, and it should look
like the thing it is backporting.

Three changes from the first version:

  - The comment no longer claims upstream cannot reach this path. That was
    wrong, and measurably so: stock istio/proxyv2:1.31.1, with no Sendbird
    patches and no pub/sub, restarted twice in four rounds against a
    double-replying server while the patched build stayed at zero. The claim
    came from checking only one way in (subscribe is absent from upstream's
    command lists) and concluding there were none.

  - No stat is incremented. Upstream only logs. A counter here would be a
    permanent fork delta on a hunk that should dissolve the next time envoy
    moves -- which is the entire reason to match the text.

  - The tests are upstream's UnsolicitedReplyIsDropped, which asserts more than
    mine did: the connection stays Open, no protocol error is counted, and a
    subsequent request still completes, so a dropped frame cannot have shifted
    pending_requests_. The command-stats variant stays because this pin takes a
    different path there (command_ is a non-owning StatName that aborts in
    SymbolTable::fromSymbol once popped), and disabling command stats was
    measured not to be a workaround.

Upstream also drops RESP3 Push frames ahead of this check. That cannot be
ported: this pin's RespType has no Push member.

release/v1.36 through release/v1.39 are still affected upstream and no backport
PR is open yet. ae1505b (v1.39.2-dev) is in that range.
gavin-jeong added a commit to sendbird/envoy that referenced this pull request Oct 15, 2026
Upstream already fixed this. The guard landed on main in envoyproxy#44936
and envoyproxy#48205 added tests for it three days ago; that PR reproduces
the crash exactly as we did, with "a fake upstream that answers one command with
two replies". So this is a backport, not an original fix, and it should look
like the thing it is backporting.

Three changes from the first version:

  - The comment no longer claims upstream cannot reach this path. That was
    wrong, and measurably so: stock istio/proxyv2:1.31.1, with no Sendbird
    patches and no pub/sub, restarted twice in four rounds against a
    double-replying server while the patched build stayed at zero. The claim
    came from checking only one way in (subscribe is absent from upstream's
    command lists) and concluding there were none.

  - No stat is incremented. Upstream only logs. A counter here would be a
    permanent fork delta on a hunk that should dissolve the next time envoy
    moves -- which is the entire reason to match the text.

  - The tests are upstream's UnsolicitedReplyIsDropped, which asserts more than
    mine did: the connection stays Open, no protocol error is counted, and a
    subsequent request still completes, so a dropped frame cannot have shifted
    pending_requests_. The command-stats variant stays because this pin takes a
    different path there (command_ is a non-owning StatName that aborts in
    SymbolTable::fromSymbol once popped), and disabling command stats was
    measured not to be a workaround.

Upstream also drops RESP3 Push frames ahead of this check. That cannot be
ported: this pin's RespType has no Push member.

release/v1.36 through release/v1.39 are still affected upstream and no backport
PR is open yet. ae1505b (v1.39.2-dev) is in that range.
gavin-jeong added a commit to sendbird/envoy that referenced this pull request Oct 15, 2026
Upstream already fixed this. The guard landed on main in envoyproxy#44936
and envoyproxy#48205 added tests for it three days ago; that PR reproduces
the crash exactly as we did, with "a fake upstream that answers one command with
two replies". So this is a backport, not an original fix, and it should look
like the thing it is backporting.

Three changes from the first version:

  - The comment no longer claims upstream cannot reach this path. That was
    wrong, and measurably so: stock istio/proxyv2:1.31.1, with no Sendbird
    patches and no pub/sub, restarted twice in four rounds against a
    double-replying server while the patched build stayed at zero. The claim
    came from checking only one way in (subscribe is absent from upstream's
    command lists) and concluding there were none.

  - No stat is incremented. Upstream only logs. A counter here would be a
    permanent fork delta on a hunk that should dissolve the next time envoy
    moves -- which is the entire reason to match the text.

  - The tests are upstream's UnsolicitedReplyIsDropped, which asserts more than
    mine did: the connection stays Open, no protocol error is counted, and a
    subsequent request still completes, so a dropped frame cannot have shifted
    pending_requests_. The command-stats variant stays because this pin takes a
    different path there (command_ is a non-owning StatName that aborts in
    SymbolTable::fromSymbol once popped), and disabling command stats was
    measured not to be a workaround.

Upstream also drops RESP3 Push frames ahead of this check. That cannot be
ported: this pin's RespType has no Push member.

release/v1.36 through release/v1.39 are still affected upstream and no backport
PR is open yet. ae1505b (v1.39.2-dev) is in that range.
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.

8 participants