Skip to content

refactor!: pass tasks to middlewares, not requests - #320

Merged
uniqueg merged 12 commits into
devfrom
refactor/task-middlewares
Oct 24, 2026
Merged

uniqueg merged 12 commits into
devfrom
refactor/task-middlewares

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Breaking change for custom middlewares. Middlewares now get and return the task as a plain dict instead of the flask.Request of POST /tasks, and each alternative of a step works on its own copy: only a successful alternative's result is kept, so failed alternatives leave no changes (this replaces the snapshot-and-restore of #313). Only the controllers in server.py read the request; TaskRuns gets the task and the request path as plain data. That keeps task processing free of Flask, so the later move to Connexion 3 without Flask (#188) and the FOCA plugin engine (#194) only replace the controller glue and TaskRuns._apply_middlewares().

  • A new ast-grep rule (framework-free-tasks, on the syntax tree, including aliased and comma-separated imports) keeps Flask, Werkzeug, Connexion and Starlette imports out of task_runs.py, pro_tes/middleware/ and pro_tes/plugins/; its scope is documented in docs/development.md.
  • The request fails with 500 ("Middleware could not be applied.") if no middleware leaves a list of URL strings in tes_urls; nothing is stored.
  • docs/upgrading.md has a new "Custom middlewares" section: the new signature, the copy per alternative, non-dict results failing the middleware, _set_tes_urls(task=), and that old-style middlewares usually fail only at runtime (changes made through the global flask.request are ignored).
  • Auth, ownership, credential stripping and the inline-content limit run as before (before the middlewares on a copy, and again on their result).

Verification

Run locally after the last commit:

  • ruff, ruff format, mypy, ast-grep and its rule tests, semgrep: passed
  • pytest: 1045 passed, 80 skipped (chart and real-MongoDB tests), 100% coverage; new client-level tests check the controller wiring (request path → collection and owner policies, also under another base path; missing body → 400)
  • mkdocs build --strict: passed

Two review rounds with the adversarial and quality reviewer subagents. Round 1: two medium findings (upgrade notes for the breaking change; untested controller wiring) and several lows, all fixed. Round 2: no high or medium findings; the lows (wording of the upgrade notes, a test that couldn't tell the request path from the default base path, a docs claim about Connexion 3) are fixed.

Not run locally: the Docker Compose smoke test and the MongoDB 7.0 CI entry.

Declined review findings

  • An extra deep copy of the task per alternative (on top of the copy before the middlewares): accepted for simplicity and correctness; the cost is small.

Open questions

None.

Closes #315

🤖 Generated with Claude Code

Summary by Sourcery

Adopt framework-independent task dictionaries throughout middleware processing and isolate request handling in the controllers.

Enhancements:

  • Refactor task processing and custom middleware execution to use framework-independent task dictionaries, with each fallback alternative isolated to its own copy.
  • Move request-specific data handling into the controllers and pass task payloads and collection paths explicitly to TaskRuns.
  • Reject middleware results that do not select a valid list of TES backend URLs before persisting the task.

Documentation:

  • Document the framework-free middleware contract, fallback behavior, failure modes, and upgrade guidance for existing custom middlewares.
  • Add development guidance and static checks preventing web-framework imports from task processing, middleware, and plugin code.

Tests:

  • Update middleware, task-processing, and controller tests to cover isolated alternatives, invalid backend selection, unchanged input tasks, request-path propagation, and missing request bodies.

uniqueg and others added 11 commits October 24, 2026 23:59
Alternatives of a middleware step shared one mutable request: an
alternative that changed the JSON body and then raised left its partial
changes for the next alternative. The handler now copies the body
before each step and restores it, in place, after each failed
alternative, so every alternative starts from the body as it was before
the step.

The middleware interface is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The task distribution middlewares removed duplicate backends with
`set()`, which loses the order of `custom.tes.service_list` and the
discovered backends; with hash randomization, the order even differed
between processes. They now keep the first occurrence of each backend,
in order: the base class forwards in the configured order, the
distance-based middleware keeps that order for backends at the same
distance, and the random order depends on the random state only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Middlewares got the `flask.Request` of `POST /tasks` and changed its
JSON body. They now get the task, as a `dict`, and return it:
`AbstractMiddleware.apply_middleware(task) -> task`. Each alternative
gets its own copy of the task, which is kept only if it succeeds;
alternatives that return no task fail, too.

The task processing no longer reads the request: the controllers of
`POST /tasks` and `GET /tasks` pass the task (Connexion's `body`) and
the request path to `TaskRuns`, which has no Flask import any more,
and doesn't change the task of the request. The middlewares are applied
behind one method, `TaskRuns._apply_middlewares()`, which returns the
task and the TES backends to try; it is the seam that the FOCA plugin
engine replaces. An ast-grep rule keeps Flask, Werkzeug, Connexion and
Starlette out of the task processing and the middlewares, so they run
unchanged after the move to Connexion 3 without Flask.

BREAKING CHANGE: custom middlewares implement
`apply_middleware(task: dict) -> dict` instead of taking and returning
a `flask.Request`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ports the order tests of the base class and the random middleware to
the task interface.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Take the snapshot of the body only for steps with more than one
alternative, and skip the restore after the last one. The docs say
that only the JSON body is restored, not other request state or a
replaced body.

Refs #313

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The test of the reproducible random order compares with the literal
order for `random.seed(1)`, so it fails with the old `set()`-based
order, which depends on the hash seed.

Refs #314

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keeps the copy semantics of the task interface; the restore of request
bodies is not needed with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Ports the pinned random order test to the task interface.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses the review of #315:

- upgrading notes: custom middlewares get and return the task, each
  alternative gets a copy, non-dict results fail, `_set_tes_urls()`
  takes `task=`, and old-style middlewares fail only at runtime;
- the request fails if no middleware leaves a list of URL strings in
  `tes_urls` (docs and `create_task()` docstring);
- tests of the controller wiring: the task and the request path reach
  `TaskRuns`, the owner policies are on the request path, and missing
  bodies give `400`;
- the ast-grep rule `framework-free-tasks` matches the syntax tree, so
  it finds aliased imports and lists of modules, too; its scope is
  described in the development docs.

Refs #315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Addresses round 2 of the review of #315: old-style middlewares usually
fail, and changes through the global `flask.request` are ignored; the
client gets the mapped detail, the log the reason. The development
docs no longer claim that the task processing is unaffected by the
move to Connexion 3 (it raises Connexion's and Werkzeug's exceptions).
A test calls the controllers under another request path.

Refs #315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in #317, #318 and #319. Keeps the copy-per-alternative
semantics of the task interface (no body restore) and the ported
tests of #313 and #314; the auto-merge had re-added the old restore
code and the old-style order tests, which are dropped.

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

This breaking refactor moves middleware and task processing from Flask request objects to plain task dictionaries, with controllers supplying request-derived data, isolated fallback alternatives, strict TES backend selection validation, framework-import enforcement, and migration documentation/tests.

Sequence diagram for framework-free task creation

sequenceDiagram
    participant Client
    participant Controller as CreateTask
    participant TaskRuns
    participant MiddlewareHandler
    participant Middleware
    participant Store

    Client->>Controller: POST /tasks with body
    Controller->>TaskRuns: create_task(task, collection)
    TaskRuns->>MiddlewareHandler: apply_middlewares(task)
    MiddlewareHandler->>Middleware: apply_middleware(task copy)
    Middleware-->>MiddlewareHandler: modified task
    MiddlewareHandler-->>TaskRuns: task with tes_urls
    TaskRuns->>Store: store task and forward to selected TES backends
    Store-->>Controller: task response
    Controller-->>Client: response
Loading

Flow diagram for isolated middleware alternatives

flowchart TD
    A[Task before middleware step] --> B{Try alternative}
    B --> C["apply_middleware(task copy)"]
    C -->|returns dict| D[Keep alternative result]
    C -->|raises or returns non-dict| E[Discard copy]
    E --> B
    D --> F{Next middleware step}
    B -->|all alternatives fail| G[MiddlewareException]
    F --> H[Validate tes_urls]
    H -->|list of URL strings| I[Continue task creation]
    H -->|missing or invalid| J[Fail with 500; store nothing]
Loading

File-Level Changes

Change Details Files
Decouple task processing and middleware execution from Flask request objects by passing plain task dictionaries and request paths from controllers.
  • Move request-body extraction and path propagation into the task controllers.
  • Update TaskRuns creation/listing and ownership-policy calls to consume plain data.
  • Convert middleware interfaces and built-in task-distribution implementations to task dictionaries.
  • Preserve request validation, credential handling, ownership, and inline-content checks around middleware processing.
pro_tes/ga4gh/tes/server.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/middleware/abstract_middleware.py
pro_tes/middleware/middleware_handler.py
pro_tes/plugins/middlewares/task_distribution/task_distribution/base.py
pro_tes/plugins/middlewares/task_distribution/distance.py
pro_tes/plugins/middlewares/task_distribution/random.py
Make middleware alternatives isolated and strictly validate successful task/backend selection results.
  • Deep-copy the task for every middleware alternative and retain only successful results.
  • Treat exceptions and non-dict middleware returns as failed alternatives.
  • Require tes_urls to be a list of strings and reject task creation without valid backend selection.
  • Avoid persisting or forwarding tasks when middleware processing fails.
pro_tes/middleware/middleware_handler.py
pro_tes/ga4gh/tes/task_runs.py
tests/middleware/test_middleware_handler.py
tests/ga4gh/tes/test_server.py
Enforce and document the framework-free processing boundary and the breaking middleware API.
  • Add ast-grep coverage preventing Flask, Werkzeug, Connexion, and Starlette imports in task-processing and middleware modules, including aliases and grouped imports.
  • Document the new middleware signature, copy semantics, failure behavior, and migration details.
  • Update middleware and distribution tests to use plain task dictionaries.
  • Add controller-level tests for request-path propagation, missing bodies, isolation, and invalid TES URL selection.
.ast-grep/rules/framework-free-tasks.yml
.ast-grep/rule-tests/framework-free-tasks-test.yml
docs/development.md
docs/middlewares.md
docs/upgrading.md
tests/ga4gh/tes/test_access_control.py
tests/ga4gh/tes/test_server.py
tests/plugins/middlewares/task_distribution/test_distance.py
tests/plugins/middlewares/task_distribution/test_random.py

Assessment against linked issues

Issue Objective Addressed Explanation
#315 Change middleware processing to accept and return plain task dictionaries, giving each alternative an isolated deep copy and discarding failed or non-dict results. ✅
#315 Keep request access in the controllers: pass the task body and request path into task processing, which must work on a copy and remain free of Flask and other web-framework imports. ✅
#315 Provide the middleware-application seam and fail task creation with a 500 if middleware processing does not produce TES backend URLs; document and test the new interface and framework-free boundary. ✅

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 #35385114 | 📁 Comparing 7168ace against latest (ec9a510)

  🔍 Preview build  

4 files changed
± development/index.html
± middlewares/index.html
± reference/index.html
± upgrading/index.html

@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 (ec9a510) to head (7168ace).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #320   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         2479      2470    -9     
=========================================
- Hits          2479      2470    -9     

☔ 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 October 24, 2026 23:25

@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 2 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="534-537" />
<code_context>
+        logger.debug("Middlewares registered: %s", mw_handler.middlewares)
+        payload = mw_handler.apply_middlewares(task=task)
+        tes_urls = payload.pop("tes_urls", None)
+        if not isinstance(tes_urls, list) or not all(
+            isinstance(url, str) for url in tes_urls
+        ):
+            raise MiddlewareException("Middlewares selected no TES backends")
+        return payload, tes_urls
+
</code_context>
<issue_to_address>
**Empty selections report wrong failure**

When a middleware returns `tes_urls=[]`, `all(...)` accepts the empty list, so `_apply_middlewares()` returns it and `create_task()` skips the backend loop, then raises `NoTesInstancesAvailable` instead of `MiddlewareException`; if cleanup fails, the created task remains marked `SYSTEM_ERROR`.

Reject an empty `tes_urls` list in `_apply_middlewares()` and raise `MiddlewareException` before task creation.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="103-104" />
<code_context>
         self.store_logs = self.custom_config.storeLogs.execution_trace

-    def create_task(self, **kwargs: Any) -> dict[str, Any]:
+    def create_task(
+        self, task: dict[str, Any] | None, collection: str, **kwargs: Any
+    ) -> dict[str, Any]:
         """Start task.
</code_context>
<issue_to_address>
**Direct task-processing callers break**

When a consumer calls the documented `TaskRuns` methods using their previous signatures, external callers of the documented `TaskRuns` methods that still call `create_task(**kwargs)` or `list_tasks(**kwargs)` now get `TypeError` because `task` and `collection` are required arguments. The upgrade notes describe the custom-middleware break but not this direct Python API break.

Document the `TaskRuns` signature migration in the upgrade notes, or preserve a compatible public entry point if direct callers are supported.

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

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and the middleware-selected tes_urls determine which TES backend receives the task, including its task data. If the new task-based middleware flow selects an unintended backend, the task may already have been forwarded or executed before a revert; reverting cannot undo that disclosure or submission.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:537, pro_tes/ga4gh/tes/task_runs.py:104


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
Middlewares that select an empty list of TES backends (e.g., as none
are configured or discovered) now fail the request before the task is
stored, with the error that `dev` gives for this case
(`NoTesInstancesAvailable`, `500`, "No TES instance accepted the
task."), instead of storing the task and discarding it afterwards. The
upgrading notes describe the new arguments of `TaskRuns.create_task()`
and `list_tasks()` for code that calls them directly.

Refs #315

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 296e8f8 into dev Oct 24, 2026
19 checks passed
@uniqueg
uniqueg deleted the refactor/task-middlewares branch October 24, 2026 23:38
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.

refactor!: pass tasks to middlewares, not requests

1 participant