Repository navigation
fix: store and cancel new tasks at backends - #291
Conversation
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe 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 cancellationsequenceDiagram
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
Flow diagram for cancellation eligibility and conflictsflowchart 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"]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
Forwarding may have stored the remote identifier since the task was read. Part of #275 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #275.
UNKNOWN, through the new conditionalDbDocumentConnector.update_task_state(state, if_state=None) -> bool. Requests that cancel a task while it is being forwarded therefore win: the task staysCANCELED.stateis left out, so a cancel between the two writes is not overwritten.UNKNOWNare now canceled at their TES instance too (States.TO_CANCEL); before, the request returned200without effect.409 Conflict(TaskNotCancelable; was500). Such tasks are read once more before the cancel is refused, in case forwarding has stored the identifier in the meantime.docs/api.md(cancel row, forwarding steps, errors) anddocs/upgrading.md.How it was verified
coverage run -m pytestafter mergingdev(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.test_forward_state_changed_while_storedfails.Declined review findings
INITIALIZINGunconditionally 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 keepsCANCELED. The conditionalupdate_task_state(..., if_state=...)added here is available for it.409when cancelingSYSTEM_ERRORtasks without a remote identifier (Sourcery).SYSTEM_ERRORis final, and canceling finished tasks has no effect. The502at creation already tells the client that proTES can neither track nor cancel the task (docs/api.md, step 3).UNKNOWNuntil the tracker's first poll, and the error is logged.Open questions
None.
🤖 Generated with Claude Code