feat(http): response compression with gzip and br (CARD-16, #112) #149

Merged
chrnx merged 1 commits from feature/fprd-001c-compression into develop 2026-10-23 06:15:08 +00:00
Owner

Depends on #144 (CARD-15), which depends on #140 (CARD-14). Review and merge after both. This branch stacks on feature/fprd-001c-etag, so until those PRs merge the diff against develop includes their commits. Review only the top commit (feat(http): response compression …).

Implements CARD-16 (core #112) under decision D13 (strategy B with changes, accepted 2026-10-22).

What changed and why

  • One shared step: compressOutcome (src/http/compression.ts) runs after handle() and before either adapter writes. server.ts and web.ts both call it, so Node and the fetch runtimes cannot diverge. Without compression it returns the outcome synchronously, so the write path is unchanged.
  • Negotiation and Vary:
    • RFC 9110 §12.5.3: q-values, identity, *, q=0. Ties go to server preference.
    • Vary: Accept-Encoding is merged into an existing Vary (string or array) on identity clients, HEAD, bodies under the threshold and every 304.
    • Skipped with no Vary: existing Content-Encoding/Content-Range, missing or incompressible Content-Type (ndjson counts as compressible), and no-transform. A 204 gets nothing.
    • Content-Length is dropped from an encoded body.
  • Node, Deno, Bun: node:zlib through nodeRequire, loaded lazily. Buffered bodies always use async gzip/brotliCompress; there is no sync path. br is fixed at quality 4. CompressionStream is not used.
  • Streams (SSE, ndjson):
    • Node: pipeStream writes frames through a zlib stream piped into res, flushed after every frame, error frame and ping. Backpressure waits on the compressor's drain, and a client that leaves destroys the compressor.
    • Fetch runtimes: compressWebStream flushes per chunk and cancels the source when the body is cancelled. zlib errors are captured instead of thrown.
    • threshold does not apply to streams.
  • Edge (two signals):
    • createApp detects workerd: navigator.userAgent === 'Cloudflare-Workers', or node:zlib failing to load. This covers a bare export default { fetch: app.fetch }.
    • edgeHandler(app) marks the app explicitly through an internal Symbol.for('green-tea.mark-edge') hook, the same pattern as WS_MAX_MESSAGE_BYTES. No public API.
    • Either way, core sets Vary only and never encodes.
  • ETag (CARD-15): the tag is computed in dispatch on the identity body, before compression, and is weak. It is identical with and without compression. A handler-set strong ETag is left as it is.
  • pipeStream now takes the stream outcome rather than five positional fields. It is internal.

Deno memory (AC): plateaus, no leak found

Method: serveDeno running the fixture app, 32 keep-alive connections, 51,108 B HTML. Each round is 20,000 requests with gzip, then 20,000 with br. 15 rounds is 600,000 requests. A control run used the same load with compression off. The machine was on AC power with caffeinate running, and pmset logged no sleep or wake during the run. Deno 2.9.7, Apple Silicon. The scripts and raw JSONL are in the container at .workspace/FPRD-001/spikes/compression-c-deno-memory/.

after r1 r2 r3 r5 r8 r10 r12 r15 idle + gc() JS heap used rps gzip / br
compression on, RSS MB 399 488 492 492 495 496 499 500 498 9–24 MB throughout 2.8k / 4.4k
compression off, RSS MB 80 86 87 87 100 100 100 100 100 9–20 MB 23k
  • RSS plateaus. It climbs to about 490 MB by round 3, then moves by 8 MB over the next 12 rounds (480,000 requests, about 0.02 KB per request). The control run shows a similar 13 MB step.
  • The memory is native, not JS. Heap used stays between 9 and 24 MB and external returns to single digits between rounds.
  • It is not given back. The resident size stays after idle and a forced gc(). That looks like the allocator keeping its high-water mark from 32 concurrent zlib/brotli contexts, not a growing leak.
  • This also explains the spike's 350–780 MB spread (§7): the plateau is reached quickly, and its height varies between runs.
  • Nothing to report upstream. If you want a longer soak before RC.1 (hours rather than minutes), the harness is ready.

Covered vs the card

  • T1–T8, T11, T12, T14, T15, validation, merged Vary, strong-ETag passthrough, edge through both signals: test/compression.test.ts, on Node listen() with raw sockets and on app.fetch.
  • T9 on Node, plus a client disconnecting mid-stream (Node and fetch) and slow-client backpressure. In the backpressure test a paused client stops the generator after about 57 frames of roughly 28 KB each on macOS (more on Linux, whose socket buffers auto-tune larger). The test waits for production to stall, up to 10 s, then checks that it does not advance.
  • T10 (etag: true + gzip → same tag; the 304 carries Vary) runs now that CARD-15 is underneath.
  • Deno and Bun: real Deno.serve/Bun.serve run T1–T5, T7, T8, T10–T12, T14, T15 and T9 (test/fixtures/compression-checks.ts).
  • Documented runtime facts are pinned by tests.
    • On Deno, a 1 ms timer barely ticks while async zlib.gzip runs (main thread). If that test fails, Deno has changed and the docs should be updated.
    • On Node and Bun the timer keeps ticking (zlib runs off the main thread).
    • Deno.serve and Bun.serve do not compress by themselves.
  • Edge (test/edge/compression.ts, chained into test:edge):
    • workerd served on a real port and read with node:http; layers are peeled by magic bytes.
    • Runs through edgeHandler (T13) and through a bare app.fetch (T16), with default compat flags and again with no_global_navigator.
    • Every response has at most one layer, the original bytes and Vary; identity clients get identity; SSE arrives on time.

Unsure / not covered

  • Pings under compression have no dedicated test. They go through the same flushed sink.write as frames, but the 15 s interval is fixed, so I didn't test them separately.
  • The timer test may be fragile on a loaded CI runner. It gzips 16 MB of random bytes and refuses to judge a run under 50 ms. My first input was repetitive and finished in 4 ms on CI, which is why this guard exists. Thresholds: Deno ticks ≤ max(5, ms/10); Node and Bun ticks > ms/4. CI uses deno-version: v2.x, so a Deno release that starts offloading zlib will fail it on purpose.
  • AC-power results: the soak above ran on AC power, which covers that unmeasured item. I didn't repeat the throughput matrix; the rps column is consistent with SPIKE-COMPRESSION-B §7.
  • q follows the RFC 9110 §12.4.2 grammar (0[.ddd] or 1[.000]). A malformed or out-of-range q (2, 1e0, -1, 0.5000) excludes the member. Review fix.
  • Absent Accept-Encoding means identity. RFC 9110 allows any coding then; identity is the conservative choice. Duplicate entries in encodings are deduplicated.

Test evidence

CI run 525 on the final head (after the qvalue fix): all jobs green. An earlier run failed runtimes (bun) with TypeError: fetch failed inside setup-bun (a download, before any test ran); later runs passed.

== npm run lint
exit 0
✖ 50 problems (0 errors, 50 warnings)
== npm run format:check
exit 0
All matched files use Prettier code style!
== npm run typecheck
exit 0
== npm run test
exit 0
 Test Files  95 passed (95)
      Tests  1039 passed (1039)
== npm run build
exit 0
CJS ⚡️ Build success in 26ms
ESM ⚡️ Build success in 26ms
DTS ⚡️ Build success in 916ms
== npm run complexity:check
exit 0
✓ cognitive complexity: every function ≤ 25
== npm run test:deno
exit 0
T3 serveDeno: an IPv6 peer is passed through as Deno reports it ... ok (722µs)
ok | 45 passed | 0 failed (5s)
== npm run test:bun
exit 0
 35 pass
 0 fail
== npm run test:edge
exit 0
edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS
edge (workerd): router parity — 1158 matcher cases + 55 app.fetch cases — PASS
edge (workerd): compression — edgeHandler and bare app.fetch, with and without navigator: identity from core, ≤ 1 layer on the wire, Vary set, SSE on time — PASS

deno publish --dry-run --allow-dirty passes. Frozen router-parity captures are untouched.

Docs follow-up (CARD-12)

  • reference/createapp.md: the compression option (shape, defaults, validation), the skip list, Vary behaviour, the stream behaviour, and the ETag interplay.
  • guides/runtimes.md:
    • Node and Bun: async node:zlib; Bun.serve doesn't compress by itself.
    • Deno: zlib runs on the main thread, about 4× slower than Node for 51 KB gzip under load. automaticCompression gzip is about 3× faster but slower for br, compresses below core's threshold and weakens strong ETags. RSS plateaus around 0.5 GB at 32 concurrent compressions.
    • Workers: Vary only, the platform picks the encoding, the edgeHandler versus bare app.fetch detection, and the old-compat-date caveat.
  • guides/streaming.md: SSE and ndjson compression with per-event flush.
**Depends on #144 (CARD-15), which depends on #140 (CARD-14). Review and merge after both.** This branch stacks on `feature/fprd-001c-etag`, so until those PRs merge the diff against `develop` includes their commits. Review only the top commit (`feat(http): response compression …`). Implements **CARD-16** (core #112) under decision **D13** (strategy B with changes, accepted 2026-10-22). ## What changed and why - **One shared step:** `compressOutcome` (`src/http/compression.ts`) runs after `handle()` and before either adapter writes. `server.ts` and `web.ts` both call it, so Node and the fetch runtimes cannot diverge. Without `compression` it returns the outcome synchronously, so the write path is unchanged. - **Negotiation and `Vary`:** - RFC 9110 §12.5.3: q-values, `identity`, `*`, `q=0`. Ties go to server preference. - `Vary: Accept-Encoding` is merged into an existing `Vary` (string or array) on identity clients, `HEAD`, bodies under the threshold and every `304`. - Skipped with no `Vary`: existing `Content-Encoding`/`Content-Range`, missing or incompressible `Content-Type` (ndjson counts as compressible), and `no-transform`. A `204` gets nothing. - `Content-Length` is dropped from an encoded body. - **Node, Deno, Bun:** `node:zlib` through `nodeRequire`, loaded lazily. Buffered bodies always use async `gzip`/`brotliCompress`; there is **no sync path**. br is fixed at quality 4. `CompressionStream` is not used. - **Streams (SSE, ndjson):** - Node: `pipeStream` writes frames through a zlib stream piped into `res`, flushed after every frame, error frame and ping. Backpressure waits on the compressor's `drain`, and a client that leaves destroys the compressor. - Fetch runtimes: `compressWebStream` flushes per chunk and cancels the source when the body is cancelled. zlib errors are captured instead of thrown. - `threshold` does not apply to streams. - **Edge (two signals):** - `createApp` detects workerd: `navigator.userAgent === 'Cloudflare-Workers'`, or `node:zlib` failing to load. This covers a bare `export default { fetch: app.fetch }`. - `edgeHandler(app)` marks the app explicitly through an internal `Symbol.for('green-tea.mark-edge')` hook, the same pattern as `WS_MAX_MESSAGE_BYTES`. No public API. - Either way, core sets `Vary` only and never encodes. - **ETag (CARD-15):** the tag is computed in `dispatch` on the identity body, before compression, and is weak. It is identical with and without compression. A handler-set strong ETag is left as it is. - `pipeStream` now takes the stream outcome rather than five positional fields. It is internal. ## Deno memory (AC): plateaus, no leak found Method: `serveDeno` running the fixture app, 32 keep-alive connections, 51,108 B HTML. Each round is 20,000 requests with gzip, then 20,000 with br. 15 rounds is 600,000 requests. A control run used the same load with compression off. The machine was on AC power with `caffeinate` running, and `pmset` logged no sleep or wake during the run. Deno 2.9.7, Apple Silicon. The scripts and raw JSONL are in the container at `.workspace/FPRD-001/spikes/compression-c-deno-memory/`. | | after r1 | r2 | r3 | r5 | r8 | r10 | r12 | r15 | idle + `gc()` | JS heap used | rps gzip / br | |---|---|---|---|---|---|---|---|---|---|---|---| | compression on, RSS MB | 399 | 488 | 492 | 492 | 495 | 496 | 499 | 500 | 498 | 9–24 MB throughout | 2.8k / 4.4k | | compression off, RSS MB | 80 | 86 | 87 | 87 | 100 | 100 | 100 | 100 | 100 | 9–20 MB | 23k | - **RSS plateaus.** It climbs to about 490 MB by round 3, then moves by 8 MB over the next 12 rounds (480,000 requests, about 0.02 KB per request). The control run shows a similar 13 MB step. - **The memory is native, not JS.** Heap used stays between 9 and 24 MB and `external` returns to single digits between rounds. - **It is not given back.** The resident size stays after idle and a forced `gc()`. That looks like the allocator keeping its high-water mark from 32 concurrent zlib/brotli contexts, not a growing leak. - This also explains the spike's 350–780 MB spread (§7): the plateau is reached quickly, and its height varies between runs. - Nothing to report upstream. If you want a longer soak before RC.1 (hours rather than minutes), the harness is ready. ## Covered vs the card - T1–T8, T11, T12, T14, T15, validation, merged `Vary`, strong-ETag passthrough, edge through both signals: `test/compression.test.ts`, on Node `listen()` with raw sockets and on `app.fetch`. - T9 on Node, plus a client disconnecting mid-stream (Node and fetch) and **slow-client backpressure**. In the backpressure test a paused client stops the generator after about 57 frames of roughly 28 KB each on macOS (more on Linux, whose socket buffers auto-tune larger). The test waits for production to stall, up to 10 s, then checks that it does not advance. - T10 (`etag: true` + gzip → same tag; the 304 carries `Vary`) runs now that CARD-15 is underneath. - Deno and Bun: real `Deno.serve`/`Bun.serve` run T1–T5, T7, T8, T10–T12, T14, T15 and T9 (`test/fixtures/compression-checks.ts`). - **Documented runtime facts are pinned by tests.** - On Deno, a 1 ms timer barely ticks while async `zlib.gzip` runs (main thread). If that test fails, Deno has changed and the docs should be updated. - On Node and Bun the timer keeps ticking (zlib runs off the main thread). - `Deno.serve` and `Bun.serve` do not compress by themselves. - Edge (`test/edge/compression.ts`, chained into `test:edge`): - workerd served on a real port and read with `node:http`; layers are peeled by magic bytes. - Runs through `edgeHandler` (T13) and through a bare `app.fetch` (T16), with default compat flags and again with `no_global_navigator`. - Every response has at most one layer, the original bytes and `Vary`; identity clients get identity; SSE arrives on time. ## Unsure / not covered - **Pings under compression have no dedicated test.** They go through the same flushed `sink.write` as frames, but the 15 s interval is fixed, so I didn't test them separately. - **The timer test may be fragile on a loaded CI runner.** It gzips 16 MB of random bytes and refuses to judge a run under 50 ms. My first input was repetitive and finished in 4 ms on CI, which is why this guard exists. Thresholds: Deno ticks ≤ max(5, ms/10); Node and Bun ticks > ms/4. CI uses `deno-version: v2.x`, so a Deno release that starts offloading zlib will fail it on purpose. - **AC-power results:** the soak above ran on AC power, which covers that unmeasured item. I didn't repeat the throughput matrix; the rps column is consistent with SPIKE-COMPRESSION-B §7. - **`q` follows the RFC 9110 §12.4.2 grammar** (`0[.ddd]` or `1[.000]`). A malformed or out-of-range `q` (`2`, `1e0`, `-1`, `0.5000`) excludes the member. Review fix. - **Absent `Accept-Encoding` means identity.** RFC 9110 allows any coding then; identity is the conservative choice. Duplicate entries in `encodings` are deduplicated. ## Test evidence CI run 525 on the final head (after the qvalue fix): all jobs green. An earlier run failed `runtimes (bun)` with `TypeError: fetch failed` inside `setup-bun` (a download, before any test ran); later runs passed. ``` == npm run lint exit 0 ✖ 50 problems (0 errors, 50 warnings) == npm run format:check exit 0 All matched files use Prettier code style! == npm run typecheck exit 0 == npm run test exit 0 Test Files 95 passed (95) Tests 1039 passed (1039) == npm run build exit 0 CJS ⚡️ Build success in 26ms ESM ⚡️ Build success in 26ms DTS ⚡️ Build success in 916ms == npm run complexity:check exit 0 ✓ cognitive complexity: every function ≤ 25 == npm run test:deno exit 0 T3 serveDeno: an IPv6 peer is passed through as Deno reports it ... ok (722µs) ok | 45 passed | 0 failed (5s) == npm run test:bun exit 0 35 pass 0 fail == npm run test:edge exit 0 edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS edge (workerd): router parity — 1158 matcher cases + 55 app.fetch cases — PASS edge (workerd): compression — edgeHandler and bare app.fetch, with and without navigator: identity from core, ≤ 1 layer on the wire, Vary set, SSE on time — PASS ``` `deno publish --dry-run --allow-dirty` passes. Frozen router-parity captures are untouched. ## Docs follow-up (CARD-12) - `reference/createapp.md`: the `compression` option (shape, defaults, validation), the skip list, `Vary` behaviour, the stream behaviour, and the ETag interplay. - `guides/runtimes.md`: - Node and Bun: async `node:zlib`; `Bun.serve` doesn't compress by itself. - Deno: zlib runs on the main thread, about 4× slower than Node for 51 KB gzip under load. `automaticCompression` gzip is about 3× faster but slower for br, compresses below core's threshold and weakens strong ETags. RSS plateaus around 0.5 GB at 32 concurrent compressions. - Workers: Vary only, the platform picks the encoding, the `edgeHandler` versus bare `app.fetch` detection, and the old-compat-date caveat. - `guides/streaming.md`: SSE and ndjson compression with per-event flush.
chrnx force-pushed feature/fprd-001c-compression from 292c2f07b0 to d5643da03a 2026-10-23 05:25:03 +00:00 Compare
chrnx force-pushed feature/fprd-001c-compression from d5643da03a to 5a494d44a2 2026-10-23 05:27:46 +00:00 Compare
Author
Owner

Owner decision (2026-10-23): the Deno soak (RSS plateaus at about 500 MB, native zlib memory, no leak) is enough for RC.1, and the cost is documented. The missing keep-alive-ping-under-compression test goes to the implementation review. Not merging yet.

Owner decision (2026-10-23): the Deno soak (RSS plateaus at about 500 MB, native zlib memory, no leak) is enough for RC.1, and the cost is documented. The missing keep-alive-ping-under-compression test goes to the implementation review. Not merging yet.
chrnx force-pushed feature/fprd-001c-compression from 5a494d44a2 to 7df1eae5a1 2026-10-23 05:48:46 +00:00 Compare
Author
Owner

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.
chrnx force-pushed feature/fprd-001c-compression from 7df1eae5a1 to 29f6406c96 2026-10-23 06:04:14 +00:00 Compare
chrnx added 1 commit 2026-10-23 06:13:24 +00:00
feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
3296189093
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
chrnx force-pushed feature/fprd-001c-compression from 29f6406c96 to 3296189093 2026-10-23 06:13:24 +00:00 Compare
chrnx merged commit bfa4c1464a into develop 2026-10-23 06:15:08 +00:00
chrnx deleted branch feature/fprd-001c-compression 2026-10-23 06:15:09 +00:00
Sign in to join this conversation.