Skip to content

fix: store and cancel new tasks at backends - #291

Merged
uniqueg merged 8 commits into
devfrom
fix/cancel-new-tasks
Oct 24, 2026
Merged

uniqueg merged 8 commits into
devfrom
fix/cancel-new-tasks

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #275.

  • New tasks are stored with their TES endpoint and remote identifier first. The state that the TES instance reports is stored afterwards, and only if the task is still UNKNOWN, through the new conditional DbDocumentConnector.update_task_state(state, if_state=None) -> bool. Requests that cancel a task while it is being forwarded therefore win: the task stays CANCELED.
  • When stored forwards are written, the task's state is left out, so a cancel between the two writes is not overwritten.
  • Tasks in state UNKNOWN are now canceled at their TES instance too (States.TO_CANCEL); before, the request returned 200 without effect.
  • Unfinished tasks without a remote identifier can't be canceled: the request returns 409 Conflict (TaskNotCancelable; was 500). Such tasks are read once more before the cancel is refused, in case forwarding has stored the identifier in the meantime.
  • Docs: docs/api.md (cancel row, forwarding steps, errors) and docs/upgrading.md.

How it was verified

  • coverage run -m pytest after merging dev (which includes fix: track tasks by rescheduled polls #288): 928 passed, 81 skipped (the MongoDB-only tests); coverage 100%.
  • pre-commit run --all-files: all hooks passed (ruff, mypy, and so on).
  • mkdocs build --strict: OK.
  • Mutation check: with the state written back when forwards are stored, the new test_forward_state_changed_while_stored fails.
  • Reviews: adversarial and quality reviewers, two rounds, then Sourcery. The fixed findings are in the commits.
  • CI: passed on the first push (15 checks; the image push and publish jobs skipped as expected).

Declined review findings

  • The Celery tracker sets INITIALIZING unconditionally when it starts (adversarial reviewer, medium). Deferred to fix: keep stored task states when tracking starts #283, which covers the tracker (pro_tes/tasks/track_task_progress.py). The redesigned tracker from fix: track tasks by rescheduled polls #288 no longer does this and keeps CANCELED. The conditional update_task_state(..., if_state=...) added here is available for it.
  • Return 409 when canceling SYSTEM_ERROR tasks without a remote identifier (Sourcery). SYSTEM_ERROR is final, and canceling finished tasks has no effect. The 502 at creation already tells the client that proTES can neither track nor cancel the task (docs/api.md, step 3).
  • Fail creation if the state write after forwarding fails (Sourcery). The TES instance has already accepted the task, and its backend and remote identifier are stored. Failing the request would make clients resubmit the task, so it would run twice. The state stays UNKNOWN until the tracker's first poll, and the error is logged.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits October 24, 2026 02:45
Store the state that the backend reports when a task is forwarded:
_update_doc_in_db replaced the local document with the stored one, so
new tasks stayed UNKNOWN until the Celery worker tracked them.

Cancel tasks in state UNKNOWN at their backend too, instead of
returning 200 without effect. Unfinished tasks without an identifier at
their backend (e.g., while being forwarded) can't be canceled: 409
(TaskNotCancelable) instead of a ValueError (500).

Test cancelling right after creation, without setting the state.

Closes #275

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes:

- Store the backend state only if the task is still UNKNOWN, and do
  not write the state back with the forward, so that a cancel request
  in the meantime is kept (update_task_state(if_state=...)).
- Invalid states of the backend leave the task UNKNOWN, but stored
  with its backend (tracked, cancelable), instead of a 500.
- Name the group of states to cancel (States.TO_CANCEL); docs: the 409
  can be permanent.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Resolve the conflicts with #274, and store the forward (backend and
remote identifier) before getting the state of a new task, so that the
task is cancelable even if getting its state fails or the instance
stops; the state is then stored only if the task is still UNKNOWN.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also fix the upgrade note on canceling tasks in state UNKNOWN.

Part of #275

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 makes newly forwarded tasks reliably cancelable by persisting backend identity first, conditionally applying backend state so concurrent cancellation is preserved, supporting cancellation from UNKNOWN, and returning 409 when cancellation lacks a remote identifier; accompanying tests and documentation cover the new behavior.

Sequence diagram for race-safe task forwarding and cancellation

sequenceDiagram
    participant Client
    participant API as TaskRuns
    participant DB as DbDocumentConnector
    participant TES as TESBackend

    Client->>API: create_task()
    API->>TES: create task
    TES-->>API: remote_task_id
    API->>DB: _update_doc_in_db(tes_url, remote_task_id)
    DB-->>API: backend identity stored
    API->>TES: get_task(remote_task_id)
    TES-->>API: backend state
    API->>DB: update_task_state(state, if_state=UNKNOWN)
    DB-->>API: updated or rejected

    Client->>API: cancel_task(id)
    API->>DB: find task
    DB-->>API: task identity and state
    API->>TES: cancel_task(remote_task_id)
    TES-->>API: cancellation result
Loading

Flow diagram for cancellation eligibility and conflicts

flowchart TD
    A["cancel_task(id)"] --> B{Task state in TO_CANCEL?}
    B -->|No| C["Leave finished or already-canceling task unchanged"]
    B -->|Yes| D{Remote identifier available?}
    D -->|No| E["Raise TaskNotCancelable\n409 Conflict"]
    D -->|Yes| F["Cancel task at TES backend"]
Loading

File-Level Changes

Change Details Files
Make task forwarding persistence race-safe so cancellation wins over backend-reported state.
  • Persist the TES endpoint and remote task identifier before retrieving backend state.
  • Apply the backend state only through an atomic conditional update when the task remains UNKNOWN.
  • Exclude state from the later forwarded-task upsert so it cannot overwrite a concurrent cancellation.
pro_tes/ga4gh/tes/task_runs.py
pro_tes/utils/db.py
tests/ga4gh/tes/test_server.py
tests/utils/test_db.py
Expand cancellation handling for newly forwarded and not-yet-tracked tasks.
  • Treat UNKNOWN as cancelable and forward cancellation to the TES backend.
  • Return a typed 409 Conflict when an unfinished task lacks a remote identifier.
  • Define the TO_CANCEL state set and add coverage for unknown-state, missing-identifier, and race scenarios.
pro_tes/ga4gh/tes/states.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/exceptions.py
tests/ga4gh/tes/test_server.py
Document the revised forwarding and cancellation behavior and API errors.
  • Describe the two-stage persistence during forwarding and backend state initialization.
  • Document UNKNOWN-state cancellation and the 409 response for tasks without remote identifiers.
  • Add upgrade guidance for the changed cancellation semantics.
docs/api.md
docs/upgrading.md

Assessment against linked issues

Issue Objective Addressed Explanation
#275 Persist the state reported by the backend when a newly forwarded task is stored, rather than leaving it UNKNOWN until background tracking begins. ✅
#275 Cancel unfinished tasks at their backend even when their state is UNKNOWN, and return 409 when an unfinished task has no remote backend identifier. ✅
#275 Add regression coverage for cancelling immediately after task creation, without manually changing the task state. ✅

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

@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 (9e3ff28) to head (d6be51b).

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

☔ 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 02:23

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

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

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/states.py" line_range="47" />
<code_context>

+    # canceled at their backend on request: also tasks whose state is not
+    # known yet (e.g., not tracked yet)
+    TO_CANCEL: ClassVar[list[str]] = CANCELABLE + UNDEFINED
+
     ALL: ClassVar[list[str]] = UNDEFINED + DEFINED
</code_context>
<issue_to_address>
**Unknown backend tasks appear canceled successfully**

When forwarding raises `BackendOutcomeUnknown` and a caller tries to cancel the task, the task remains in `SYSTEM_ERROR` without a remote identifier, but `cancel_task` skips the `TO_CANCEL` branch and the missing-identifier check, then returns success without contacting the backend; the documented `409 Conflict` is not returned.

Route `SYSTEM_ERROR` tasks through the missing-identifier check so cancellation fails with `409 Conflict` when the remote identifier is unknown.

Also at `docs/api.md:80`.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="285" />
<code_context>
+                state = TesState(task_converted.state)
+                # unless a request to cancel the task changed it meanwhile
+                if db_connector.update_task_state(
+                    state=state.value, if_state=TesState.UNKNOWN.value
+                ):
+                    db_document.task.state = state
</code_context>
<issue_to_address>
**Database state-write failure is swallowed**

When the conditional MongoDB state update raises after the backend state was retrieved, `update_task_state` can raise on a database failure, but the surrounding `except Exception` treats it as a backend state-fetch failure and continues. `create_task` can therefore return success with the task still `UNKNOWN` and without confirming that its reported backend state was stored.

Handle backend retrieval/conversion exceptions separately from database-write exceptions, and propagate database failures instead of returning success.
</issue_to_address>

### Comment 3
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="458" />
<code_context>
-                raise ValueError(f"No remote identifier of task '{id}'")
+                # e.g., tasks that are being forwarded, or that a TES
+                # instance may have accepted without confirming it
+                raise TaskNotCancelable(
+                    f"Task '{id}' can't be canceled: its identifier at its TES"
+                    " instance is unknown"
</code_context>
<issue_to_address>
**Stale lookup rejects a cancel**

When the cancellation lookup runs just before forwarding stores the remote identifier, `cancel_task` uses its earlier database snapshot and raises `TaskNotCancelable` without checking again. If forwarding stores the remote identifier after that lookup, the cancellation request returns `409` even though the task is now cancelable, and it continues running unless the caller retries.

Before raising `TaskNotCancelable`, reread the task's endpoint and remote identifier and proceed with cancellation if forwarding has stored them.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and a cancel request for a task in UNKNOWN now reaches the TES backend when its remote identifier is known, so an incorrect state classification or backend response could terminate work and lose its outputs. Reverting stops future cancellations but cannot restore tasks already canceled.

Blocking findings: pro_tes/ga4gh/tes/states.py:47, pro_tes/ga4gh/tes/task_runs.py:285, pro_tes/ga4gh/tes/task_runs.py:458


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

Comment thread pro_tes/ga4gh/tes/states.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
uniqueg and others added 2 commits October 24, 2026 04:34
Forwarding may have stored the remote identifier since the task was
read.

Part of #275

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 810a3fb into dev Oct 24, 2026
19 checks passed
@uniqueg
uniqueg deleted the fix/cancel-new-tasks branch October 24, 2026 02:46
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: store and cancel new tasks at backends

1 participant