Repository navigation
fix: submit tasks to backends exactly once - #282
Conversation
Create and cancel tasks with a single POST to <url>/ga4gh/tes/v1, instead of py-tes's fallback over several base paths, which could send a task to a backend more than once. Fail over to the next backend only if the backend certainly did not accept the task: no connection (refused, unresolved, connect timeout, certificate rejected), no credentials, or a status other than 2xx and 5xx. Read timeouts, connections lost after sending, 5xx responses and 2xx responses without an identifier leave the outcome unknown (BackendOutcomeUnknown, 502): the task is stored as SYSTEM_ERROR with its backend and not sent elsewhere. Replace the unused custom.controllers.post_task.timeout with custom.tes.timeout (default 30 seconds instead of a hard-coded 5), used by the app and the Celery worker. Closes #274 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes:
- POST requests never follow redirects, so that the GET of a redirect
(e.g., to the login page of an authentication gateway) is not taken
for a confirmation; redirects are rejections.
- Connecting times out after 5 seconds at most, and the default
timeout is 15 seconds, below Gunicorn's graceful timeout of the chart.
- GET /tasks/{id} goes to the API path only, with a quoted identifier.
- Requests that could not be prepared (e.g., invalid headers) count as
not sent.
- Tests of cancel errors at the API, of real redirects and refused
connections (allowing loopback connections in these tests).
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: after a backend accepted a task, any error of getting it (e.g., an unknown state) is logged, and the task is stored with its backend and tracked, instead of failing with 500 (which clients could retry, creating the task twice). Docs: TLS and proxy failures stop the failover; size the timeout by the read timeout of a reverse proxy. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR prevents duplicate TES task creation or cancellation by replacing py-tes retries and path fallbacks with single canonical requests, conservatively stopping failover whenever a backend may have processed a request, and preserving backend ownership for accepted tasks. It also adds configurable backend timeouts, maps uncertain outcomes to 502, updates documentation and dependencies, and provides extensive regression coverage. Sequence diagram for exactly-once TES task submissionsequenceDiagram
participant Client
participant proTES
participant BackendA
participant BackendB
Client->>proTES: POST /tasks
proTES->>BackendA: POST /ga4gh/tes/v1/tasks
alt 2xx with task identifier
BackendA-->>proTES: Success and identifier
proTES-->>Client: 200 task accepted
else Certainly not accepted
BackendA-->>proTES: Connection refusal, preparation error, or non-2xx/5xx
proTES->>BackendB: POST /ga4gh/tes/v1/tasks
BackendB-->>proTES: Success and identifier
proTES-->>Client: 200 task accepted
else Outcome unknown
BackendA-->>proTES: Timeout, lost connection, 5xx, or missing identifier
proTES-->>Client: 502 Bad Gateway
end
Sequence diagram for accepted TES task trackingsequenceDiagram
participant proTES
participant TES
participant Celery
participant Database
proTES->>TES: POST /ga4gh/tes/v1/tasks
TES-->>proTES: 2xx and remote task identifier
proTES->>Database: Store backend and task identifier
proTES->>TES: GET /ga4gh/tes/v1/tasks/{quoted_id}
alt State retrieval succeeds
TES-->>proTES: Task state
proTES->>Database: Store current state
else State retrieval fails or state is invalid
TES-->>proTES: Error or unknown state
proTES->>Database: Keep backend and track task
end
Celery->>TES: Poll task state
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± api/index.html± configuration/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 #282 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 28 28
Lines 2092 2159 +67
=========================================
+ Hits 2092 2159 +67 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
# Conflicts: # pro_tes/config_models.py
There was a problem hiding this comment.
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/backends.py" line_range="577" />
<code_context>
(unless allowed).
"""
kwargs: dict[str, Any] = super()._request_params(data=data, params=params)
+ kwargs["timeout"] = (min(CONNECT_TIMEOUT, self.timeout), self.timeout)
config = get_custom_config().tes
if isinstance(self.backend, DiscoveredBackend):
</code_context>
<issue_to_address>
**Retries create duplicate tasks**
When DNS resolution stalls or a backend keeps sending response bytes before each read timeout expires, the timeout tuple limits connection and read-inactivity waits, not total request duration, so the request can outlast the reverse proxy timeout and a client retry can create the task again.
Enforce an overall wall-clock deadline for the request.
</issue_to_address>
### Comment 2
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="275" />
<code_context>
task_converted: TesTask = task_model_converter.convert_task()
db_document.task.state = task_converted.state
- except (requests.RequestException, BackendAuthError) as exc:
+ except Exception as exc:
+ # the task is stored with its backend and tracked anyway, also
+ # if its backend serves it invalid (e.g., with an unknown state)
</code_context>
<issue_to_address>
**Invalid state leaves task stuck**
When a backend returns a state not defined by `TesState`, the broad catch lets task creation proceed and enqueues tracking; the worker’s `update_task_state` rejects the invalid state and exits, leaving the stored task in `INITIALIZING`.
Reject invalid backend states before enqueueing tracking and mark the task failed.
</issue_to_address>
### Comment 3
<location path="pro_tes/ga4gh/tes/backends.py" line_range="486" />
<code_context>
+ kwargs = self._request_params(params={"view": view})
+ timeout = kwargs.pop("timeout")
+ url = f"{self.url}/{API_PATH}/tasks/{quote(task_id, safe='')}"
+ response = requests.get(url, timeout=timeout, **kwargs)
+ response.raise_for_status()
+ task: tes.Task = unmarshal(response.json(), tes.Task)
</code_context>
<issue_to_address>
**Dot identifiers alter request paths**
When a TES backend assigns the valid opaque task identifier `.` or `..` and an intermediary or server normalizes dot segments, `quote(task_id, safe='')` leaves `.` and `..` unescaped, so a backend task ID of `..` produces a dot-segment URL. A proxy or server that normalizes dot segments sends the GET or cancel request to a different path, leaving the task untrackable or uncancelable.
Encode dot-only identifiers so they cannot become path dot segments, or reject such identifiers and classify creation as outcome unknown.
Also at `pro_tes/ga4gh/tes/backends.py:505`.
</issue_to_address>
### Comment 4
<location path="docs/api.md" line_range="80-81" />
<code_context>
-if a task could not be forwarded or no middleware could be applied. The
+limit](configuration.md#request-size-limit), `500 Internal Server Error`
+if a task could not be forwarded or no middleware could be applied, and
+`502 Bad Gateway` if a TES instance did not confirm a request to create or
+cancel a task, which it may have processed (see [Tasks](#tasks)). The
mapping of exceptions to problem details is
`exceptions` in
</code_context>
<issue_to_address>
**OpenAPI omits the new 502 response**
When a client is generated from the published OpenAPI document, the published TES OpenAPI operations still declare only `200` for `CreateTask` and `CancelTask`, so generated clients consuming that contract do not see the newly documented `502 Bad Gateway` outcome for requests the backend may have processed.
Add the `502` problem-details response to the `CreateTask` and `CancelTask` OpenAPI operations, or document the error through a shared default response.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 4 findings to address first, and if a request is misclassified as definitely unsent after a TES backend has accepted it, proTES may submit the task elsewhere and cause duplicate executions; if its outcome is unknown, the backend task may run without a remote ID for proTES to track or cancel. Those executions and any effects they cause can outlive a revert.
Blocking findings: pro_tes/ga4gh/tes/backends.py:577, pro_tes/ga4gh/tes/task_runs.py:275, pro_tes/ga4gh/tes/backends.py:486, docs/api.md:81
Sourcery review: the identifiers . and .. are percent-encoded too, so that they cannot become dot segments of request paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
proTES no longer sends a task to TES backends more than once (pre-release review of v0.3.0, finding 1, plus the timeout part of finding 9):
One POST each.
TesClientcreates and cancels tasks with a singlePOSTeach, to<url>/ga4gh/tes/v1, without following redirects. It overrides py-tes 1.1.4, which also tried/v1and/after anyRequestException, 404 or 5xx.GET /tasks/{id}goes to the same path only, and remote identifiers are quoted in paths.Fail over only when the task was certainly not accepted:
not_sentwalks the cause chain ofrequestsandurllib3)Outcome unknown. These cases raise
BackendOutcomeUnknown, which maps to 502:The task is stored as
SYSTEM_ERRORwith the backend that may run it, and is not sent elsewhere. A cancel request with such an error leaves the task unchanged.Accepted tasks are always tracked. Once a backend has accepted a task, any error while getting its state (e.g., an unknown state) is logged. The task is still stored with its backend and tracked, instead of failing with a 500.
Timeouts.
custom.tes.timeout(default 15 seconds, was a hard-coded 5) replaces the deadcustom.controllers.post_task.timeout. Connecting times out after at most 5 seconds. The app and the Celery worker both use these timeouts.Docs:
docs/configuration.md,docs/api.md(502),docs/upgrading.mdandpro_tes/config.yaml.Dependency:
urllib3>=2,<3is now a direct dependency, because its exception classes are imported.Verification
pre-commit run --all-files: passedcoverage run -m pytest(mongomock): 859 passed, 81 skipped (helm chart tests, helm not installed locally);coverage report: 100%MONGODB_TEST_URI=... pytestagainst MongoDB 7.0 (before the last review fix): 858 passed, 81 skippedmkdocs build --strict: passedrequestsraises themPOST /tasksand of cancelnot_sentagainst real sockets: refused, DNS, unreachable, certificate failure, reset after receipt, read timeout, truncated body, TLS EOF. The fixed findings: redirects of POSTs were followed for configured backends, the connect timeout was too long, GETs still used the path fallback, a 500 was returned after acceptance when the follow-up GET failed, the timeout guidance in the docs was misleading, and several test and docstring gaps.Also fixed after Sourcery's review: the remote identifiers
.and..are percent-encoded, so they can't become dot segments of paths.Declined review findings
requestshas none, and adding one would change all requests to backends. Backends are trusted, and the timeouts are bounded by phase and documented.docs/api.md.monkeypatchfor the timeout intest_client_timeout. The config belongs to a function-scoped app fixture, so it doesn't leak into other tests.Open questions
None.
Closes #274
🤖 Generated with Claude Code