Skip to content

fix: bound task listings and stored task data - #292

Merged
uniqueg merged 7 commits into
devfrom
fix/bound-task-data
Oct 24, 2026
Merged

uniqueg merged 7 commits into
devfrom
fix/bound-task-data

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #284.

  • Full listings: pages of the view FULL have at most custom.controllers.list_tasks.max_page_size_full tasks (new, default 64). The cap also applies to the default page size. Listings iterate the cursor one document at a time instead of list(cursor). They no longer read task_original in the views BASIC and FULL, since only task is served.
  • Tasks that are not forwarded are not kept: tasks that fail validation by py-tes (400), and tasks that no TES instance accepts (500), are deleted, together with their owner's roles. Before, they were stored as SYSTEM_ERROR. Tasks that a TES instance may have accepted (502) are still kept as SYSTEM_ERROR. If the deletion fails, the error is logged, the task is marked SYSTEM_ERROR if possible, and the original error is returned.
  • Inline contents: the inline content of each input (inputs[].content) is limited to custom.controllers.post_task.max_inline_content (new, default 131072 bytes of UTF-8, i.e., 128 KiB, the minimum that the TES specification recommends per field). Larger tasks are rejected with 413 Content Too Large, before and after the middlewares. All contents together are bounded by server.max_content_length.
  • Docs:
    • Configuration: the new keys, the request size limit, and a new "Rate limits" section.
    • API: the forwarding steps and the errors.
    • Helm chart README: a recommendation to rate-limit at the ingress controller, with generic examples and no deployment values.
    • upgrading.md: the behaviour changes.

The follow-ups #285 (per-user task limit) and #286 (retention of finished tasks) are opt-in features for after the release.

How it was verified

  • coverage run -m pytest: 942 passed, 81 skipped; coverage 100%. test_server.py and test_access_control.py also passed against MongoDB 7.0 (MONGODB_TEST_URI).
  • pre-commit run --all-files: all hooks passed.
  • mkdocs build --strict: OK.
  • Mutation checks: without the task_original exclusion, the projection tests fail. With _sanitize_request outside the discarding try, test_create_task_unknown_field fails.
  • Reviews: adversarial reviewer (two rounds) and quality reviewer. All findings are fixed.

Declined review findings

  • Pass the config to _check_inline_content instead of a limit (quality, low). The static helper with an explicit limit is simpler to test and reads the config only once per request.
  • Limit the total of inline contents after the middlewares (Sourcery). The TES specification recommends supporting 128 KiB per field, so the limit applies per input. The total from clients is bounded by server.max_content_length. Middlewares are configured by the deployer and are trusted code.
  • Remove owner roles separately if the deletion succeeded (Sourcery). Roles left on deleted tasks give no access and keep the identifier from being reused (_write_doc_to_db). The SYSTEM_ERROR update on a deleted task has no effect.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits October 24, 2026 04:04
- Pages of the view FULL have at most
  custom.controllers.list_tasks.max_page_size_full tasks (default 64),
  and the cursor is processed document by document instead of being
  loaded as a list.
- Inline contents of inputs are limited to
  custom.controllers.post_task.max_inline_content bytes together
  (default 64 KiB), also those that middlewares add (413).
- Docs: rate limits at the proxy are recommended for production.

Part of #284

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tasks that fail validation after the middlewares, and tasks that no
TES instance accepts, are deleted with their owner's roles, instead of
being stored as SYSTEM_ERROR.

Part of #284

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also: don't read original tasks in listings, raise the default inline
content limit to the 128 KiB that the TES specification recommends,
keep the error of the request if a task can't be discarded, and
complete the docs of the new errors.

Part of #284

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The TES specification recommends supporting 128 KiB per content field;
all contents together are bounded by the request size limit. Also
don't claim in the error that tasks were not kept, as they are kept if
they can't be deleted.

Part of #284

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR bounds memory and storage growth by limiting FULL task listings and inline input content, streaming listing cursors, and removing tasks that are definitively not forwarded while preserving uncertain outcomes; configuration, error mapping, tests, and operational documentation are updated accordingly.

Sequence diagram for bounded task creation and forwarding

sequenceDiagram
    actor Client
    participant API as proTES
    participant Middleware
    participant TES as TES instance
    participant DB as Task database

    Client->>API: POST /tasks
    API->>API: _check_inline_content
    alt inline content exceeds limit
        API-->>Client: 413 Content Too Large
    else content is within limit
        API->>Middleware: Apply middlewares
        Middleware-->>API: Modified task
        API->>API: _check_inline_content
        alt modified task is too large or invalid
            API->>DB: _discard_task
            API-->>Client: 413 or 400
        else task is valid
            API->>TES: Forward task
            alt TES accepts
                TES-->>API: Accepted
                API-->>Client: Task identifier
            else TES may have accepted
                TES-->>API: Uncertain outcome
                API-->>Client: 502 Bad Gateway
            else no TES accepts
                API->>DB: _discard_task
                API-->>Client: 500 Internal Server Error
            end
        end
    end
Loading

Flow diagram for bounded FULL task listings

flowchart TD
    A[GET /tasks] --> B{view is FULL}
    B -->|yes| C[Limit page size to min max_page_size and max_page_size_full]
    B -->|no| D[Limit page size to max_page_size]
    C --> E[Query cursor with page_size plus one]
    D --> E
    E --> F[Iterate cursor one document at a time]
    F --> G[Return page and next_page_token]
Loading

File-Level Changes

Change Details Files
Bound full task listings and avoid loading original task payloads.
  • Add a configurable 64-task cap for FULL pages, including default page sizes.
  • Consume database cursors incrementally while generating pagination tokens.
  • Exclude task_original from task-list projections.
pro_tes/config_models.py
pro_tes/config.yaml
pro_tes/ga4gh/tes/task_runs.py
tests/ga4gh/tes/test_server.py
Stop retaining tasks that cannot be validated or forwarded.
  • Delete failed tasks and their ownership roles for validation failures and 500 forwarding failures.
  • Preserve SYSTEM_ERROR for uncertain 502 outcomes.
  • Log discard failures and fall back to SYSTEM_ERROR while returning the original error.
pro_tes/ga4gh/tes/task_runs.py
pro_tes/exceptions.py
tests/ga4gh/tes/test_access_control.py
tests/ga4gh/tes/test_server.py
Limit inline input content before and after middleware processing.
  • Add a configurable per-input UTF-8 byte limit with a 128 KiB default.
  • Return 413 for oversized content without relaying or retaining the task.
  • Continue enforcing the aggregate request body limit.
pro_tes/config_models.py
pro_tes/config.yaml
pro_tes/exceptions.py
pro_tes/ga4gh/tes/task_runs.py
tests/ga4gh/tes/test_server.py
Document the new task lifecycle, size limits, pagination behavior, and deployment guidance.
  • Update API and upgrade documentation for forwarding errors, discarded tasks, FULL pagination, and inline-content limits.
  • Document configuration keys and recommend ingress-level rate limiting.
  • Add Helm README guidance without prescribing deployment-specific values.
docs/api.md
docs/configuration.md
docs/upgrading.md
deployment/README.md

Assessment against linked issues

Issue Objective Addressed Explanation
#284 Bound memory use for FULL task listings with a configurable maximum page size, and process database results incrementally rather than loading the entire cursor. ✅
#284 Avoid retaining tasks that fail validation or are accepted by no backend, including removing their owner rules, while retaining tasks with an unknown backend outcome; document the behavior change. ✅
#284 Add a configurable limit for inline input content and document production rate-limiting recommendations at the ingress. ✅

Possibly linked issues


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 Oct 24, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35371431 | 📁 Comparing 2891315 against latest (810a3fb)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@uniqueg
uniqueg marked this pull request as ready for review October 24, 2026 03:32
@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (810a3fb) to head (2891315).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #292   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         2343      2372   +29     
=========================================
+ Hits          2343      2372   +29     

☔ 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.

@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 4 issues

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

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="897-902" />
<code_context>
+        if not isinstance(inputs, list):
+            return
+        size = max(
+            (
+                len(item["content"].encode("utf-8", errors="surrogatepass"))
+                for item in inputs
+                if isinstance(item, dict) and isinstance(item.get("content"), str)
+            ),
+            default=0,
+        )
+        if size > limit:
</code_context>
<issue_to_address>
**Middleware contents exceed size bound**

When middleware adds multiple inline contents that are each within the per-input limit but whose combined size exceeds the configured bound, `_check_inline_content` measures only the largest individual content, while the request-body limit applies before middleware processing. The transformed task therefore exceeds the intended aggregate bound and is stored and forwarded.

Change `_check_inline_content` to measure the aggregate size of inline contents and reject the transformed task when it exceeds the configured limit.

Also at `pro_tes/ga4gh/tes/task_runs.py:173`.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="598-601" />
<code_context>
+        """
+        try:
+            self.db_client.delete_one({"worker_id": db_document.worker_id})
+            remove_task_owner(
+                collection=collection, task_id=str(db_document.task.id), owner=owner
+            )
+        except Exception:
+            logger.exception("Task '%s' could not be discarded", db_document.task.id)
+            with suppress(Exception):
</code_context>
<issue_to_address>
**Owner roles remain after deletion**

When task deletion succeeds but revoking one or more owner roles fails, `remove_task_owner` raises after the task document has been deleted, so `_discard_task` attempts to mark a nonexistent document `SYSTEM_ERROR` and leaves remaining owner policy roles behind indefinitely.

Handle owner-role revocation independently of task deletion and skip the `SYSTEM_ERROR` update when the task document is already gone.
</issue_to_address>

### Comment 3
<location path="tests/ga4gh/tes/test_server.py" line_range="709-711" />
<code_context>
+    if accepted:
+        assert response.status_code == 200
+        return
+    assert response.status_code == 413
+    assert "inline content" in response.get_json()["detail"]
+    assert not relayed(backend)
+    assert mongo_client[DB]["tasks"].count_documents({}) == 0
+
+
+def test_create_task_inline_content_middleware(
</code_context>
<issue_to_address>
**Middleware rejection leaves task stored**

When the middleware adds oversized inline content, the test checks only the `413` response and that nothing was relayed; a broken path that leaves the already-inserted task in the database still passes.

Also assert that the task was not stored (and that its owner roles were removed).
</issue_to_address>

### Comment 4
<location path="tests/ga4gh/tes/test_server.py" line_range="1187" />
<code_context>
+    """Tasks that could not be forwarded are not kept, so users don't own them."""
     backend.failing.update(BACKENDS)
     response = client.post(f"{BASE_PATH}/tasks", json=TASK)
     assert response.status_code == 500
-    (task_id,) = list_ids(client, USER)
-    response = client.get(f"{BASE_PATH}/tasks/{task_id}")
</code_context>
<issue_to_address>
**Wrong server error still passes**

When task deletion fails after no TES instance accepts it, `test_create_task_not_discarded` checks only `response.status_code == 500`, so returning a different 500 problem instead of the original forwarding error passes; the database-state assertion does not distinguish the responses.

Assert that the response identifies the original no-instance-accepted error, not merely that its status is 500.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and when validation fails or no TES instance accepts a task, the new cleanup deletes the stored task record and its owner roles. Reverting stops future deletions but cannot restore records already removed; the loss is limited to tasks from those failed submissions.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:902, pro_tes/ga4gh/tes/task_runs.py:601, tests/ga4gh/tes/test_server.py:711, tests/ga4gh/tes/test_server.py:1187


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

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread tests/ga4gh/tes/test_server.py Resolved
Comment thread tests/ga4gh/tes/test_server.py Resolved
@uniqueg
uniqueg merged commit 28a49c6 into dev Oct 24, 2026
17 checks passed
@uniqueg
uniqueg deleted the fix/bound-task-data branch October 24, 2026 03:40
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 task listings and stored task data

1 participant