Repository navigation
refactor!: pass tasks to middlewares, not requests - #320
Conversation
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]>
Reviewer's GuideThis 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 creationsequenceDiagram
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
Flow diagram for isolated middleware alternativesflowchart 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]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Documentation build overview
4 files changed± development/index.html± middlewares/index.html± reference/index.html± upgrading/index.html |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
Breaking change for custom middlewares. Middlewares now get and return the task as a plain dict instead of the
flask.RequestofPOST /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 inserver.pyread the request;TaskRunsgets 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 andTaskRuns._apply_middlewares().framework-free-tasks, on the syntax tree, including aliased and comma-separated imports) keeps Flask, Werkzeug, Connexion and Starlette imports out oftask_runs.py,pro_tes/middleware/andpro_tes/plugins/; its scope is documented indocs/development.md.tes_urls; nothing is stored.docs/upgrading.mdhas 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 globalflask.requestare ignored).Verification
Run locally after the last commit:
mkdocs build --strict: passedTwo 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
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:
Documentation:
Tests: