Size-limit errors are not distinguishable, and gRPC reports a padded limit or `internal`

Open
#321 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
3/5
Estimated time
1-2 days
Newbie friendliness
55/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
grpc, rust
Domain
api, backend

Research direction

The issue points to specific files: src/service.rs (collect_body_limited), src/client/mod.rs (lines around 2383-2387 for the wrong limit, 4669 for body_parse_error, and 1744-1747 for decode_response_error). Start by reproducing the error with the provided code. Examine how error messages are constructed for size limits in the client and server, and compare with the element-memory limit error pattern. The fix involves updating error messages to name the relevant configuration methods (ClientConfig::with_default_max_message_size, CallOptions::with_max_message_size, Limits::with_max_request_body_size) and correcting the gRPC limit calculation and error code mapping.

Written by the indexing model from the issue text.

Description

Summary

When a unary message crosses the default 4 MiB limit, the error gives the limit's value but does not identify the specific limit, or how to modify that limit. On gRPC and gRPC-Web the client also reports an unconfigured limit (4259845), and a response up to ~64 KiB over the limit fails as internal instead of resource_exhausted.

We hit this in production when some responses grew past 4 MiB. Callers saw resource_exhausted: decompressed size exceeds limit 4194304, and the fix was to change ClientConfig::with_default_max_message_size. The element-memory error added in 0.9 already gives the kind of hint we'd like here:

failed to decode response: element memory limit exceeded; if this server is trusted, raise CallOptions::with_element_memory_limit or ClientConfig::with_default_element_memory_limit

Versions: connectrpc 0.9.0 with buffa 0.9.1, unary RPC over loopback h2c, default ClientConfig and default server limits. An earlier, longer version of this reproduction printed the same messages on connectrpc 0.8.1 with buffa 0.8.1.

Reproduction
Reproduction source code

Cargo.toml dependencies:

[dependencies]
connectrpc = { version = "=0.9.0", features = ["client", "server", "axum"] }
buffa = { version = "=0.9.1", features = ["std", "json"] }
axum = "0.8"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

[build-dependencies]
connectrpc-build = "=0.9.0"

proto/repro.proto:

syntax = "proto3";

package repro.v1;

message GetRequest {
  // How many payload bytes the server should send back.
  uint64 size = 1;
  // Random bytes (true) or one repeated byte (false).
  bool incompressible = 2;
  // A payload for the request itself.
  bytes upload = 3;
}

message GetResponse {
  bytes payload = 1;
}

service BlobService {
  rpc Get(GetRequest) returns (GetResponse);
}

build.rs:

fn main() {
    connectrpc_build::Config::new()
        .files(&["proto/repro.proto"])
        .includes(&["proto/"])
        .include_file("_connectrpc.rs")
        .compile()
        .unwrap();
}

src/main.rs:

//! A default-config connectrpc client reading unary responses just over the
//! default 4 MiB message limit, on Connect, gRPC and gRPC-Web.
use std::sync::Arc;

use connectrpc::client::{ClientConfig, HttpClient};
use connectrpc::{
    CompressionPolicy, ConnectRpcService, Protocol, RequestContext, Response, Router,
    ServiceRequest, ServiceResult,
};

pub mod proto {
    connectrpc::include_generated!();
}
use proto::repro::v1::{BlobService, BlobServiceClient, GetRequest, GetResponse};

const MIB: usize = 1024 * 1024;

fn payload(len: usize, incompressible: bool) -> Vec<u8> {
    if !incompressible {
        return vec![b'A'; len];
    }
    let mut x: u64 = 0x9E37_79B9_7F4A_7C15;
    (0..len)
        .map(|_| {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            x as u8
        })
        .collect()
}

struct Svc;

impl BlobService for Svc {
    async fn get(
        &self,
        _ctx: RequestContext,
        req: ServiceRequest<'_, GetRequest>,
    ) -> ServiceResult<GetResponse> {
        Response::ok(GetResponse {
            payload: payload(req.size as usize, req.incompressible),
            ..Default::default()
        })
    }
}

/// Serves BlobService on a loopback port, with the library's default response
/// compression or with compression off.
async fn serve(compress: bool) -> String {
    let mut svc = ConnectRpcService::new(Router::new().add_service(Arc::new(Svc)));
    if !compress {
        svc = svc.with_compression_policy(CompressionPolicy::disabled());
    }
    let app = axum::Router::new().fallback_service(svc);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    format!("http://{addr}")
}

#[tokio::main]
async fn main() {
    let gzip = serve(true).await;
    let plain = serve(false).await;
    // (label, server, response bytes, incompressible, client limit, request bytes)
    let cases: [(&str, &str, usize, bool, Option<usize>, usize); 5] = [
        ("response 5 MiB, compressible, default server compression", &gzip, 5 * MIB, false, None, 0),
        ("response 5 MiB, incompressible, server compression off", &plain, 5 * MIB, true, None, 0),
        ("response 4,200,000 bytes, incompressible, server compression off", &plain, 4_200_000, true, None, 0),
        ("response 5 MiB, incompressible, client limit raised to 64 MiB", &plain, 5 * MIB, true, Some(64 * MIB), 0),
        ("request 5 MiB, default server limits", &plain, 0, true, None, 5 * MIB),
    ];
    for (label, base, size, incompressible, max, upload) in cases {
        for protocol in [Protocol::Connect, Protocol::Grpc, Protocol::GrpcWeb] {
            let mut config = ClientConfig::new(base.parse().unwrap()).with_protocol(protocol);
            if let Some(max) = max {
                config = config.with_default_max_message_size(max);
            }
            let client = BlobServiceClient::new(HttpClient::plaintext_http2_only(), config);
            let request = GetRequest {
                size: size as u64,
                incompressible,
                upload: payload(upload, true),
                ..Default::default()
            };
            match client.get(request).await {
                Ok(_) => println!("{label} | {protocol:?} | Ok"),
                Err(e) => println!(
                    "{label} | {protocol:?} | {}: {}",
                    e.code.as_str(),
                    e.message.as_deref().unwrap_or("")
                ),
            }
        }
    }
}

Reproduction output

Output (`cargo run --release`):

response 5 MiB, compressible, default server compression | Connect | resource_exhausted: decompressed size exceeds limit 4194304
response 5 MiB, compressible, default server compression | Grpc | resource_exhausted: decompressed size exceeds limit 4194304
response 5 MiB, compressible, default server compression | GrpcWeb | resource_exhausted: decompressed size exceeds limit 4194304
response 5 MiB, incompressible, server compression off | Connect | resource_exhausted: response body size exceeds limit 4194304
response 5 MiB, incompressible, server compression off | Grpc | resource_exhausted: response body size exceeds limit 4259845
response 5 MiB, incompressible, server compression off | GrpcWeb | resource_exhausted: response body size exceeds limit 4259845
response 4,200,000 bytes, incompressible, server compression off | Connect | resource_exhausted: response body size exceeds limit 4194304
response 4,200,000 bytes, incompressible, server compression off | Grpc | internal: envelope decode failed: resource_exhausted: message size 4200005 exceeds limit 4194304
response 4,200,000 bytes, incompressible, server compression off | GrpcWeb | internal: envelope decode failed: resource_exhausted: message size 4200005 exceeds limit 4194304
response 5 MiB, incompressible, client limit raised to 64 MiB | Connect | Ok
response 5 MiB, incompressible, client limit raised to 64 MiB | Grpc | Ok
response 5 MiB, incompressible, client limit raised to 64 MiB | GrpcWeb | Ok
request 5 MiB, default server limits | Connect | resource_exhausted: request body size exceeds limit 4194304
request 5 MiB, default server limits | Grpc | resource_exhausted: request body size exceeds limit 4194304
request 5 MiB, default server limits | GrpcWeb | resource_exhausted: request body size exceeds limit 4194304

Expected vs actual
  1. Over-limit response. Actual: decompressed size exceeds limit 4194304 or response body size exceeds limit 4194304. Expected: a message that says this is the client's response size limit and names ClientConfig::with_default_max_message_size or CallOptions::with_max_message_size, as the element-memory error names its settings.

  2. Over-limit request. Actual: the client receives the server's request body size exceeds limit 4194304, with no indication as to whether this was enforced by the client or the server. Connect maps resource_exhausted to HTTP 429, as the protocol specifies, so the message is the only thing telling the caller this is a size limit. Expected: the message says this is the server's request limit. Separately, connectrpc emits no log or tracing event when the server rejects the request: in the earlier run, a tracing subscriber at connectrpc=debug printed nothing for it, and the unary request path in src/service.rs (collect_body_limited, line 285, and its callers) has no logging. A server-side event naming the settings would tell the operator what to raise: Limits::with_max_request_body_size and Limits::with_max_message_size, set through ConnectRpcService::with_limits or Router::with_route_limits.

  3. gRPC and gRPC-Web report the wrong number. Actual: response body size exceeds limit 4259845. Expected: the configured limit, 4194304. 4259845 is the limit plus the 5-byte envelope header plus RESPONSE_BUFFER_TRAILER_SLACK (64 KiB), in src/client/mod.rs lines 2383-2387.

  4. gRPC and gRPC-Web use internal just over the limit. Actual: a 4,200,005-byte message, which is over the limit but under that buffer cap, fails with internal: envelope decode failed: resource_exhausted: message size 4200005 exceeds limit 4194304, while a 5 MiB one fails with resource_exhausted. Envelope::decode_with_limit returns resource_exhausted, and body_parse_error (src/client/mod.rs line 4669) puts that error's text into a new internal error whenever the HTTP status is 2xx, so the original code is lost. Expected: resource_exhausted for every over-limit response, as on Connect. A comment in decode_response_error (lines 1744-1747) says size overflows are meant to be resource_exhausted:

    ResourceExhausted, not internal, and deliberately: this is the same class as the max_message_size overflow above it, which already uses that code. internal reads as "the client broke" and would route a raise-and-retry caller into an on-call page.

Line numbers are from the published 0.9.0 crate.

Dominant language
Rust
Stars
544
Forks
77
PR merge metrics
No merged PRs in 30d

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from connectrpc/connect-rust

All issues in connectrpc/connect-rust

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.