fix(proxy): bound brotli output per step and lossless inverse expansion (#4861)

## Description

Two places could allocate far more memory than the input size justifies:

1. **Brotli request bodies** (`_brotli_bounded` in
`headroom/proxy/helpers.py`): the body was fed to
`Decompressor.process()` in 64 KiB input slices, with the 100 MB cap
checked after each slice. One slice of a highly compressed body (a
1,681-byte body holding 1 GiB of zeros) expands in full inside a single
`process()` call before the check runs.
2. **Lossless compaction self-checks** (`compact_lossless` in
`headroom/transforms/lossless_compaction.py`): to confirm a fold
round-trips, it runs `expand_runs` / `unfold_repeated_blocks` on the
candidate. Those inverses read their repeat counts from the text, so a
marker line already present in tool output (`... (repeated 2000000
times)`, or chained `... (repeats N lines from N lines back)` lines that
double each time) made the check allocate millions of lines.

Fixes:

1. `process()` is called with `output_buffer_limit=64 KiB`. Pending
output is drained with `process(b"")` before the next slice (brotli
accepts only empty input while it holds unprocessed input) and again
after the last slice until `is_finished()`, with the cap checked after
every step. brotli older than 1.2.0 has no output limit, so it is now
refused for `br` bodies with a clear upgrade message, the same way a
brotli without `Decompressor` already was.
2. `expand_runs` and `unfold_repeated_blocks` take an optional
`max_chars`. Every line is charged its length plus its newline before it
is appended: a run costs `count * (len(line) + 1)`, and a block copy is
costed by summing the copied lines. Going over the limit raises a
private `CompressionError` subclass before anything is allocated, and
the content is returned unchanged. The extra character for the dropped
last newline is allowed only when the input has no trailing newline.
`compact_lossless` bounds each inverse by the text it must reproduce:
the content itself, or for config, the run-collapsed text that the block
inverse must rebuild (it can be longer than the content). Called without
`max_chars`, both public functions behave exactly as before.

Fix adapted from a proposal by HetCreep. Change from that proposal: with
real brotli 1.2.1, `can_accept_more_data()` is already True once all
input is consumed even while output is still pending, so stopping there
cut off normal bodies (600 KB of text failed as "truncated stream").
This version drains until `is_finished()`.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/proxy/helpers.py`: `_brotli_bounded` pulls output in limited
steps, drains pending output, and requires `can_accept_more_data`
(brotli>=1.2.0).
- `headroom/transforms/lossless_compaction.py`: `_OutputBudget` and
`max_chars` on `expand_runs` / `unfold_repeated_blocks`;
`compact_lossless` passes per-stage limits and returns the content
unchanged when one is exceeded.
- `tests/test_lossless_expansion_limit.py` (new), using tracemalloc so
it works on any OS:
- a run marker (log/text/config) and chained block markers stay under an
8 MB peak;
- a 1 MiB line expanded 1000x with 1000 shrinking markers, and 1000
block copies of it, stay under 16 MB;
- the exact `max_chars` boundary holds for both inverses, with and
without a trailing newline;
- a config fold whose run-collapsed intermediate is longer than the
content is still kept;
  - the block inverse on 400 KB of short lines stays under 6 MB;
  - real repeats still fold.
- `tests/test_request_body_decompression_limits.py`: fake decompressors
for the per-step bound, the fail-closed path on old brotli, and draining
output that is still pending after the last slice.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

New tests on `origin/main` code:

```text
E   AssertionError: peak 133.5MB: the marker count was expanded
E   AssertionError: peak 217.4MB: the block markers were unfolded
E   AssertionError: peak 128.0MB suggests one slice was fully expanded
FAILED tests/test_lossless_expansion_limit.py::test_run_marker_in_input_is_not_expanded[log]
FAILED tests/test_lossless_expansion_limit.py::test_run_marker_in_input_is_not_expanded[text]
FAILED tests/test_lossless_expansion_limit.py::test_run_marker_in_input_is_not_expanded[config]
FAILED tests/test_lossless_expansion_limit.py::test_chained_block_markers_in_config_are_not_expanded
FAILED tests/test_request_body_decompression_limits.py::test_brotli_step_output_is_bounded
FAILED tests/test_request_body_decompression_limits.py::test_brotli_without_output_limit_fails_closed
```

With the fix:

```text
$ pytest -q tests/test_request_body_decompression_limits.py tests/test_lossless_expansion_limit.py
======================== 32 passed, 2 skipped in 1.68s =========================
# same file with brotli 1.2.1 importable (the 2 skips are real-brotli tests):
$ pytest -q tests/test_request_body_decompression_limits.py
============================== 29 passed in 4.32s ==============================
$ pytest -q tests/test_lossless_expansion_limit.py tests/test_lossless_excluded_compaction.py tests/test_transforms_config_compressor.py tests/test_request_body_decompression_limits.py tests/test_lossless_diff_fold_guard.py tests/test_lossless_timestamp_guard.py tests/test_bash_search_lossless_fold.py
======================== 177 passed, 2 skipped in 6.90s ========================
$ ruff check / ruff format --check (0.17.3): All checks passed
$ mypy headroom/proxy/helpers.py headroom/transforms/lossless_compaction.py --ignore-missing-imports
Success: no issues found in 2 source files
```

## Real Behavior Proof

- Environment: macOS (Apple silicon), Python 3.12, brotli 1.2.1.
- Exact command / steps: built a 1 GiB-of-zeros brotli stream (1,681
bytes compressed) and called `_brotli_bounded`. Then round-tripped
`b""`, `b"x"`, 600 KB of text, 300 KB of random bytes, 50 MB of zeros
and 5 MB of repeated random data, plus a stream with its last 3 bytes
cut off.
- Observed result: `refused: Decompressed brotli request body exceeds
100MB`, max RSS growth 100 MB, 0.09 s. All round trips were exact. The
cut-off stream gave `Failed to decompress brotli request body: truncated
stream`.
- Lossless: `compact_lossless(("X" * 1 MiB) + "\n... (repeated 1000
times)\n" + "a\n... (repeated 1 times)\n" * 1000, "text")` returns the
input unchanged with a 3.1 MiB tracemalloc peak. With a line limit only,
it peaked at 1002 MiB.
- Not tested: a full proxy request carrying `Content-Encoding: br` (the
reader dispatches to the same function).

## Runtime Rollout Safety

- Rollout-managed feature(s): none
- Minimum rollout channel: n/a
- Stable/default behavior changed: `br` request bodies are now refused
(400 with an upgrade message) when the installed `brotli` is older than
1.2.0. brotli is an optional install, and gzip/deflate/zstd are
unaffected. Lossless compaction leaves content unchanged only when it
carries markers asking for more lines than it has.
- Kill switch / disable path: upgrade `brotli` to >=1.2.0
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation — n/a
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

The memory tests use tracemalloc peaks, not RLIMIT_AS, so they run on
macOS as well as Linux.

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

Reported by @JoaoMarcos44. Thank you for your contribution! 🩵

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Tejas Chopra
2026-11-14 10:46:38 +05:30
committed by GitHub
co-authored by Claude Opus 5.5 JerrettDavis
parent 5d44855c6f
commit 5503383bef
4 changed files with 303 additions and 13 deletions
+25 -5
View File
@@ -3227,7 +3227,7 @@ def _zstd_bounded(raw: bytes) -> bytes:
def _brotli_bounded(raw: bytes) -> bytes:
"""Feed brotli input in slices, checking the cap after each one."""
"""Feed brotli input in slices, pulling at most one chunk of output per step."""
import brotli
decompressor_cls = getattr(brotli, "Decompressor", None)
@@ -3240,16 +3240,36 @@ def _brotli_bounded(raw: bytes) -> bytes:
)
decompressor = decompressor_cls()
can_accept_more = getattr(decompressor, "can_accept_more_data", None)
if can_accept_more is None:
# Before brotli 1.2.0, process() has no output limit: one small input
# slice can expand without bound before the size check runs.
raise ValueError(
"Installed 'brotli' cannot bound decompressed output "
"(needs brotli>=1.2.0); upgrade it to accept br request bodies."
)
out = bytearray()
for start in range(0, len(raw), _DECOMPRESS_CHUNK_SIZE):
out += decompressor.process(raw[start : start + _DECOMPRESS_CHUNK_SIZE])
def pull(data: bytes) -> bytes:
chunk: bytes = decompressor.process(data, output_buffer_limit=_DECOMPRESS_CHUNK_SIZE)
out.extend(chunk)
if len(out) > MAX_DECOMPRESSED_BODY_SIZE:
raise RequestBodyTooLarge(
f"Decompressed brotli request body exceeds "
f"{MAX_DECOMPRESSED_BODY_SIZE // (1024 * 1024)}MB"
)
is_finished = getattr(decompressor, "is_finished", None)
if is_finished is not None and not is_finished():
return chunk
for start in range(0, len(raw), _DECOMPRESS_CHUNK_SIZE):
pull(raw[start : start + _DECOMPRESS_CHUNK_SIZE])
# While the decompressor holds unprocessed input it accepts only empty
# input; drain its output before feeding the next slice.
while not can_accept_more() and pull(b""):
pass
# All input is in, but output beyond the per-call limit is still pending.
while not decompressor.is_finished() and pull(b""):
pass
if not decompressor.is_finished():
raise ValueError("Failed to decompress brotli request body: truncated stream")
return bytes(out)
+65 -8
View File
@@ -33,6 +33,7 @@ __all__ = [
"compact_lossless",
]
from ..exceptions import CompressionError
from ..log_safety import describe_exception, safe_id
logger = logging.getLogger(__name__)
@@ -136,11 +137,47 @@ def collapse_runs(text: str) -> str:
return _join(out, had_trailing)
def expand_runs(text: str) -> str:
"""Exact inverse of :func:`collapse_runs`."""
class _ExpansionLimitExceeded(CompressionError):
"""An inverse would produce more text than its ``max_chars`` allows."""
class _OutputBudget:
"""Characters an inverse may still emit (``None`` = unlimited).
A line costs its length plus its newline, so the budget also bounds the
line count. Checked before each append, so an oversized expansion is
refused before it is allocated.
"""
def __init__(self, max_chars: int | None, had_trailing: bool) -> None:
self.max_chars = max_chars
self.used = 0
# Without a trailing newline, the join drops the newline charged to
# the last line, so one more character fits.
self.slack = 0 if had_trailing else 1
def take(self, chars: int) -> None:
if self.max_chars is None:
return
self.used += chars
if self.used > self.max_chars + self.slack:
raise _ExpansionLimitExceeded(
"Lossless inverse would exceed its size limit",
details={"max_chars": self.max_chars, "requested": self.used},
)
def expand_runs(text: str, max_chars: int | None = None) -> str:
"""Exact inverse of :func:`collapse_runs`.
Repeat counts are read from the text itself, so a marker line already in
the input can ask for any amount of output. With ``max_chars`` set, a line
or marker that would take the output past it raises before allocating.
"""
lines, had_trailing = _split_keep_trailing(text)
if not lines:
return text
budget = _OutputBudget(max_chars, had_trailing)
out: list[str] = []
i = 0
n = len(lines)
@@ -150,9 +187,11 @@ def expand_runs(text: str) -> str:
m = _RUN_MARKER_RE.match(lines[i + 1])
if m:
count = int(m.group(1))
budget.take(count * (len(line) + 1))
out.extend([line] * count)
i += 2
continue
budget.take(len(line) + 1)
out.append(line)
i += 1
return _join(out, had_trailing)
@@ -221,11 +260,16 @@ def _remember(positions: dict[str, list[int]], line: str, index: int) -> None:
del bucket[0]
def unfold_repeated_blocks(text: str) -> str:
"""Exact inverse of :func:`fold_repeated_blocks`."""
def unfold_repeated_blocks(text: str, max_chars: int | None = None) -> str:
"""Exact inverse of :func:`fold_repeated_blocks`.
``max_chars`` bounds the output as in :func:`expand_runs`; without it,
chained markers can double the output once per marker line.
"""
lines, had_trailing = _split_keep_trailing(text)
if not lines:
return text
budget = _OutputBudget(max_chars, had_trailing)
out: list[str] = []
for line in lines:
m = _BLOCK_MARKER_RE.match(line)
@@ -233,8 +277,12 @@ def unfold_repeated_blocks(text: str) -> str:
length, dist = int(m.group(1)), int(m.group(2))
start = len(out) - dist
if start >= 0 and length <= dist:
# Cost the block before copying it; same order of work as
# the copy, no extra allocation.
budget.take(sum(len(out[k]) + 1 for k in range(start, start + length)))
out.extend(out[start : start + length])
continue
budget.take(len(line) + 1)
out.append(line)
return _join(out, had_trailing)
@@ -506,7 +554,7 @@ def compact_lossless(content: str, kind: str) -> str:
# exactly reversible against the de-ANSI'd baseline.
baseline = strip_ansi(content)
candidate = collapse_runs(baseline)
if expand_runs(candidate) != baseline:
if expand_runs(candidate, len(baseline)) != baseline:
return content
return candidate if _smaller(candidate, content) else content
@@ -540,17 +588,26 @@ def compact_lossless(content: str, kind: str) -> str:
if kind == "text":
# Collapse blank-line runs; reversible against itself.
candidate = collapse_runs(content)
if expand_runs(candidate) != content:
if expand_runs(candidate, len(content)) != content:
return content
return candidate if _smaller(candidate, content) else content
if kind == "config":
# Structured config (YAML/TOML/INI): single-line runs first, then
# repeated multi-line stanzas. Inverse applies in reverse order.
candidate = fold_repeated_blocks(collapse_runs(content))
if expand_runs(unfold_repeated_blocks(candidate)) != content:
# The block inverse must reproduce the run-collapsed text, which
# can be longer than the content (a run marker outgrows a short
# repeated line), so each inverse is bounded by its own target.
collapsed = collapse_runs(content)
candidate = fold_repeated_blocks(collapsed)
unfolded = unfold_repeated_blocks(candidate, len(collapsed))
if expand_runs(unfolded, len(content)) != content:
return content
return candidate if _smaller(candidate, content) else content
except _ExpansionLimitExceeded:
# The input itself carried marker lines asking for more lines than it
# has, so the fold cannot round-trip; leave the content as it is.
return content
except Exception as e:
# The exception text can quote the content, so no level logs it;
# describe_exception keeps only types and code locations.
+129
View File
@@ -0,0 +1,129 @@
"""The lossless round-trip checks must not expand past the input's own size.
``expand_runs`` and ``unfold_repeated_blocks`` read repeat counts from marker
lines, and tool output may already contain such lines. ``compact_lossless``
only needs to know whether the inverse reproduces the input, so an expansion
longer than the input is a failed round-trip and is abandoned before it is
allocated. Memory is measured with tracemalloc, so this runs on any OS.
"""
from __future__ import annotations
import tracemalloc
from collections.abc import Callable
import pytest
from headroom.exceptions import CompressionError
from headroom.transforms.lossless_compaction import (
compact_lossless,
expand_runs,
unfold_repeated_blocks,
)
MB = 1024 * 1024
def _peak_of(call: Callable[[], str]) -> tuple[str, int]:
tracemalloc.start()
try:
tracemalloc.reset_peak()
result = call()
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
return result, peak
@pytest.mark.parametrize("kind", ["log", "text", "config"])
def test_run_marker_in_input_is_not_expanded(kind: str) -> None:
text = "A" * 60 + "\n... (repeated 2000000 times)\ntail\n"
result, peak = _peak_of(lambda: compact_lossless(text, kind))
assert result == text
assert peak < 8 * MB, f"peak {peak / MB:.1f}MB: the marker count was expanded"
def test_chained_block_markers_in_config_are_not_expanded() -> None:
lines = ["a: 1", "b: 2", "c: 3"]
size = 3
for _ in range(20): # 3 * 2**20 lines if unfolded
lines.append(f"... (repeats {size} lines from {size} lines back)")
size *= 2
text = "\n".join(lines) + "\n"
result, peak = _peak_of(lambda: compact_lossless(text, "config"))
assert result == text
assert peak < 8 * MB, f"peak {peak / MB:.1f}MB: the block markers were unfolded"
def test_real_repeats_still_fold() -> None:
log = "same line\n" * 50 + "end\n"
folded = compact_lossless(log, "log")
assert "(repeated 50 times)" in folded
assert len(folded) < len(log)
config = "name: x\nvalue: 1\n" * 30
assert len(compact_lossless(config, "config")) < len(config)
@pytest.mark.parametrize(
"text",
[
"a\nb", # no markers
"a\n... (repeated 2 times)", # valid run marker
"a\n... (repeats 5 lines from 1 lines back)", # invalid block marker, kept as a line
],
)
def test_inverses_hold_max_chars_for_every_line(text: str) -> None:
for inverse in (expand_runs, unfold_repeated_blocks):
with pytest.raises(CompressionError):
inverse(text, max_chars=1)
assert inverse(text, max_chars=100) == inverse(text)
# A long line expanded by a marker, offset by many markers that shrink the
# line count back: the line count stays under the input's, the size does not.
_WIDE_LINE_RUN = (
"X" * (1024 * 1024) + "\n... (repeated 1000 times)\n" + "a\n... (repeated 1 times)\n" * 1000
)
_WIDE_LINE_BLOCK = "X" * (1024 * 1024) + "\n" + "... (repeats 1 lines from 1 lines back)\n" * 1000
@pytest.mark.parametrize(
("text", "kind"),
[
(_WIDE_LINE_RUN, "text"),
(_WIDE_LINE_RUN, "log"),
(_WIDE_LINE_RUN, "config"),
(_WIDE_LINE_BLOCK, "config"),
],
ids=["run-text", "run-log", "run-config", "block-config"],
)
def test_wide_line_expansion_is_refused_before_allocating(text: str, kind: str) -> None:
result, peak = _peak_of(lambda: compact_lossless(text, kind))
assert result == text
assert peak < 16 * MB, f"peak {peak / MB:.1f}MB: the wide line was expanded"
@pytest.mark.parametrize("trailing", ["", "\n"])
def test_inverses_hold_max_chars_exactly(trailing: str) -> None:
text = "ab\ncd" + trailing
for inverse in (expand_runs, unfold_repeated_blocks):
assert inverse(text, max_chars=len(text)) == text
with pytest.raises(CompressionError):
inverse(text, max_chars=len(text) - 1)
def test_config_fold_kept_when_run_collapse_lengthens_short_lines() -> None:
value = "x" * 40
stanza = f"name: {value}\nvalue: {value}\nother: {value}\n"
config = stanza * 2 + "\n\n"
folded = compact_lossless(config, "config")
assert len(folded) < len(config)
assert expand_runs(unfold_repeated_blocks(folded)) == config
def test_block_inverse_without_markers_stays_lean() -> None:
text = "a\nb\n" * 100000
result, peak = _peak_of(lambda: unfold_repeated_blocks(text, len(text)))
assert result == text
assert peak < 6 * MB, f"peak {peak / MB:.1f}MB"
@@ -18,6 +18,7 @@ from __future__ import annotations
import gzip
import io
import sys
import tracemalloc
import zlib
@@ -409,3 +410,86 @@ async def test_reader_ignores_an_untrustworthy_content_length(small_raw_cap: int
request = _Request(oversized, "", headers={"content-length": "not-a-number"})
with pytest.raises(_helpers().RequestBodyTooLarge):
await _helpers()._read_request_body_bytes(request)
# ───────────────── brotli: output bounded per step, not per input slice ─────
class _FakeBrotliDecompressor:
"""Mimics brotli>=1.2.0 ``Decompressor`` output limiting without the package.
Each non-empty input slice "expands" to ``EXPANSION`` zero bytes. With
``output_buffer_limit`` the surplus stays pending inside the decompressor
(``can_accept_more_data()`` is False until drained); without it the whole
expansion is returned at once, which is the bomb.
"""
EXPANSION = 64 * MB
def __init__(self) -> None:
self.pending = 0
def process(self, data: bytes, output_buffer_limit: int | None = None) -> bytes:
self.pending += self.EXPANSION if data else 0
n = self.pending if output_buffer_limit is None else min(self.pending, output_buffer_limit)
self.pending -= n
return b"\x00" * n
def can_accept_more_data(self) -> bool:
return self.pending == 0
def is_finished(self) -> bool:
return self.pending == 0
def test_brotli_step_output_is_bounded(monkeypatch, small_cap: int) -> None:
"""One input slice that expands far past the cap must not be materialized."""
import types
monkeypatch.setitem(
sys.modules, "brotli", types.SimpleNamespace(Decompressor=_FakeBrotliDecompressor)
)
tracemalloc.start()
try:
tracemalloc.reset_peak()
with pytest.raises(_helpers().RequestBodyTooLarge):
_helpers()._brotli_bounded(b"x" * 100)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
assert peak < 8 * MB, f"peak {peak / MB:.1f}MB suggests one slice was fully expanded"
def test_brotli_without_output_limit_fails_closed(monkeypatch) -> None:
import types
class _Old:
def process(self, data: bytes) -> bytes:
return data
monkeypatch.setitem(sys.modules, "brotli", types.SimpleNamespace(Decompressor=_Old))
with pytest.raises(ValueError, match="brotli>=1.2.0"):
_helpers()._brotli_bounded(b"x")
class _FakeBrotliAcceptingWhilePending(_FakeBrotliDecompressor):
"""Real brotli 1.2 reports it can accept input once all input is consumed,
even while limited output is still pending; the rest comes from empty
``process(b"")`` calls."""
EXPANSION = 3 * 1024 * 1024 + 123
def can_accept_more_data(self) -> bool:
return True
def test_brotli_drains_output_pending_after_the_last_slice(monkeypatch) -> None:
import types
monkeypatch.setitem(
sys.modules,
"brotli",
types.SimpleNamespace(Decompressor=_FakeBrotliAcceptingWhilePending),
)
out = _helpers()._brotli_bounded(b"x")
assert len(out) == _FakeBrotliAcceptingWhilePending.EXPANSION