Lazily allocate GZipMiddleware compression resources

Merged
KL
3mo ago
+20-3

Summary

  • lazily allocate BytesIO and GzipFile only when a response is compressed
  • retain context-managed, reverse-order cleanup on normal completion and application errors
  • add regression coverage for responses below minimum_size, existing Content-Encoding, text/event-stream, and http.response.pathsend
  • update the gzip benchmark to use the lazy compression context

Motivation

GZipResponder previously constructed the gzip buffer and compressor before it knew whether the response should be compressed. Bypassed responses therefore paid the compressor's allocation cost even though their body was forwarded unchanged.

This keeps the public GZipMiddleware configuration and response behavior unchanged while avoiding those allocations for bypassed responses. CodSpeed's memory-mode bypass benchmarks will measure the resulting allocation reduction.

Validation

  • scripts/check
  • uv run pytest — 989 passed, 2 skipped, 2 xfailed
  • focused gzip tests and representative CodSpeed benchmark cases on Python 3.14