Skip to content

perf(http): compress responses with brotli, gzip fallback - #860

Merged
sv merged 1 commit into
mainfrom
feat/compress-responses
Sep 16, 2026
Merged

sv merged 1 commit into
mainfrom
feat/compress-responses

Conversation

@sv

@sv sv commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

What

Responses are now compressed on the wire. Callers see no change in bytes — compression is a transport encoding, so a client decodes to exactly what it got before, and the export stays byte-exact for offline re-verification.

Why

#859: the CDN asks this origin for gzip, br on every request (16,782 of 16,782 in one capture) and the service answered every one in plaintext, so the whole metered origin leg was uncompressed.

Brotli rather than Starlette's built-in GZipMiddleware because on this service's own payloads it wins on both axes, which seemed the only honest reason to take a dependency: streamed in store.EXPORT_CHUNK blocks, br q=4 is 2.62x at 162 MB/s against gzip-6's 2.35x at 66 MB/s. bench/compression.py reproduces it. The cost is stated in pyproject.toml: this is the first dependency that brings its own, and dropping to GZipMiddleware(compresslevel=4) is a three-line swap keeping ~88% of the win — happy to take that instead.

application/x-ndjson is not in the library's default allow-list, so /r/<room>/export — the largest lane by far — needs the explicit add_compress_type. tests/http/test_compression.py covers that specific silent failure.

One existing assertion in test_docs.py moved: Vary is now Accept, Accept-Encoding on the negotiating documents, so it checks the Accept dimension rather than the whole header.

Note for merge

This grows core/app.py 1020 -> 1023 code lines. It is inside the policy cap (1030, so sz.py --caps and the PR's CI are green), but it moves the ratchet, so main will want uv run sz.py --update-baseline after merge — the deliberate step the workflow comment describes for growth. The three lines are an import, add_compress_type and the middleware entry; CompressMiddleware takes no content-type argument, so none of them consolidates away.

Checks

  • uv run coverage run -m pytest tests -q && uv run coverage report — 775 passed, 1 skipped, 97.97%
  • uv run ruff check . && uv run ruff format --check . and uv run ty check
  • Docs that would now be wrong are updated: none — no served document states an encoding
  • New surface on a world-writable service: nothing new. No new route or parameter. Compression can leak a secret only where one is stable across responses that mix in attacker-controlled bytes (BREACH); there is no auth, no cookie and no session here, and the one per-response secret — the /humans CSP nonce — is regenerated every response.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-16T07:26:54.957528Z 8209351 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8209351691

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app.py Resolved
@WIZARDspace

Copy link
Copy Markdown
Contributor

@sv — #858 and this PR don't collide in code, but they do collide in the size budget, and
nothing on either PR will catch it.

Both grow core/app.py. Measured on the current heads (5de0efc, 8209351) merged onto
main@20a4457 separately and together, uv run sz.py --caps:

tree core/app.py cap headroom
main@20a4457 1020 1030 10
+ #858 1027 1030 3
+ #860 1023 1030 7
both 1030 1030 0

--caps exits 0 in all four, including both — it is a ceiling, and 1030 is not over it. So no
PR gate flags this and whichever merges second lands the file exactly on its cap, leaving the
next change to app.py, from anyone, with nothing to spend.

One figure to correct while you are here: #858's body says "core/app.py grows 5 code-lines
(1020 → 1025, cap 1030)". That was true of 6bbaa65; after 5de0efc it is +7, and
sz.py --check prints core/app.py 1020 -> 1027 (cap 1030). Together the ratchet reads
1020 -> 1030.

On the P1 above. --check is not a PR gate, so this PR does not leave "the repository's
required core-size check failing". .github/workflows/ci.yml:

uv run sz.py
if [[ "${{ github.event_name }}" != "pull_request" ]]; then
  uv run sz.py --check
fi

with the comment directly above it saying the ratchet "stays on pushes to main, where
maintainers can regenerate it after reviewing the merged change". It will go red on the push to
main until sz-baseline.json is regenerated, which is that documented step — and on an in-repo
branch the protected-files rule does not stand in the way, so "rather than updating the
maintainer-owned baseline" is advice aimed at a fork contributor, not at you.

The P1 also cites commit fb14fca5, which is not in this PR — its only commit is 8209351.

Nothing needed from me here; flagging the arithmetic before the second merge rather than after.

@NyxClawd

Copy link
Copy Markdown

On exact head 8209351691f2b847aee1f58d34e0a0d2d18a031f, the export benchmark is not exercising the middleware mode this PR configures. starlette-compress==1.8.0 makes add_compress_type(..., streaming=False) the default; its responder then calls encoder.feed(body, False), while bench/compression.py::streamed_brotli calls flush() after every 64 KiB input chunk. The PR uses add_compress_type("application/x-ndjson") without streaming=True, so the benchmark and runtime differ exactly at that flush.

I verified this against the wheel pinned by this PR (sha256:3c991e21...456b623). With the PR benchmark corpus (4,180,345 bytes, 64 x 64 KiB input chunks), Brotli q=4 in the configured no-flush mode emitted from process() on only one input chunk, first at chunk index 56; about 3.7 MiB had entered the compressor before the first compressed body bytes emerged. The benchmark flush-per-chunk mode does not expose that latency/buffering behavior.

That changes an explicitly streaming, up-to-10-MiB export into a response whose body can sit silent for megabytes, increasing first-body latency and per-export buffering; the current TestClient assertions only inspect the fully decoded result, so they cannot catch the lost chunk cadence. If 64 KiB streaming is intended, register NDJSON with streaming=True (which makes the runtime match this benchmark) and add an ASGI-level regression that observes output before several MiB of input. If the no-flush ratio is preferred, the benchmark and PR claims should measure that mode and the buffering/TTFB tradeoff should be explicit.

@sv
sv merged commit 542790b into main Sep 16, 2026
14 checks passed
@sv
sv deleted the feat/compress-responses branch September 16, 2026 14:53
sv added a commit that referenced this pull request Sep 17, 2026
## What

Cuts **0.14.0**: folds `[Unreleased]` into a dated section, bumps the
version the service, the MCP wrapper and the worker share (the same
eight files as #776), and re-ratchets `sz-baseline.json`. Three verified
doc corrections ride along. Nothing a caller sees changes until the tag.

## Why

Three commits since v0.13.0: #860 (brotli on the wire), #796 (the manual
names the operator's measurement probe), and #858 (`/stats` served stale
while it refreshes), which merged after this branch was cut and is now
folded in — without its entry the tag would have shipped it
undocumented.

**MINOR rather than PATCH** because #860 puts a `Content-Encoding` on
every reply and adds `Accept-Encoding` to `Vary`. Nothing a client
parses moves — compression is a transport encoding, and the export is
byte-exact once decoded — but it is an addition to the HTTP surface,
which the changelog's own rule calls MINOR, and it lands a runtime
dependency in the image. A reviewer could call it a patch; the version
files are one substitution away.

**The baseline refresh rides along**, as #860 asked for at merge and
#858 needs again: `main` has failed `sz.py --check` since #860, and #858
moved it further — `app.py` 1020 → 1030, `store.py` 992 → 987. Only the
measured `files` block moves; every cap is untouched.

**`core/app.py` is now at 1030 against a cap of 1030.** Passing, with no
headroom left: the next code line in that file fails `sz.py --caps` for
whoever writes it. Raising a cap is a policy call, so this PR states it
rather than moving it — worth a decision before the next `app.py`
change, not after.

**Three doc corrections**, each checked against the code it describes
rather than taken on trust — a release is the wrong moment to ship prose
that contradicts the service. Credit to the authors who filed them;
close those PRs as included rather than stale:

- `README.md`'s never-limited list omitted `/interop.md`, which
`limit.FREE_PATHS` has carried since the document existed (#410, @Xelp66
— and #354, @zkasuran, which found the same line first).
- The `CHAT_STILLBORN_SECONDS` row said the clamp was against a
`CHAT_IDLE_SECONDS` knob. There is no such knob:
`store.STILLBORN_SECONDS` clamps to `IDLE_SECONDS`, a fixed 7 days
(#848, @Baophan00).
- `edge/README.md` and the Worker's header comment listed `/robots.txt`
in the static-first lane. `snapshot.py`'s `STATIC_FIRST` is two paths
and says why robots.txt is not one of them — its `Sitemap` line is built
from `CHAT_PUBLIC_URL` (#850, @kuky123100-create).

I left the *path counts* in those edge files alone, which #850 also
touches: `edge/README.md` says seventeen (the snapshot surface),
`wrangler.jsonc` says sixteen where the routes list holds twenty
patterns, and `/rooms*` is a wildcard beside a comment saying nothing
here is one. Three different things are being counted; #850's
"seventeen" is not right either. That deserves its own change with a
test pinning the numbers, not a release PR. #354's other four
corrections — the 51 GiB → 50 GiB arithmetic among them — are likewise
left to that PR.

After merge, by hand and in this order: tag `v0.14.0` and `mcp-v0.14.0`,
which builds the image and publishes the wrapper; pull the image on the
box; then `edge/deploy.sh`, once the origin is up, so the snapshot
carries this release's documents — including the two-document static
lane.

## Checks

- [x] `uv run coverage run -m pytest tests -q && uv run coverage report`
— 782 passed, 1 skipped, 98.01% (after the `main` merge that brought
#858 in)
- [x] `uv run ruff check . && uv run ruff format --check .` and `uv run
ty check` — clean
- [x] `uv lock --check` (root and `mcp/worker`, after `uv build
--project mcp` produces the 0.14.0 wheel), `uv run sz.py --caps`, `uv
run sz.py --check`, `uv run just contract` (881 cases, no issues), and
both gates `release.yml` runs before building
- [x] Verified on a booted service, not just in tests: `/openapi.json`
and `/config` report `0.14.0`; `Content-Encoding: br` with `Vary:
Accept-Encoding`, and `Vary: Accept, Accept-Encoding` on the four `.md`
documents — which is what the deployer note in the changelog now states
- [x] Docs that would now be wrong are updated: `CHANGELOG.md` is the
change; the three corrections above are the rest; the manual and
`/skill.md` need nothing
- [x] New surface on a world-writable service: **nothing new** — no
route, parameter or persistent state moves

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01KPQWysM3BJjzZCtyfPZGE4

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
WIZARDspace added a commit to WIZARDspace/technocore-chat that referenced this pull request Sep 21, 2026
Clean auto-merge, no conflicts. The one file where a clash was plausible was
src/app.py: flop-labs#860 added the compression import and the middleware entry while
this branch rewrote note_list, and the two never touch the same lines.
tests/http/test_notes.py took both sides' appended tests; tests/http/test_stats.py
resolved to main's copy unchanged.

sz-baseline.json is regenerated because the merge brings main's copy, which reads
this branch's core growth as drift:

    core/store.py 987 -> 992 (cap 1010)

Those five lines are note_ns_stats and note_ns_footer. No cap moved -- the caps
block is byte-identical to main's, and every other change in the file is a
recounted measurement. core/app.py stays at 1030 code lines, unchanged from main
and exactly at its cap, which is the reason the footer rendering sits in
store.py rather than in the handler.

Checks: ruff check, ruff format --check, ty check, sz.py --check and sz.py --caps
all clean. 791 passed, 1 skipped; coverage 98.02%.
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.

3 participants