Skip to content

Request compressed API responses (zstd/gzip) and decode them transparently - #458

Merged
tomaz-lc merged 6 commits into
masterfrom
feat-accept-encoding-gzip
Nov 13, 2026
Merged

tomaz-lc merged 6 commits into
masterfrom
feat-accept-encoding-gzip

Conversation

@tomaz-lc

@tomaz-lc tomaz-lc commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

The SDK and CLI now ask the API for compressed responses and decode them before returning. Return values, parsed JSON and error messages are unchanged; only the bytes on the wire shrink. On a synthetic 142 MiB search result page, the wire size drops 4.6x with gzip and 5.2x with zstd, and the download time over a throttled link drops by the same factor.

  • Accept-Encoding: zstd, gzip when a Zstandard decoder is importable (the standard library on Python 3.14+, or the optional zstandard package on 3.10-3.13), else Accept-Encoding: gzip.
  • Bodies are decoded by the response's own Content-Encoding, while they stream in, with the same peak memory as an uncompressed read.
  • Opt out with Client(compressed_responses=False) or LC_NO_RESPONSE_COMPRESSION=1.
  • No new required dependency. A new optional extra, limacharlie[zstd], installs zstandard for Python 3.10-3.13.
  • A compressed response may decode to at most 1 GiB (LC_MAX_DECODED_RESPONSE_BYTES / Client(max_decoded_response_bytes=...) change it), so a response with an extreme compression ratio cannot exhaust memory. Uncompressed responses are not limited.
  • The search stream for detections is named detection, as the Search API requires. The SDK docstrings and CLI help named it detect, which the API rejects with HTTP 400; detect is now sent as detection.

Background

Client sends requests with urllib.request.urlopen and set no Accept-Encoding of its own, so http.client sent Accept-Encoding: identity and the API always answered uncompressed. JSON responses compress well, and the largest of them, search result pages, can be very large. Every caller paid the full uncompressed transfer, which dominates the run time on a slow link.

The API compresses a response when the client asks: it negotiates gzip and zstd, honours q-values, and picks zstd when both are offered with equal weight. It does not produce br or deflate, so the client does not ask for them.

Implementation

All requests made through Client share one code path, so the change sits in two places:

Place What it does
Client._add_accept_encoding() Adds Accept-Encoding to every request built by _rest_call (all SDK calls, request(), raw_request()) and _call_jwt_endpoint. A caller that sets its own Accept-Encoding in extra_headers keeps it.
Client._read_body() / _read_error_body() Reads success and HTTPError bodies through limacharlie._http_compression.read_body().

limacharlie/_http_compression.py (new, private):

  • content_codings() collects every Content-Encoding header line, case-insensitively, dropping identity and empty elements.
  • read_body() removes the codings last-applied first (RFC 9110 8.4), so stacked codings and multiple header lines work. With no coding it returns fp.read() unchanged.
  • gzip and x-gzip use gzip.GzipFile: multi-member streams, CRC-32 and length checks, EOFError on truncation.
  • zstd uses compression.zstd.ZstdFile on Python 3.14+. Before 3.14 it uses the zstandard package when installed, through a small frame loop over decompressobj(). The package's own stream_reader returns a truncated frame's prefix as the whole body with no error, so the loop tracks frame boundaries itself, starts each frame from the previous one's unused_data (which also consumes skippable frames), and raises when the input ends inside a frame. A zstandard too old to report decompressobj().eof is not used.
  • Decoding streams from the socket in 256 KiB steps into one BytesIO, whose bytes are returned without a final copy. The compressed body is never held in full.
  • An empty body is empty whatever coding it is labelled with.
  • Decoded-size limit: every layer of the decoder chain is wrapped in a reader that fails once it has produced more than the limit (default 1 GiB). gzip and compression.zstd return at most the requested bytes per read, so they stop within one 256 KiB step of the limit. The zstandard package's decompressobj() returns all the output of its input, so that input is fed in pieces of at most (limit - decoded so far) / 65,536 bytes. 65,536 is above the densest zstd expansion (an RLE block: 4 bytes to 128 KiB), so one piece cannot overshoot the limit by more than about 1 MiB.
  • Why 1 GiB: the largest responses that go through this decoder are search result pages, which decode to a few hundred megabytes at most. Listings, CSV exports and single records are smaller or paged, and bulk downloads use signed URLs, which are not decoded here.

Errors:

Case Result
Truncated or corrupt stream (bad checksum, trailing garbage, cut-off frame or member) on a 2xx ResponseDecodeError, never a partial body
Connection closed early under Content-Length ResponseDecodeError: urllib's sized reads return short silently, so a cut inside a member or frame is caught by the stream's end marker, and a cut exactly between members or frames by the unmet Content-Length
A coding the client cannot decode (br, deflate, zstd with no decoder) ResponseDecodeError naming it
A body that decodes to more than the limit ResponseDecodeError naming the limit and LC_MAX_DECODED_RESPONSE_BYTES, after at most the limit plus one decode step of output
Timeout, reset, chunked body cut mid-chunk Unchanged transport exception
4xx/5xx with a compressed body Decoded; the status-code exception carries the server's message as before
4xx/5xx whose body cannot be decoded The status-code exception still raises (auth refresh, 429 backoff and 5xx retries still apply), with a short note in place of the body

ResponseDecodeError subclasses ApiError, so existing except ApiError handlers keep catching it. It is not retried: the search poll loop treats it as non-transient.

Entry points covered: every limacharlie.sdk.* class (they all call Client.request/raw_request), the search API (Search.execute initiate, page polls and cancel, validate, estimate, query listing), the JWT endpoint, and every CLI command built on them (limacharlie api, search run, ...). All of these send the lc-cli/<version> User-Agent, except the JWT endpoint, which sends urllib's default User-Agent as before.

Search stream names: the Search API accepts event, detection and audit in a request's stream field and answers HTTP 400 to anything else. Search.execute, validate, estimate and search saved-create now send detect, in any case, as detection (limacharlie.sdk.search.search_stream()), and pass every other value through for the server to validate. Their docstrings and the search run, search estimate and search saved-create help now name detection. Outputs, Spout and firehose keep detect, which is the correct name in those APIs.

Left as they are, deliberately:

  • Signed-URL downloads (artifacts, payloads, case exports, SBOM documents, sensor and adapter installers): callers expect the stored bytes exactly, some of which are already compressed files.
  • Uploads (artifact ingestion, payload PUT): tiny JSON responses.
  • External services (GitHub API during rule conversion, the public IP lookup in firehose).
  • Paths built on requests (OAuth, spout): requests already negotiates and decodes compression itself.

Architecture

flowchart LR
    A[SDK / CLI call] --> B[Client._rest_call]
    B -->|Accept-Encoding| C[(API)]
    C -->|Content-Encoding: zstd / gzip / none| D[_http_compression.read_body]
    D -->|decoded bytes| E[json.loads / text, unchanged]
    D -->|truncated, corrupt, unsupported| F[ResponseDecodeError]
Loading

Client-only change. No server change is needed.

Backward Compatibility

  • Return types and values are unchanged for every call: same bytes, same text, same parsed JSON, same exception classes for HTTP status codes.
  • Client.__init__ gains two keyword arguments, compressed_responses: bool | None = None and max_decoded_response_bytes: int | None = None, appended last.
  • A compressed response that decodes to more than 1 GiB raises ResponseDecodeError where it was returned before; no API response comes near that size. Uncompressed responses are never limited.
  • stream="detect" in a search now works (sent as detection) where it failed with HTTP 400. No other stream value changes.
  • New public exception limacharlie.errors.ResponseDecodeError(ApiError).
  • raw_request() still returns (status, data) for every HTTP status, but a 2xx body that cannot be decoded raises ResponseDecodeError rather than being returned truncated or as {}.
  • A response that arrives compressed is decoded even with the opt-out set. That case returned {} (the JSON parse of gzip bytes failed silently) before.
  • Proxies and servers that ignore Accept-Encoding keep working: an absent or identity Content-Encoding is read as before.
  • Python 3.10-3.14 supported, as before.

Configuration and opt-out

Setting Effect Default
Client(compressed_responses=False) Send no Accept-Encoding (urllib then sends identity) None: on unless the env var is set
LC_NO_RESPONSE_COMPRESSION=1 Same, for the SDK and the CLI. 0, false, no, off and empty read as unset unset
pip install 'limacharlie[zstd]' Adds the zstandard decoder on Python 3.10-3.13 so zstd is requested not installed
LC_MAX_DECODED_RESPONSE_BYTES=<bytes> Most bytes a compressed response may decode to. 0 or negative removes the limit; a non-integer warns and keeps the default 1073741824 (1 GiB)
Client(max_decoded_response_bytes=<bytes>) Same, for one client; overrides the environment variable None: environment or 1 GiB

Documented in doc/sdk/README.md (Compressed Responses), README.md, doc/authentication.md and CHANGELOG.md.

Performance

Fixture: a synthetic search-like JSON page, 142.1 MiB, 178,522 event rows with repeated hosts, paths and command lines and random per-row ids and hashes. It is served by a local Go HTTP server that negotiates gzip and zstd the way the API does. Real pages compress better than this fixture, because its random ids and hashes do not compress. Linux x86-64 laptop, arms interleaved, separate process per run. master is origin/master measured with the identical harness; the opt-out arm on this branch measured the same as master.

Wire size:

Bytes on the wire vs master
master (identity) 142.1 MiB 1.0x
gzip 31.1 MiB 4.6x smaller
zstd 27.3 MiB 5.2x smaller

Download over a link throttled to 10 MiB/s, raw_response=True, 3 runs each, median [min-max]:

Python Wall time Client CPU
master 3.11 14.39 s [14.37-14.43] 0.17 s [0.16-0.21]
gzip 3.11 3.17 s [3.16-3.17] 0.89 s [0.82-0.91]
zstd (zstandard) 3.11 2.78 s [2.78-2.78] 0.65 s [0.65-0.69]
gzip 3.14 3.17 s [3.17-3.19] 0.81 s [0.80-0.86]
zstd (stdlib) 3.14 2.80 s [2.79-2.80] 0.60 s [0.59-0.63]

The time saved scales with the link: on a slower link the saving is larger in absolute seconds and the ratio stays at the wire-size ratio.

Memory for the same page, unthrottled:

Peak traced memory (tracemalloc, 1 run) Peak RSS growth (3 runs)
master 284.3 MiB 298-299 MiB
gzip 284.3 MiB 285 MiB
zstd 284.3 MiB 286-287 MiB

Decoding adds no memory over an uncompressed read: both end holding the body as bytes and as text. With full JSON parsing the RSS growth is 817 MiB on master, 805 MiB gzip and 806 MiB zstd (3 runs each, identical across runs).

Decoding cost (tests/microbenchmarks/test_response_compression_microbenchmark.py, 6.7 MB page): gzip 14.1 ms (about 480 MB/s decoded), zstd 5.6 ms (about 1.2 GB/s) on Python 3.11; gzip 16.1 ms, zstd 5.0 ms on 3.14. That CPU is the cost of this change: about 0.5 s more client CPU per 142 MiB page with gzip and about 0.25 s with zstd. On an unthrottled loopback link, where the transfer costs nothing, a page therefore takes longer than on master (0.17 s master, about 0.5 s zstd, about 0.9 s gzip, including the server compressing it). Over any real network link the saved transfer time is much larger.

Testing

tests/unit/test_client_response_compression.py drives the real Client, Search and CLI over real sockets to an http.server on 127.0.0.1. The server records every request's headers and answers with what the test chose. Every test runs three times: with compression.zstd, with zstandard, and with no zstd decoder. Each case is produced by hiding modules from the SDK's import (a None entry in sys.modules) and re-importing its compression module; no SDK code is replaced.

  • Request header on every path: all verbs, raw_request, the JWT endpoint, a caller-supplied header, the opt-out by argument and by environment (truthy and falsy values), and the argument overriding the environment.
  • Decoding: gzip, x-gzip, mixed case and whitespace, identity labels, stacked codings in one header and across header lines, multi-member gzip, zstd single and multi-frame, skippable frames before and after, frames with and without checksum, zstd over gzip, empty bodies labelled gzip or zstd, chunked transfer in 3-byte pieces, CSV via raw_response, non-ASCII text, a server that ignores Accept-Encoding, and an opted-out client receiving gzip anyway.
  • Broken streams, each raising ResponseDecodeError and never a partial body: truncated, missing trailer, bad CRC, bad length, trailing garbage, corrupt deflate data, not gzip; for zstd truncated, missing checksum byte, header only, truncated last frame, truncated skippable frame, bad checksum, corrupt block, trailing garbage, not zstd; a connection closed early under Content-Length, inside a member or frame and exactly between two (on 2xx and error responses); unsupported codings (br, deflate, compress, snappy, gzip, br; zstd with no decoder). Decode errors are not retried.
  • Transport errors keep their types: a socket timeout mid-body and a chunked body cut mid-chunk.
  • Compressed error bodies: 404 and 400 messages, 429 with Retry-After, 401 that refreshes the JWT and retries, 504 retried, 500 with an undecodable body still raising ApiError with status 500, and a compressed JWT endpoint error.
  • Large bodies: a 10 MB round trip, and a 25 MB body whose peak traced memory decoded stays within 1 MiB of the uncompressed read (measured equal within a few KiB).
  • Search API: a two-page paginated search (~3 MB pages) through a real Organization and Search, checking every call (org URL lookup, initiate, both polls, cancel) carried the header, the rows round-trip, and the wire was less than half the JSON. A corrupt page surfaces as SearchError caused by ResponseDecodeError after one poll.
  • CLI: limacharlie search run end to end, checking every request (JWT, URL lookup, search calls) and the lc-cli/ User-Agent, and the opt-out by environment.
  • Decoded-size limit: a 64 MiB gzip and zstd bomb (a few KiB on the wire) against a 1 MiB limit raises with peak traced memory under 8 MiB, on all three decoder arms; the same for stacked gzip, gzip; a body exactly at the limit decodes and one byte more fails; identity bodies above the limit are untouched; the environment variable raising, lowering and removing the limit (0, negative), an empty value, and invalid values (lots, 1.5e9, 1GB, 0x10) warning and keeping the default; the constructor argument overriding the environment; an oversized error body keeping its status code; and an oversized search page surfacing as SearchError.
  • tests/unit/test_search_stream_names.py: against a local search API that accepts only event, detection and audit, Search.execute, validate and estimate and the CLI's search run send detection for both detection and detect, event and audit pass through, no stream sends no field, search saved-create --stream detect stores detection, and the help of search run, estimate and saved-create names detection.
  • tests/unit/test_packaging.py: zstandard is never a hard dependency, the zstd extra exists and installs it only below Python 3.14 (3.14+ uses the standard library), and dev pulls it in so CI covers that decoder on 3.10-3.13.

Full suite (pytest tests/unit/ tests/microbenchmarks/): 5,567 passed on Python 3.10 and 3.11, 5,685 passed on 3.14. The skips on 3.10-3.13 are the compression.zstd runs, which need 3.14.

End-to-end testing

Run against the production LimaCharlie API with a test organization, through api.limacharlie.io, the JWT endpoint and the organization's search API host. Read-only calls only. Each arm ran in its own virtualenv, and master is the current release code (origin/master) with the identical harness. A wrapper around urllib's urlopen recorded each request's Accept-Encoding, each response's Content-Encoding and Content-Length, and the body bytes read from the socket. It changed no SDK logic.

Arm Python Decoder Accept-Encoding sent
master 3.11.2, 3.14.10 none none (identity)
branch 3.14.10 compression.zstd zstd, gzip
branch 3.11.2 + zstandard zstandard zstd, gzip
branch 3.11.2 none gzip
branch, opt-out 3.14.10 compressed_responses=False (SDK), LC_NO_RESPONSE_COMPRESSION=1 (CLI) none (identity)

Encodings observed:

  • Both the main API and the search API returned exactly the coding the client preferred: zstd when offered zstd, gzip, gzip when offered gzip, and no coding to master and the opt-out arm.
  • Bodies under 1 KiB uncompressed (search status polls, cancel, validate, limits, org info, the org URL lookup) came back uncompressed in every arm, and were read unchanged.
  • The JWT endpoint never compressed (about 2.3 KiB, chunked) whatever was requested.
  • limacharlie api ontology -H 'Accept-Encoding: gzip': the server answers gzip. Master prints {}. Every branch arm, including the opt-out arm, prints the decoded JSON.

Correctness, branch vs master:

  • SDK Search.execute, 5 query shapes, 16 runs per shape (3 per arm, 1 for master on 3.11): row count and the sha256 of the sorted canonical rows were identical in all 16. Facets and timeline items, and the summed eventsScanned, bytesScanned and eventsMatched, were identical too. For every shape except the aggregation the row order was identical as well; the aggregation's row order differs between runs on master itself.
  • Page boundaries are chosen by the server. In 3 of 45 compressed runs it split one page in two or added an empty trailing page. The rows were identical.
  • CLI limacharlie search run (paginated event search, aggregation, invalid query): identical rows, facets and timeline, exit codes and error text in every arm.
  • Other reads through the SDK and CLI were identical in every arm: org info and URLs, a paged sensor list (49 pages, 11.7 MiB), outputs, tags, online sensors, D&R and extension hive lists, search validate and limits. Ontology, event types and tags come back in a different list order on each call, so they were compared order-insensitively.

Error paths, all identical to master (exception class, status code, message):

  • An invalid JWT is refreshed after the 401 and the call then succeeds.
  • An unknown API key fails at the JWT endpoint with AuthenticationError (401).
  • 404 on a search poll for an unknown query id: NotFoundError.
  • An invalid LCQL query, short and about 4 KB long: a 400 from execute (SearchError), and the same error result from validate.
  • 400 on an invalid stream name, an unknown sensor and an unknown hive record. The CLI's sensor get gives the same exit code and stderr.

The server sent these error bodies uncompressed (they are under 1 KiB). Compressed error bodies are covered by the unit tests above.

Bytes on the wire (median of the runs; ratio vs master on the same Python):

Shape rows / pages master, 3.11 master, 3.14 opt-out, 3.14 gzip, 3.11 zstd (zstandard), 3.11 zstd (stdlib), 3.14
Paginated event search 10,930 / 13 8.68 MiB 8.68 MiB 8.68 MiB 0.92 MiB (9.5x) 0.81 MiB (10.8x) 0.81 MiB (10.8x)
Large-page event search 21,462 / 23 33.43 MiB 33.43 MiB 33.43 MiB 3.37 MiB (9.9x) 2.69 MiB (12.4x) 2.69 MiB (12.4x)
Detection stream 677 / 3 8.14 MiB 8.14 MiB 8.14 MiB 1.47 MiB (5.5x) 0.89 MiB (9.1x) 0.89 MiB (9.1x)
Aggregation (GROUP BY) 68 / 1 18.6 KiB 18.6 KiB 18.6 KiB 7.9 KiB (2.4x) 7.8 KiB (2.4x) 7.8 KiB (2.4x)
Audit stream 42 / 1 28.7 KiB 28.6 KiB 28.6 KiB 8.0 KiB (3.6x) 8.0 KiB (3.6x) 7.9 KiB (3.6x)
Paged sensor list (n=1) 49 pages 11.74 MiB 11.74 MiB 11.74 MiB 1.48 MiB (7.9x) 1.35 MiB (8.7x) 1.34 MiB (8.8x)

The largest single search page was 6.4 MiB uncompressed, 0.68 MiB as zstd and 1.08 MiB as gzip.

Wall time, client CPU and peak RSS. Each figure is the median [min-max]; n=3, except master on 3.11, which is a single run. With n=3 the p99 equals the max.

Shape Arm Wall s Client CPU s Peak RSS MiB
Paginated event search master, 3.14 35.7 [34.5-38.3] 1.04 [0.76-1.13] 86 [86-87]
Paginated event search opt-out, 3.14 35.9 [34.3-39.2] 0.76 [0.72-1.04] 87 [86-87]
Paginated event search gzip, 3.11 34.3 [33.5-47.6] 0.71 [0.68-0.97] 85 [85-85]
Paginated event search zstd (zstandard), 3.11 37.3 [35.7-40.3] 0.74 [0.68-1.03] 86 [86-86]
Paginated event search zstd (stdlib), 3.14 32.5 [29.5-48.8] 0.65 [0.55-0.85] 87 [87-87]
Large-page event search master, 3.11 (n=1) 78.0 4.89 249
Large-page event search master, 3.14 73.3 [72.9-92.2] 2.67 [2.32-3.12] 244 [244-244]
Large-page event search opt-out, 3.14 76.0 [72.2-87.5] 2.77 [2.45-2.91] 244 [244-244]
Large-page event search gzip, 3.11 63.9 [61.8-69.5] 2.25 [1.86-3.06] 250 [249-250]
Large-page event search zstd (zstandard), 3.11 64.5 [63.7-68.1] 2.27 [1.84-2.98] 250 [250-250]
Large-page event search zstd (stdlib), 3.14 68.8 [66.9-72.9] 3.02 [2.19-3.07] 245 [245-245]
Detection stream master, 3.14 9.7 [9.6-10.4] 0.42 [0.37-0.64] 70 [70-70]
Detection stream opt-out, 3.14 9.8 [9.3-9.9] 0.47 [0.31-0.57] 70 [70-70]
Detection stream gzip, 3.11 9.5 [9.2-9.7] 0.43 [0.42-0.46] 68 [68-68]
Detection stream zstd (zstandard), 3.11 9.2 [9.1-10.3] 0.46 [0.35-0.62] 69 [69-69]
Detection stream zstd (stdlib), 3.14 9.2 [8.9-10.3] 0.39 [0.23-0.40] 71 [71-71]

How to read these numbers:

  • Wall time is dominated by the server running the query and by the poll interval it sets, not by the transfer. The differences in wall time are mostly inside the master-vs-opt-out spread, which is the noise floor. Only the large-page shape moves beyond it (about 6-13% faster).
  • Client CPU stays within the range master shows between its own runs. The decode cost is offset by less data passing through TLS and the socket. Peak RSS is unchanged.
  • Setup: a Linux x86-64 laptop on a residential internet link. Runs were sequential and interleaved across arms in rotating order, with one query at a time.

Not covered end to end: batch search mode (the SDK does not select a search mode, and the test organization defaults to interactive), and a compressed 4xx/5xx body from the real server.

Rollback

  1. Per process or user: LC_NO_RESPONSE_COMPRESSION=1, or Client(compressed_responses=False) in code. No reinstall needed.
  2. If the decoded-size limit ever stops a legitimate response: LC_MAX_DECODED_RESPONSE_BYTES=<larger> or 0 to remove it.
  3. Uninstall zstandard on Python 3.10-3.13 to fall back from zstd to gzip.
  4. Pin the previous release of limacharlie, or revert this commit and release.

Watch after rollout

  • Issues mentioning ResponseDecodeError, "Failed to decode the ... response body" or "decodes to more than": should be none. Something re-encoding responses in between (a proxy sending br) or a broken stream would show here.
  • Search download times reported by users on slow links: pages should arrive several times faster.
  • Client CPU in tight loops over large responses on fast links: up to about 0.5 s per 142 MiB page with gzip, about 0.25 s with zstd.

Related PRs

  • documentation#603 - documents compressed responses, the limacharlie[zstd] extra, the opt-out and the decoded-size limit; to merge after the release that contains this change.

🤖 Generated with Claude Code

@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

Found 1 Medium issue: a likely flaky memory assertion in the new tests. I found no correctness problems in _http_compression.py or in the client.py changes. I checked how decode errors move through _rest_call, request(), _call_jwt_endpoint and the search poll loop. ResponseDecodeError has no status code, so is_transient does not retry it.

General Feedback

  • test-time-budget: No test-time-budget check run exists for this commit. The base branch master does not require it in branch protection or in rulesets, and this PR does not add or change anything that creates the check. So this check does not block the review.
  • Low: the decoded size has no cap. A response with a very high compression ratio can grow to any size in memory. Before this PR, memory was limited by the bytes sent on the wire. Every caller targets the first-party API over TLS, so this is not a blocker. A cap tied to a sane maximum page size would be a cheap safety net.

Blast Radius

  • Client._rest_call and _call_jwt_endpoint now send Accept-Encoding and decode bodies on every request. That covers every limacharlie.sdk.* class, the search, AI and replay services reached through alt_root, the JWT endpoint and every CLI command built on them.
  • New public API: Client(compressed_responses=...), limacharlie.errors.ResponseDecodeError (a subclass of ApiError) and the LC_NO_RESPONSE_COMPRESSION environment variable.
  • Behaviour change for callers of raw_request(): a 2xx body that cannot be decoded now raises ResponseDecodeError instead of returning (code, data).
  • Packaging: new optional extra zstd, and dev now pulls in zstandard.
  • Code that mocks urlopen and returns objects with Content-Encoding headers but without matching bodies will now go through the decoder.

This review was generated automatically by Claude Code.

@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

I re-reviewed the PR at 9c98675. The earlier Medium finding (the flaky tracemalloc test) is fixed. I found one new Low issue, so the verdict is APPROVED.

General Feedback

  • test-time-budget: No test-time-budget check run exists for this commit. master does not require the check in branch protection or in rulesets. This PR does not change anything that creates the check. It does not block this review.
  • Low, still open from the last review: the decoded size has no cap. A body with a very high compression ratio can use any amount of memory. A cap tied to a sane maximum page size would be a cheap safety net.

Blast Radius

  • Every request made through Client._rest_call and _call_jwt_endpoint now sends Accept-Encoding and decodes the body. That covers all limacharlie.sdk.* classes, request()/raw_request(), services reached through alt_root (search and others), and every CLI command built on them.
  • New public surface: Client(compressed_responses=...), limacharlie.errors.ResponseDecodeError (an ApiError subclass) and LC_NO_RESPONSE_COMPRESSION.
  • raw_request() can now raise ResponseDecodeError on a 2xx response.
  • Packaging: new zstd extra. dev now installs zstandard.
  • Downstream tests that mock urlopen with a Content-Encoding header but a plain body will now hit the decoder.

This review was generated automatically by Claude Code.

Comment thread limacharlie/_http_compression.py Resolved
@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

I re-reviewed the PR at a849696. The earlier Low finding is fixed: a body cut exactly at a member or frame boundary is now caught. I found no new issues.

General Feedback

  • test-time-budget: This commit has no test-time-budget check run. master does not require the check, either in branch protection or in rulesets. This PR does not change anything that creates the check, so it does not block this review.
  • Low, still open from earlier reviews: the decoded size has no cap. A body with a very high compression ratio can use any amount of memory. A cap tied to a sane maximum page size would be a cheap safety net.

Blast Radius

  • Every request made through Client._rest_call and _call_jwt_endpoint now sends Accept-Encoding and decodes the body. That covers all limacharlie.sdk.* classes, request() and raw_request(), services reached through alt_root, and every CLI command built on them.
  • New public surface: Client(compressed_responses=...), limacharlie.errors.ResponseDecodeError (an ApiError subclass) and LC_NO_RESPONSE_COMPRESSION.
  • raw_request() can now raise ResponseDecodeError on a 2xx response. That includes a compressed body that falls short of its Content-Length.
  • Packaging: new zstd extra. dev now installs zstandard.
  • Downstream tests that mock urlopen with a Content-Encoding header but a plain body will now go through the decoder.

This review was generated automatically by Claude Code.

tomaz-lc and others added 3 commits November 13, 2026 19:46
…arently

The client sent no Accept-Encoding of its own, so urllib asked for
"identity" and every response, including multi-megabyte search result
pages, crossed the wire uncompressed.

Every request made through Client (API calls, raw_request, the JWT
endpoint, the search API and the CLI built on them) now sends
Accept-Encoding and decodes the body by the response's Content-Encoding:

- "zstd, gzip" when a Zstandard decoder is importable: the standard
  library's compression.zstd on Python 3.14+, else the optional zstandard
  package (new "zstd" extra). Otherwise "gzip", from the standard library.
- gzip, x-gzip, zstd, stacked codings and identity are decoded while the
  body streams in, into one buffer, so peak memory matches an
  uncompressed read.
- A truncated or corrupt stream, or a coding the client did not ask for,
  raises the new ResponseDecodeError (an ApiError) instead of returning a
  partial body. An error response whose body cannot be decoded still
  raises the exception for its status code.
- Client(compressed_responses=False) or LC_NO_RESPONSE_COMPRESSION=1
  turns the request header off. A caller's own Accept-Encoding is kept.

Signed-URL downloads (artifacts, payloads, exports, installers) keep
reading raw bytes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tracemalloc traces every thread, including the in-process test server's
handler thread. Compressing the reply inside the traced window could leave
the compressed body alive at the client's peak on a busy runner and fail
the bound for reasons unrelated to decoding. Both replies are now built
up front, so the server thread only sends existing bytes while tracing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ames

A connection that closes early exactly at a gzip member or zstd frame
boundary looks like a clean end to the decoder, so the first members were
returned as the whole body. http.client still records the Content-Length
shortfall; read_body now raises ResponseDecodeError when it is non-zero,
as an uncompressed read raises IncompleteRead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tomaz-lc
tomaz-lc force-pushed the feat-accept-encoding-gzip branch from a849696 to 1066046 Compare November 13, 2026 18:46
@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

I re-reviewed the PR at 1066046. The branch was rebased, so the earlier fixes are now in 0bd04c8 (memory test replies built before tracing) and 1066046 (Content-Length shortfall check). Both are present and correct. I found no new High or Medium issues.

What I checked again on this commit:

  • ResponseDecodeError subclasses ApiError, not ValueError. So the except ValueError in _rest_call does not turn it into {}. It propagates, and _is_transient_poll_error does not retry it.
  • In _call_jwt_endpoint, a decode error on a 2xx is wrapped as AuthenticationError by the existing except Exception. That matches how other JWT read failures are reported.
  • read_body checks fp.length after decoding. This catches a cut that lands exactly on a member or frame boundary.

General Feedback

  • test-time-budget: No test-time-budget check run exists for this commit. master does not require the check in branch protection or in rulesets, and this PR does not change anything that creates it. So it does not block this review.
  • Low, still open from earlier reviews: the decoded size has no cap. A body that compresses very well can grow to any size in memory. Before this PR, memory was bounded by the bytes on the wire. A cap tied to a sane maximum page size would be a cheap safety net.
  • Low: the zstd extra has no python_version < \"3.14\" marker. The comment in pyproject.toml and the docs say 3.14+ needs nothing extra, but pip install limacharlie[zstd] (and dev) still installs zstandard there. It is harmless because the stdlib decoder is chosen first. Add the marker if the extra is meant only for 3.10-3.13.

Blast Radius

  • Every request through Client._rest_call and _call_jwt_endpoint now sends Accept-Encoding and decodes the body. That covers all limacharlie.sdk.* classes, request() / raw_request(), services reached through alt_root (search and others), and every CLI command built on them.
  • New public API: Client(compressed_responses=...), limacharlie.errors.ResponseDecodeError (an ApiError subclass) and LC_NO_RESPONSE_COMPRESSION.
  • raw_request() can now raise ResponseDecodeError on a 2xx response, including a compressed body that falls short of its Content-Length.
  • Packaging: new zstd extra, and dev now installs zstandard.
  • Downstream tests that mock urlopen and return a Content-Encoding header with a plain body will now go through the decoder and may fail.

This review was generated automatically by Claude Code.

tomaz-lc and others added 2 commits November 13, 2026 19:58
A compressed response could expand without bound: a few kilobytes on the
wire with an extreme compression ratio could inflate to gigabytes before
anything noticed, where an uncompressed response is bounded by the bytes
actually received.

read_body now enforces a decoded-size limit while decoding, on every layer
of the decoder chain. Exceeding it raises ResponseDecodeError naming the
limit and how to change it, after at most the limit plus one decode step of
output, never a partial body. The zstandard package's decompressobj has no
output limit, so its input is fed in pieces sized from the remaining budget
and the densest zstd expansion (an RLE block).

- Default 1 GiB: the largest API responses, search result pages, decode to
  a few hundred megabytes at most, and other decoded responses are smaller
  or paged.
- LC_MAX_DECODED_RESPONSE_BYTES=<bytes> or
  Client(max_decoded_response_bytes=...) changes it; 0 or a negative value
  removes it; a non-integer value warns and keeps the default.
- Uncompressed responses are not limited, exactly as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… requires

The Search API accepts `event`, `detection` and `audit` in a request's
stream field and answers HTTP 400 to anything else. The SDK docstrings and
the `search run`, `search estimate` and `search saved-create` help named the
detection stream `detect`, so following them failed.

- Docstrings and CLI help now name `detection`.
- Search.execute, validate, estimate and `search saved-create` send
  `detect` (any case) as `detection` through search_stream(), so scripts
  and saved queries that used the documented name keep working. Every
  other value is passed through for the server to validate.
- Outputs, Spout and firehose keep `detect`, the correct name there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tomaz-lc

Copy link
Copy Markdown
Contributor Author

Resolved in 209365a: the review summary point that the decoded size has no cap. A compressed response may now decode to at most 1 GiB (LC_MAX_DECODED_RESPONSE_BYTES or Client(max_decoded_response_bytes=...) to change it, 0 to remove it), enforced while decoding on every layer, so a high-ratio stream raises ResponseDecodeError with bounded memory; uncompressed responses are unchanged.

@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

I re-reviewed the PR at edfc573. This review covers the two commits added since the last one: 209365a (decoded-size limit) and edfc573 (detect is sent as detection). I found no High or Medium issues and one new Low issue.

What I checked in the new code:

  • _LimitedReader wraps every decoder layer. GzipFile.read(n) and ZstdFile.read(n) return at most n bytes, so the stdlib paths stop within one 256 KiB step of the limit.
  • _ZstandardReader._piece_size keeps each decompress() call under about 1 MiB of overshoot near the limit. With the default 1 GiB limit, input is fed in 16 KiB pieces. This costs a little extra per call but is fine.
  • When the limit is hit on an error response, _read_error_body replaces the body, so the status code still raises. When it is hit on a search page, the error reaches the caller as SearchError, and it is not retried, because ResponseDecodeError has no status code.
  • The bomb memory tests build their replies before tracemalloc.start(), so the server thread only sends bytes that already exist inside the traced window.
  • search_stream() is applied in execute, validate (which estimate uses too) and saved-create. Saved queries that already store detect also work, because they go through execute.

General Feedback

  • test-time-budget: No test-time-budget check run exists for this commit. master does not require it in branch protection or in rulesets (both lists are empty). This PR does not change anything that creates the check, so it does not block this review.
  • Low, still open: the zstd extra has no python_version < \"3.14\" marker, so limacharlie[zstd] and dev still install zstandard on 3.14+, where the docs say nothing extra is needed. This does no harm, because the stdlib decoder is chosen first.
  • The earlier Low point about a missing decoded-size cap is fixed in 209365a.

Blast Radius

  • Every request through Client._rest_call and _call_jwt_endpoint now sends Accept-Encoding and decodes the body. That covers all limacharlie.sdk.* classes, request() / raw_request(), services reached through alt_root, and every CLI command built on them.
  • New public API: Client(compressed_responses=..., max_decoded_response_bytes=...), ResponseDecodeError, LC_NO_RESPONSE_COMPRESSION, LC_MAX_DECODED_RESPONSE_BYTES, limacharlie.sdk.search.search_stream and SEARCH_STREAMS.
  • Behaviour changes: a compressed body larger than 1 GiB decoded now raises. raw_request() can raise ResponseDecodeError on a 2xx. Search stream="detect" is rewritten to detection, and saved queries created with --stream detect now store detection.
  • Packaging: new zstd extra, and dev now installs zstandard.
  • Downstream tests that mock urlopen with a Content-Encoding header and a plain body will now go through the decoder.

This review was generated automatically by Claude Code.

…he size-limit env in tests

Python 3.14+ decodes zstd with the standard library, so the zstd extra (and
dev through it) no longer installs zstandard there. The compression tests
clear LC_MAX_DECODED_RESPONSE_BYTES as well, so a value set on a developer
machine or runner cannot change what the default-limit tests see.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tomaz-lc

Copy link
Copy Markdown
Contributor Author

Resolved in 97c52d8: the review summary point that the zstd extra installs zstandard on Python 3.14+. It now carries python_version < '3.14', so the extra (and dev) installs nothing there, where the standard-library decoder is used.

@tomaz-lc

Copy link
Copy Markdown
Contributor Author

/lc-review

@limacharlie-event-notifications limacharlie-event-notifications Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

AI Code Review Summary

I re-reviewed the PR at 97c52d8. One commit was added since the last review (edfc573). It changes pyproject.toml, tests/unit/test_client_response_compression.py and tests/unit/test_packaging.py. I found no new issues. Both open Low points are fixed.

  • The zstd extra now has python_version < '3.14'. On 3.14+, limacharlie[zstd] and dev no longer install zstandard, which matches the docs. On 3.14 the zstandard test arm is now skipped by _importable(). That is expected: compression.zstd covers 3.14, and zstandard stays covered on 3.10-3.13. test_packaging.py asserts the marker is present.
  • _isolate now clears LC_MAX_DECODED_RESPONSE_BYTES, so an environment value can no longer change the limit tests.

General Feedback

  • test-time-budget: This commit has no test-time-budget check run. master requires no status checks, in branch protection or in rulesets (both lists are empty). This PR does not change anything that creates the check, so it does not block this review.

Blast Radius

  • Every request through Client._rest_call and _call_jwt_endpoint now sends Accept-Encoding and decodes the body. That covers all limacharlie.sdk.* classes, request() / raw_request(), services reached through alt_root, and every CLI command built on them.
  • New public API: Client(compressed_responses=..., max_decoded_response_bytes=...), ResponseDecodeError, LC_NO_RESPONSE_COMPRESSION, LC_MAX_DECODED_RESPONSE_BYTES, and search_stream / SEARCH_STREAMS.
  • Behaviour changes:
    • A compressed body that decodes to more than 1 GiB now raises.
    • raw_request() can raise ResponseDecodeError on a 2xx response.
    • A search sent with stream="detect" is now sent as detection.
  • Packaging: there is a new zstd extra. It installs zstandard only on Python below 3.14, and dev pulls it in.
  • Downstream tests that mock urlopen and return a Content-Encoding header with a plain body will now go through the decoder.

This review was generated automatically by Claude Code.

@tomaz-lc
tomaz-lc enabled auto-merge (squash) November 13, 2026 20:05
@tomaz-lc
tomaz-lc merged commit 162c743 into master Nov 13, 2026
7 checks passed
@tomaz-lc
tomaz-lc deleted the feat-accept-encoding-gzip branch November 13, 2026 22:20
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.

2 participants