Skip to content

fix: limit the size of backend responses - #452

Merged
uniqueg merged 4 commits into
devfrom
fix/response-size-limit
Nov 7, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/response-size-limit

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

proTES now reads at most custom.tes.max_response_size bytes of each response of a TES backend (default 10485760, i.e., 10 MiB; from 1 MiB to 256 MiB), configured or discovered, as decided in #439. Larger responses fail cleanly: BackendResponseTooLarge is raised, an error is logged (Response of TES backend larger than N bytes, not read (custom.tes.max_response_size): <url>), and the rest of the response isn't read.

  • Configured backends: every request is streamed and read through read_limited (before, only FULL views were limited, to a fixed 64 MiB). Answers with statuses other than 2xx, are cut off at the limit instead of failing, so that their status still decides, and the bodies of redirects that requests follows are not read at all (a large error page of a gateway stays a refusal).
  • Discovered backends: the limit is passed to FOCA's guarded client (before, a fixed 64 MiB), and its ResponseTooLarge becomes BackendResponseTooLarge with the same log line. The guarded client fails error answers over the limit too, so a large refusal counts as an unknown outcome there (documented).
  • Task creation and cancels: a too large answer is an unknown outcome (reason response_too_large), as the backend got the request; polls count it as a failed poll; the logs of finished tasks are left out, as before; for the API-path probe of a discovered backend, the path stays unknown, so tasks go elsewhere.
  • urllib3 >= 2.6, which bounds what read1 decompresses, so that the limit also bounds the memory of compressed responses (the lock already has 2.8.0).
  • Docs: configuration reference (TES instances, discovery, post_task.max_log_size), API page, upgrade notes, base config, chart values and chart README (worker memory). The memory factor ("about 7 times") comes from the existing measurement in the docs (a 64 MiB response took a worker process up to about 420 MiB).

Not covered: the page-size part of #414 that #439 mentions (pages of the view FULL from proTES itself); the maintainer's decision covers the per-response limit only.

Closes #439

Verification

  • pytest with coverage (MongoDB mock, helm on PATH): 1710 passed, 11 skipped, 100% coverage.
  • pytest against MongoDB 7.0 (mongod --nounixsocket, own port), before the last two fix commits: 1707 passed, 1 skipped.
  • ruff 0.17.3 (check, format), mypy, ast-grep (scan, test), semgrep: clean.
  • mkdocs build --strict: clean.
  • CI: all checks passed (Lint, Test (mongomock), Test (MongoDB 7.0), Chart, Docs, Smoke test, Scan image, CodeQL, codecov), also after the Sourcery fixes (83bcd3e).

Review

Full review: adversarial-reviewer and quality-reviewer (round 1), adversarial-reviewer (round 2). Fixed: urllib3 floor for bounded decompression; non-2xx bodies cut off instead of failing; redirect bodies limited; unreachable response_too_large forward reason removed and reasons pinned in tests; tests for the logged error of discovered backends, for the POST log, for not reading beyond the limit; a raw_body test helper; docstrings and docs (cancels, API-path probe, discovered refusals). Sourcery: redirect bodies are no longer read (history and timeout), reads stop one byte past the limit.

Declined review findings

  • Rename the limited parameter of TesClient._request (quality, low): its docstring now says it only bounds the time of the read as a whole; the size is limited either way.

  • Rewrap of the module docstring (quality, low): cosmetic.

  • A table row for max_response_size (quality, low): the configuration reference documents custom.tes keys in prose, which now has the setting.

  • Cut off error answers of discovered backends too (adversarial, low): FOCA's guarded client fails them regardless of status; this needs a FOCA option, so it is documented here instead.

  • Sourcery: bound pages of the view FULL by bytes (high): not in the maintainer's decision on fix: bound memory of FULL responses #439 (see Summary).

  • Sourcery: keep the old signature of read_limited (medium): an internal helper of the app, not a library API.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 7, 2026 05:48
proTES now reads at most custom.tes.max_response_size bytes (default
10 MiB, from 1 MiB to 256 MiB) of each response of a TES backend,
configured or discovered. Larger responses raise
BackendResponseTooLarge, with an error in the logs, and the rest of the
response is not read. Before, only discovered backends and responses
with the view FULL were limited, to a fixed 64 MiB.

Creating a task with a too large answer counts as an unknown outcome
(reason response_too_large), as the backend got the request; polls
count it as a failed poll; the logs of finished tasks are left out.

Document the setting in the configuration reference, the API page,
the upgrade notes, the base config and the chart values and README.

Closes #439

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Answers of configured backends with other statuses than 2xx are cut
off at custom.tes.max_response_size instead of failing, so that their
status still decides (e.g., large error pages of gateways answering
POST /tasks with 413 stay refusals, and other backends are tried).

Require urllib3 2.6, which bounds what read1 decompresses, so that the
limit bounds memory also for compressed responses. Drop the unreachable
response_too_large entry of the forward reasons, pin the reasons in the
tests, test that oversized answers of discovered backends are logged,
that bodies aren't read beyond the limit, and add a raw_body helper.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
requests reads the body of each redirect that it follows as a whole
before following it, so a large (compressed) redirect body of a
configured backend bypassed the size limit. A response hook now reads
redirect bodies through read_limited, which cuts them off at the limit.

Document that error answers of discovered backends over the limit fail
too (FOCA's guarded client), so a large refusal is an unknown outcome.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.6.0 milestone Nov 7, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add the configurable response-size limit to the TES configuration model and its default configuration value.

  • pro_tes/config.yaml L354-359
  • pro_tes/config_models.py L385-389, L404-405, L414

API

Expose oversized backend responses as a dedicated exception and classify oversized sent requests as unknown outcomes.

  • pro_tes/exceptions.py L66-74, L84-85

Implementation

Apply the configured limit to configured and discovered backend requests, bound streamed reads, skip followed redirect bodies, and map oversized responses into the appropriate logged error and outcome handling.

  • pro_tes/ga4gh/tes/backends.py L1109-1136, L1148-1165, L1176-1194 (+13 small edits)

Configuration

Raise the urllib3 minimum version so streamed decompression remains bounded by the configured response limit.

  • pyproject.toml L133-136

Provide a chart example for the response-size setting and explain the related worker and application memory requirements.

  • deployment/README.md L494-496
  • deployment/values.yaml L66-69

Documentation

Document response-size behavior and consequences for backend requests, discovery, logs, API views, upgrades, and memory sizing.

  • docs/api.md L34-35
  • docs/configuration.md L99-121, L418-419, L539-545
  • docs/upgrading.md L94-106

Tests

Adapt backend fixtures to streamed response bodies and test limits, error classification, logging, redirects, and stopping reads at the boundary.

  • tests/ga4gh/tes/conftest.py L5, L28, L185-200
  • tests/ga4gh/tes/test_backend_list.py L451-471, L496-520, L626-634 (+4 small edits)
  • tests/ga4gh/tes/test_backend_versions.py L22-500 (6 small edits)
  • tests/ga4gh/tes/test_backends.py L52-73, L1047-1155, L1368-1381 (+8 small edits)

Lock files and vendored code

Update the dependency lockfile to record the urllib3 version constraint and resolution.

  • uv.lock L1910

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@read-the-docs-community

read-the-docs-community Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35714185 | 📁 Comparing 83bcd3e against latest (74b88a6)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (74b88a6) to head (83bcd3e).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #452   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         2799      2817   +18     
=========================================
+ Hits          2799      2817   +18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 7, 2026 05:46

@sourcery-ai sourcery-ai 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.

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="docs/configuration.md" line_range="99-119" />
<code_context>
+proTES reads at most `custom.tes.max_response_size` bytes of each response
</code_context>
<issue_to_address>
**FULL pages remain unbounded**

The issue asks for memory use of FULL pages to be bounded so chart defaults hold. This change documents a byte limit for backend responses, but does not add a byte limit for FULL pages, whose size can still exceed the estimate and chart memory.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/backends.py" line_range="1003" />
<code_context>
+                `requests` reads it as a whole otherwise, before following it.
+                """
+                if response.is_redirect:
+                    read_limited(response, max_size=self.max_response_size)
+
+            if kwargs.get("allow_redirects", True):
</code_context>
<issue_to_address>
**Redirect chains exhaust worker memory**

When a configured backend returns a long chain of redirects with bodies near the response-size limit, `read_limited` caps each redirect body, but `requests` retains followed responses in `response.history`, so the final response keeps many capped bodies and can exhaust worker memory.

Prevent redirect bodies from accumulating in `response.history` while preserving the per-response size limit.
</issue_to_address>

### Comment 3
<location path="pro_tes/ga4gh/tes/backends.py" line_range="1003" />
<code_context>
+                `requests` reads it as a whole otherwise, before following it.
+                """
+                if response.is_redirect:
+                    read_limited(response, max_size=self.max_response_size)
+
+            if kwargs.get("allow_redirects", True):
</code_context>
<issue_to_address>
**Redirects outlive the request timeout**

When a configured backend slowly streams a redirect body during a FULL-view request without going idle long enough to trigger the socket read timeout, the redirect hook calls `read_limited` without a deadline, so the request can run past `custom.tes.timeout` and keep the Celery worker blocked.

Pass and enforce the request deadline when reading redirect bodies.
</issue_to_address>

### Comment 4
<location path="pro_tes/ga4gh/tes/backends.py" line_range="1118-1120" />
<code_context>

-def read_limited(response: requests.Response, timeout: float) -> requests.Response:
-    """Read the body of a streamed response, up to `MAX_RESPONSE_SIZE` bytes.
+def read_limited(
+    response: requests.Response, max_size: int, timeout: float | None = None
+) -> requests.Response:
+    """Read the body of a streamed response, up to a size.
+
</code_context>
<issue_to_address>
**Existing helper callers break**

When an existing external caller uses the previously documented helper signature, callers using the documented `read_limited(response, timeout=...)` signature now get a `TypeError` because `max_size` is required; callers passing the timeout positionally instead treat it as a byte limit. The module is included in the generated Python API reference, so existing integrations break.

Preserve the old public signature with a compatibility path, or make the helper private and document the breaking API change.
</issue_to_address>

### Comment 5
<location path="pro_tes/ga4gh/tes/backends.py" line_range="1147-1148" />
<code_context>
         # not `iter_content`, which waits for whole chunks, however long they take
         try:
             while chunk := response.raw.read1(RESPONSE_CHUNK_SIZE, decode_content=True):
                 content += chunk
-                if len(content) > MAX_RESPONSE_SIZE:
-                    raise requests.RequestException(
-                        f"Response larger than {MAX_RESPONSE_SIZE} bytes",
-                        response=response,
-                    )
-                if time.monotonic() >= deadline:
+                if len(content) > max_size:
+                    if not 200 <= response.status_code < 300:
+                        # error answers (e.g., pages of gateways): their
</code_context>
<issue_to_address>
**Response reads exceed the configured cap**

When a response body crosses the configured size limit partway through a `read1` chunk, `read_limited` appends a full chunk before checking its size, so it consumes and temporarily holds up to 64 KiB beyond `max_response_size`, exceeding the advertised read limit and memory bound.

Limit each read to the remaining bytes allowed by `max_size` before appending it.
</issue_to_address>

Linked issues

#439 fix: bound memory of FULL responses · 0 of 1 met

# Requirement Status Notes
1 Bound memory use of FULL pages and large responses so chart defaults hold, and document the limits. 🟡 Partly met The change bounds and documents backend responses, but FULL pages are still limited by task count rather than page bytes.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and a backend may accept a task before its oversized response is rejected, leaving proTES with an unknown outcome and the remote task potentially running without a local task ID. Reverting restores the old limit for future requests, but does not undo or identify a task already submitted this way; the error is logged.

Blocking findings: docs/configuration.md:119, pro_tes/ga4gh/tes/backends.py:1003, pro_tes/ga4gh/tes/backends.py:1003, pro_tes/ga4gh/tes/backends.py:1120, pro_tes/ga4gh/tes/backends.py:1148


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread docs/configuration.md Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Leave the bodies of redirects that requests follows unread, so that
they neither accumulate in the history of a response nor keep a request
beyond its timeout. Ask each read for at most the rest of the limit plus
one byte, so that no more than that is read of a response.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit b423d7c into dev Nov 7, 2026
42 of 50 checks passed
@uniqueg
uniqueg deleted the fix/response-size-limit branch November 7, 2026 06:07
@uniqueg uniqueg mentioned this pull request Nov 7, 2026
6 tasks done
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.

fix: bound memory of FULL responses

1 participant