From d6acb591a5292eb327821477039da851085781ff Mon Sep 17 00:00:00 2001 From: Andrey Osipov Date: Tue, 1 Dec 2026 23:10:24 +0700 Subject: [PATCH 1/2] Querier: don't compress query API error responses The query API compressed every response according to the client's Accept-Encoding header, errors included. The HTTP logging middleware logs the body written for 5xx responses, so for clients sending Accept-Encoding, like the Go HTTP client which sends gzip by default, the log showed a compressed blob instead of the error. Choose the encoding up front but only start compressing when the response header is written with a status code below 400. Fixes #3912 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDgKpXdZmLs9YSYU1ZSf8d Signed-off-by: Andrey Osipov --- CHANGELOG.md | 1 + pkg/api/queryapi/compression.go | 63 ++++++++++++++++++++-------- pkg/api/queryapi/compression_test.go | 35 ++++++++++++++++ pkg/api/queryapi/query_api_test.go | 29 +++++++++++++ 4 files changed, 110 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f32e39e4efe..8108f0c7dbb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,7 @@ * [BUGFIX] Ring: Fix `DoBatch` counting a key more than once when more replicas than the quorum succeed, which in rare cases could hide a write error from a key that did not reach quorum. A distributor push now always waits until every series reaches quorum, so it returns the error of a series that misses quorum, and takes as long as its slowest series to reach quorum. #7975 * [BUGFIX] Compactor: Stop downloading the parquet files and the `parquet-converter-mark.json` and `parquet-no-convert-mark.json` markers written by the parquet converter under a block's prefix. Compaction never reads them, so they only used local disk and bandwidth until the compaction job ended. #7972 * [BUGFIX] Ring: Fix shuffle-sharding subrings treating instances with a stale heartbeat as healthy when using the DynamoDB KV store. #7976 +* [BUGFIX] Querier: Stop compressing query API error responses. Clients sending `Accept-Encoding`, such as the Go HTTP client which sends `gzip` by default, got compressed error responses, so the logged body of a failed query was an unreadable compressed blob. #XXXX ## 1.22.0 2026-11-19 diff --git a/pkg/api/queryapi/compression.go b/pkg/api/queryapi/compression.go index b7c4f0ce008..f578b176a62 100644 --- a/pkg/api/queryapi/compression.go +++ b/pkg/api/queryapi/compression.go @@ -21,17 +21,56 @@ const ( ) // Wrapper around http.Handler which adds suitable response compression based -// on the client's Accept-Encoding headers. +// on the client's Accept-Encoding headers. Error responses (status code 400 or +// above) are not compressed, so they stay readable wherever the response body +// is logged. type compressedResponseWriter struct { http.ResponseWriter - writer io.Writer + writer io.Writer + encoding string + wroteHeader bool +} + +// Sends an HTTP response header with the provided status code, and enables +// the compression unless the response is an error. +func (c *compressedResponseWriter) WriteHeader(statusCode int) { + if !c.wroteHeader { + c.wroteHeader = true + if statusCode < http.StatusBadRequest { + c.startCompression() + } + } + c.ResponseWriter.WriteHeader(statusCode) } // Writes HTTP response content data. func (c *compressedResponseWriter) Write(p []byte) (int, error) { + if !c.wroteHeader { + c.WriteHeader(http.StatusOK) + } return c.writer.Write(p) } +func (c *compressedResponseWriter) startCompression() { + switch c.encoding { + case zstdEncoding: + encoder, err := zstd.NewWriter(c.ResponseWriter) + if err != nil { + return + } + c.writer = encoder + case snappyEncoding: + c.writer = snappy.NewBufferedWriter(c.ResponseWriter) + case gzipEncoding: + c.writer = gzip.NewWriter(c.ResponseWriter) + case deflateEncoding: + c.writer = zlib.NewWriter(c.ResponseWriter) + default: + return + } + c.Header().Set(contentEncodingHeader, c.encoding) +} + // Closes the compressedResponseWriter and ensures to flush all data before. func (c *compressedResponseWriter) Close() { if zstdWriter, ok := c.writer.(*zstd.Encoder); ok { @@ -52,25 +91,13 @@ func (c *compressedResponseWriter) Close() { } // Constructs a new compressedResponseWriter based on client request headers. +// The compression starts with the response header. func newCompressedResponseWriter(writer http.ResponseWriter, req *http.Request) *compressedResponseWriter { encodings := strings.SplitSeq(req.Header.Get(acceptEncodingHeader), ",") for encoding := range encodings { - switch strings.TrimSpace(encoding) { - case zstdEncoding: - encoder, err := zstd.NewWriter(writer) - if err == nil { - writer.Header().Set(contentEncodingHeader, zstdEncoding) - return &compressedResponseWriter{ResponseWriter: writer, writer: encoder} - } - case snappyEncoding: - writer.Header().Set(contentEncodingHeader, snappyEncoding) - return &compressedResponseWriter{ResponseWriter: writer, writer: snappy.NewBufferedWriter(writer)} - case gzipEncoding: - writer.Header().Set(contentEncodingHeader, gzipEncoding) - return &compressedResponseWriter{ResponseWriter: writer, writer: gzip.NewWriter(writer)} - case deflateEncoding: - writer.Header().Set(contentEncodingHeader, deflateEncoding) - return &compressedResponseWriter{ResponseWriter: writer, writer: zlib.NewWriter(writer)} + switch encoding = strings.TrimSpace(encoding); encoding { + case zstdEncoding, snappyEncoding, gzipEncoding, deflateEncoding: + return &compressedResponseWriter{ResponseWriter: writer, writer: writer, encoding: encoding} } } return &compressedResponseWriter{ResponseWriter: writer, writer: writer} diff --git a/pkg/api/queryapi/compression_test.go b/pkg/api/queryapi/compression_test.go index ce949b63ee9..bb9b1811ce9 100644 --- a/pkg/api/queryapi/compression_test.go +++ b/pkg/api/queryapi/compression_test.go @@ -157,3 +157,38 @@ func TestCompressionHandler_ServeHTTP(t *testing.T) { decompressed := decompress(t, gzipEncoding, rec.Body.Bytes()) require.Equal(t, []byte("hello"), decompressed) } + +func TestCompressionHandler_ShouldNotCompressErrorResponses(t *testing.T) { + for _, tc := range []struct { + statusCode int + expectCompressed bool + }{ + {statusCode: http.StatusOK, expectCompressed: true}, + {statusCode: http.StatusBadRequest, expectCompressed: false}, + {statusCode: http.StatusInternalServerError, expectCompressed: false}, + } { + t.Run(http.StatusText(tc.statusCode), func(t *testing.T) { + payload := []byte(`{"status":"error","error":"something went wrong"}`) + handler := CompressionHandler{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.statusCode) + _, err := w.Write(payload) + require.NoError(t, err) + })} + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + req.Header.Set(acceptEncodingHeader, gzipEncoding) + + handler.ServeHTTP(rec, req) + + require.Equal(t, tc.statusCode, rec.Code) + if tc.expectCompressed { + require.Equal(t, gzipEncoding, rec.Header().Get(contentEncodingHeader)) + require.Equal(t, payload, decompress(t, gzipEncoding, rec.Body.Bytes())) + } else { + require.Empty(t, rec.Header().Get(contentEncodingHeader)) + require.Equal(t, payload, rec.Body.Bytes()) + } + }) + } +} diff --git a/pkg/api/queryapi/query_api_test.go b/pkg/api/queryapi/query_api_test.go index 7dd13ba7549..a32a1aa1f5f 100644 --- a/pkg/api/queryapi/query_api_test.go +++ b/pkg/api/queryapi/query_api_test.go @@ -258,6 +258,35 @@ func Test_InvalidCodec(t *testing.T) { require.Equal(t, http.StatusNotAcceptable, rec.Code) } +func Test_ErrorResponseIsNotCompressed(t *testing.T) { + engine := engine2.New( + promql.EngineOpts{ + MaxSamples: 100, + Timeout: time.Second * 2, + }, + engine2.ThanosEngineConfig{Enabled: false}, + prometheus.NewRegistry()) + + queryAPI := NewQueryAPI(engine, &mockSampleAndChunkQueryable{}, querier.StatsRenderer, log.NewNopLogger(), []v1.Codec{v1.JSONCodec{}}, regexp.MustCompile(".*"), stats.PhaseTrackerConfig{}) + router := mux.NewRouter() + router.Path("/api/v1/query").Methods("POST").Handler(queryAPI.Wrap(queryAPI.InstantQueryHandler)) + + req := httptest.NewRequest(http.MethodPost, "/api/v1/query?query=test&time=invalid", nil) + req.Header.Set(acceptEncodingHeader, gzipEncoding) + ctx := context.Background() + _, ctx = stats.ContextWithEmptyStats(ctx) + req = req.WithContext(user.InjectOrgID(ctx, "user1")) + + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + require.GreaterOrEqual(t, rec.Code, http.StatusBadRequest) + + // The error must be readable as is, for example when the response body is logged. + require.Empty(t, rec.Header().Get(contentEncodingHeader)) + require.Contains(t, rec.Body.String(), `"status":"error"`) + require.Contains(t, rec.Body.String(), `invalid parameter \"time\"`) +} + func Test_CustomAPI_StatsRenderer(t *testing.T) { engine := engine2.New( promql.EngineOpts{ From 95cc6477f8bbc444a1f8421aecec7289b29170d3 Mon Sep 17 00:00:00 2001 From: Andrey Osipov Date: Tue, 1 Dec 2026 23:10:38 +0700 Subject: [PATCH 2/2] Add the PR number to the CHANGELOG entry Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01YDgKpXdZmLs9YSYU1ZSf8d Signed-off-by: Andrey Osipov --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8108f0c7dbb..44513fb5c87 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,7 @@ * [BUGFIX] Ring: Fix `DoBatch` counting a key more than once when more replicas than the quorum succeed, which in rare cases could hide a write error from a key that did not reach quorum. A distributor push now always waits until every series reaches quorum, so it returns the error of a series that misses quorum, and takes as long as its slowest series to reach quorum. #7975 * [BUGFIX] Compactor: Stop downloading the parquet files and the `parquet-converter-mark.json` and `parquet-no-convert-mark.json` markers written by the parquet converter under a block's prefix. Compaction never reads them, so they only used local disk and bandwidth until the compaction job ended. #7972 * [BUGFIX] Ring: Fix shuffle-sharding subrings treating instances with a stale heartbeat as healthy when using the DynamoDB KV store. #7976 -* [BUGFIX] Querier: Stop compressing query API error responses. Clients sending `Accept-Encoding`, such as the Go HTTP client which sends `gzip` by default, got compressed error responses, so the logged body of a failed query was an unreadable compressed blob. #XXXX +* [BUGFIX] Querier: Stop compressing query API error responses. Clients sending `Accept-Encoding`, such as the Go HTTP client which sends `gzip` by default, got compressed error responses, so the logged body of a failed query was an unreadable compressed blob. #7979 ## 1.22.0 2026-11-19