Skip to content

fix: submit tasks to backends exactly once - #282

Merged
uniqueg merged 6 commits into
devfrom
fix/submit-once
Oct 24, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/submit-once

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

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. TesClient creates and cancels tasks with a single POST each, to <url>/ga4gh/tes/v1, without following redirects. It overrides py-tes 1.1.4, which also tried /v1 and / after any RequestException, 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:

    • no connection: refused, host not resolved, connect timeout, or certificate rejected (not_sent walks the cause chain of requests and urllib3)
    • the request could not be prepared
    • no credentials
    • a status other than 2xx and 5xx, including redirects
  • Outcome unknown. These cases raise BackendOutcomeUnknown, which maps to 502:

    • read timeouts
    • connections lost after sending
    • other TLS and proxy failures
    • 5xx responses
    • 2xx responses without an identifier

    The task is stored as SYSTEM_ERROR with 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 dead custom.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.md and pro_tes/config.yaml.

  • Dependency: urllib3>=2,<3 is now a direct dependency, because its exception classes are imported.

Verification

  • pre-commit run --all-files: passed
  • coverage run -m pytest (mongomock): 859 passed, 81 skipped (helm chart tests, helm not installed locally); coverage report: 100%
  • MONGODB_TEST_URI=... pytest against MongoDB 7.0 (before the last review fix): 858 passed, 81 skipped
  • mkdocs build --strict: passed
  • New tests:
    • single requests, quoted paths and timeouts
    • each status class, for create and cancel
    • not-sent and maybe-received errors, built as requests raises them
    • a real local server that redirects POSTs: no GET follows
    • a real refused connection
    • the 502 path of POST /tasks and of cancel
    • tasks served with invalid states
  • Reviewer subagents: two rounds. The adversarial reviewer also checked not_sent against 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

  • Classify TLS and proxy failures by phase. These failures happen before sending, so failover would be safe, but telling them apart needs a custom transport adapter. They stay "outcome unknown", which is conservative, and the docs say that they stop the failover.
  • Persist the remote identifier before getting the task's state. This narrows the window in which an instance shutdown loses an accepted task. It is done in the PR for fix: store and cancel new tasks at backends #275, which reworks the same code path.
  • Sourcery: an overall wall-clock deadline for requests. requests has none, and adding one would change all requests to backends. Backends are trusted, and the timeouts are bounded by phase and documented.
  • Sourcery: mark tasks with invalid backend states as failed at creation. That would make accepted, running tasks uncancelable. How the worker handles unknown states is added to fix: keep stored task states when tracking starts #283 (tracker redesign).
  • Sourcery: declare the 502 in the OpenAPI spec. The vendored TES spec declares none of proTES's error responses; they are documented in docs/api.md.
  • Use monkeypatch for the timeout in test_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

uniqueg and others added 3 commits October 24, 2026 02:10
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 submission

sequenceDiagram
    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
Loading

Sequence diagram for accepted TES task tracking

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Reworked TES client requests to ensure create and cancel operations are sent exactly once with conservative outcome classification.
  • Use only the canonical /ga4gh/tes/v1 endpoint and disable POST redirects.
  • Quote remote task IDs in GET and cancel URLs.
  • Classify connection/preparation failures as safe to fail over, while treating timeouts, 5xx responses, and other potentially processed requests as outcome-unknown.
pro_tes/ga4gh/tes/backends.py
pro_tes/exceptions.py
pyproject.toml
Changed task lifecycle handling to preserve accepted-task ownership and prevent duplicate submissions when backend outcomes are uncertain.
  • Store outcome-unknown tasks as SYSTEM_ERROR with the potentially responsible backend and return 502.
  • Do not fail or discard accepted tasks when initial state retrieval returns an error or invalid state; continue tracking them.
  • Leave task state unchanged when cancellation outcome is unknown.
pro_tes/ga4gh/tes/task_runs.py
tests/ga4gh/tes/test_server.py
Introduced configurable backend request timeouts with a five-second connection limit.
  • Replace the ineffective controller timeout settings with custom.tes.timeout, defaulting to 15 seconds.
  • Apply connect and read timeouts consistently to application and worker backend requests.
pro_tes/config_models.py
pro_tes/config.yaml
pro_tes/ga4gh/tes/backends.py
docs/configuration.md
docs/upgrading.md
Documented the new submission, failover, error, and timeout semantics and added comprehensive regression coverage.
  • Document 502 responses and migration requirements for canonical backend paths and timeout configuration.
  • Test request uniqueness, redirects, URL quoting, status classes, uncertain network outcomes, timeout behavior, and accepted-task tracking.
docs/api.md
docs/configuration.md
docs/upgrading.md
tests/ga4gh/tes/test_backends.py
tests/ga4gh/tes/test_discovery.py

Assessment against linked issues

Issue Objective Addressed Explanation
#274 Submit create and cancel POSTs exactly once to the configured backend’s canonical TES API path, without py-tes path fallback or redirect following, and fail over only when the backend certainly did not accept the request. ✅
#274 Treat potentially processed requests as outcome-unknown: do not fail over, persist create failures as SYSTEM_ERROR with the possible backend, return an error, and leave task state unchanged when cancellation is uncertain. ✅
#274 Replace the unused post-task timeout with a configurable TES backend timeout used by the app and Celery worker, and document the behavior and configuration migration. ✅

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 #35370163 | 📁 Comparing f36bd01 against latest (716cbfb)

  🔍 Preview build  

4 files changed
± api/index.html
± configuration/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 (eb78777) to head (f36bd01).

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.
📢 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 01:28

@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/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 is free for open source - if you like our reviews please consider sharing them ✨

Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/ga4gh/tes/backends.py Resolved
Comment thread docs/api.md Resolved
uniqueg and others added 2 commits October 24, 2026 03:38
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]>
@uniqueg
uniqueg merged commit fc39975 into dev Oct 24, 2026
19 checks passed
@uniqueg
uniqueg deleted the fix/submit-once branch October 24, 2026 01:47
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: submit tasks to backends exactly once

1 participant