Skip to content

fix: end tracking of stuck CANCELING tasks - #450

Merged
uniqueg merged 5 commits into
devfrom
fix/end-stuck-cancels
Nov 6, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/end-stuck-cancels

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

As decided in #437: a task still CANCELING polling.max_cancel_time seconds after its cancel is set to SYSTEM_ERROR, no longer tracked, and logged with a warning.

  • New setting custom.controllers.post_task.polling.max_cancel_time (default 3600 seconds, at most a year).
  • Cancels store their time (tracking.canceled_at), together with CANCELING; DbDocumentConnector.update_task_state takes further fields.
  • Polls end the tracking once the limit has passed: on failed polls (e.g., a decommissioned or failing backend), and on polls that report an unfinished state. A final state reported by the backend, or a 404/410 (CANCELED), still wins. The task's poll is set to a sentinel, so that no poll claims it, and polls running meanwhile store no unfinished state over SYSTEM_ERROR, so the task is never resumed. If a worker of the earlier version stores a state over the end during a rolling upgrade, each resume sets the task back to SYSTEM_ERROR, and never resumes its tracking.
  • Tasks canceled by earlier versions (also during a rolling upgrade) get the time when the workers resume the tracking.

Docs: configuration reference (Tasks), task tracking (operations), API table, base config, chart values.yaml example, upgrade notes (To version 0.6.0).

Closes #437

Verification

  • coverage run -m pytest (mongomock, Helm 3.22.1 for the chart tests): 1642 passed, 11 skipped; coverage 100%
  • pytest against MongoDB 7.0.34 (MONGODB_TEST_URI, own mongod --nounixsocket): 1652 passed, 1 skipped
  • ruff 0.17.3 check and format, mypy, ast-grep scan and test, semgrep (.semgrep): pass
  • mkdocs build --strict: pass
  • CI: all checks passed (CI passed, tests on mongomock and MongoDB 7.0, chart, smoke test, docs, image scan), also after the Sourcery fixes

Review

Full review (adversarial + quality, 2 rounds). Fixed: a race in which another delivery of the same poll could store an unfinished state over SYSTEM_ERROR and resume the tracking (regression test test_cancel_time_exceeded_concurrently); tests of the limits of the setting, and of a 404 after the limit; the stamping of earlier cancels as a helper with its reason; docs on when exactly tracking ends; resuming skips ended tracking (rolling upgrades with workers of the earlier version).

Sourcery: fixed, each resume sets unfinished tasks whose tracking ended back to SYSTEM_ERROR (a worker of the earlier version may store a state over the end during a rolling upgrade, and the task may be canceled again; test_ended_tracking_stays_failed); documented that the cancel time of a task that a poll set to CANCELING first is stamped on resume.

Lane: full review (behaviour change in task tracking).

Declined review findings

  • Sourcery: a 404/410 racing the timeout leaves SYSTEM_ERROR instead of CANCELED; a final response lost with its worker while another delivery times out the cancel. Both need concurrent deliveries of one poll after the limit has passed, and both end in the documented final state.

  • Sourcery: a worker of the earlier version resumes a task over the end during a rolling upgrade. That worker tracks it as the earlier version does; this ends with the rollout.

  • Clock skew between the app (which stores canceled_at) and the workers (which compare it) shifts the limit by the skew: irrelevant at the default of an hour; the same holds for max_create_time.

  • One canonical wording for the upgrade note: operations and upgrade notes address different readers; the upgrade note links to the operations page.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 6, 2026 17:40
A task still `CANCELING` `polling.max_cancel_time` seconds after its
cancel (new setting, default 3600) is set to `SYSTEM_ERROR`, no longer
tracked (no poll claims it, also not a redelivered one), and logged
with a warning; before, a decommissioned or failing backend kept it
polled forever. A final state that the backend reports wins.

Cancels store their time (`tracking.canceled_at`); for tasks canceled
by earlier versions, the time counts from when the workers resume the
tracking.

Documented in the configuration reference, task tracking, the API
table, the base config, the chart values and the upgrade notes.

Closes #437

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A poll running while another delivery ends the tracking of a task
stores no unfinished state over its `SYSTEM_ERROR`, so the task is
never resumed. Tests of the race, of a backend that no longer has the
task after the limit, and of the limits of the setting; the stamping of
earlier cancels is a helper of its own; one-year limit as a constant;
docs say when exactly tracking ends.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A worker of an earlier version can store an unfinished state over a
task whose cancel timed out during a rolling upgrade. Skip tasks whose
tracking ended when resuming tracking, so they are not polled again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Store each cancel timestamp atomically with the CANCELING state so tracking can determine how long cancellation has been pending.

  • pro_tes/ga4gh/tes/task_runs.py L12, L81-84, L1010-1015
  • pro_tes/utils/db.py L272, L280-281, L300

Add the cancellation timestamp and ended-tracking markers, enforce the timeout, and make timeout handling safe across poll deliveries and worker upgrades.

  • pro_tes/tasks/track_task_progress.py L58-65, L473-516, L787-827 (+8 small edits)

Data structures

Define max_cancel_time with a one-year upper bound and reuse that bound for the existing creation-time setting.

  • pro_tes/config_models.py L79-82 (+4 small edits)

API

Document the cancellation endpoint’s timeout outcome and explain the new polling configuration setting.

  • docs/api.md L21
  • docs/configuration.md L451-458

Implementation

Exercise timeout validation, final backend outcomes, concurrency protection, legacy cancellation timestamps, and ended-tracking resumption behavior.

  • tests/tasks/test_track_task_progress.py L1105-1329, L1744-1746, L1766-1772

Configuration

Provide a commented example for configuring the cancellation timeout in both the chart values and base configuration.

  • deployment/values.yaml L47-52
  • pro_tes/config.yaml L249-252

Documentation

Explain timeout behavior during task tracking and document upgrade effects for cancellations already in progress.

  • docs/operations.md L36-42, L70-72
  • docs/upgrading.md L64-78

Tests

Verify that canceling a task records its cancellation timestamp.

  • tests/ga4gh/tes/test_server.py L7, L424-435

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 Nov 6, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35704829 | 📁 Comparing 0bb8ee9 against latest (a9bc104)

  🔍 Preview build  

5 files changed · ± 5 modified

± Modified

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a9bc104) to head (0bb8ee9).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #450   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         2696      2719   +23     
=========================================
+ Hits          2696      2719   +23     

☔ 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 November 6, 2026 17:39

@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 6 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="1015" />
<code_context>
             if db_connector.update_task_state(
                 state=TesState.CANCELING.value,
                 if_state=States.TO_CANCEL,
+                fields={CANCELED_AT_FIELD: time.time()},
             ):
                 logger.info(
</code_context>
<issue_to_address>
**Accepted cancels never time out**

When a poll changes the task to another unfinished state after the backend accepts cancellation but before `update_task_state` runs, `update_task_state` only matches `States.TO_CANCEL`, so it stores neither `canceled_at` nor `CANCELING`; tracking never applies `max_cancel_time`, and the task remains unfinished indefinitely.

Allow an accepted cancellation to record its timestamp and enter `CANCELING` despite a concurrent unfinished-state update.
</issue_to_address>

### Comment 2
<location path="pro_tes/tasks/track_task_progress.py" line_range="549" />
<code_context>
         raise
     except Exception as exc:
-        if _deleted_after_cancel(collection=collection, worker_id=worker_id, exc=exc):
+        if _deleted_after_cancel(
+            collection=collection, worker_id=worker_id, exc=exc
+        ) or _cancel_timed_out(collection=collection, worker_id=worker_id):
</code_context>
<issue_to_address>
**Deleted tasks remain failed**

When a timeout changes the task to `SYSTEM_ERROR` while another poll handles a backend 404/410, `_deleted_after_cancel` only changes `CANCELING` or `CANCELED` tasks, and `_cancel_timed_out` also returns false, so the task stays `SYSTEM_ERROR` even though the backend confirmed it is gone.

Allow `_deleted_after_cancel` to record `CANCELED` when a timeout has already changed the task to `SYSTEM_ERROR`.

Also at `pro_tes/tasks/track_task_progress.py:500`, `pro_tes/tasks/track_task_progress.py:551`.
</issue_to_address>

### Comment 3
<location path="pro_tes/tasks/track_task_progress.py" line_range="501" />
<code_context>
+        {
+            "$set": {
+                "task.state": TesState.SYSTEM_ERROR.value,
+                POLL_FIELD: TRACKING_ENDED,
+            }
+        },
</code_context>
<issue_to_address>
**Timed-out task returns to RUNNING**

When an earlier-version worker has an in-flight poll when a new worker times out the cancel during a rolling upgrade, the older worker's `_store_state` matches `SYSTEM_ERROR` because its guard excludes only canceled states, then writes `RUNNING` over the timed-out task. The sentinel prevents resumption, so the task remains stored as `RUNNING` instead of `SYSTEM_ERROR`.

Before skipping sentinel tasks during resumption, restore `SYSTEM_ERROR` on any whose state is still unfinished, or drain earlier workers before enabling the timeout.
</issue_to_address>

### Comment 4
<location path="pro_tes/tasks/track_task_progress.py" line_range="749" />
<code_context>
         "tes_endpoint.host": {"$nin": ["", None]},
         "tes_endpoint.task_id": {"$type": "string"},
+        # also if a worker of an earlier version stored a state over the end
+        POLL_FIELD: {"$ne": TRACKING_ENDED},
         "$or": [
             {POLLED_AT_FIELD: {"$exists": False}},
</code_context>
<issue_to_address>
**Ended tasks resume without timeout**

When an earlier-version worker overwrites an ended task's state with an unfinished state during a rolling upgrade and then resumes it, the older worker's resume query ignores the sentinel and replaces the ended poll ID; because the task is no longer `CANCELING`, the resumed poller never applies the timeout and tracking continues.

Prevent an older worker's resume from replacing the ended sentinel after it overwrites the task state.
</issue_to_address>

### Comment 5
<location path="pro_tes/tasks/track_task_progress.py" line_range="500-501" />
<code_context>
+        },
+        {
+            "$set": {
+                "task.state": TesState.SYSTEM_ERROR.value,
+                POLL_FIELD: TRACKING_ENDED,
+            }
+        },
</code_context>
<issue_to_address>
**Timed-out poll blocks final-state redelivery**

When one poll delivery receives a final response while another delivery times out the cancellation, and the final-response worker dies before storing the result, `_cancel_timed_out` replaces the poll identifier with `TRACKING_ENDED`. If another delivery has already received a final backend response but its worker dies before storing it, Celery redelivers that poll and `_claim` rejects it because the sentinel no longer matches; the final state is lost and the task remains `SYSTEM_ERROR`.

Ensure an in-flight final response can still be persisted or redelivered after timeout handling, rather than making the timeout sentinel unconditionally reject that poll.
</issue_to_address>

### Comment 6
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="1015" />
<code_context>
             if db_connector.update_task_state(
                 state=TesState.CANCELING.value,
                 if_state=States.TO_CANCEL,
+                fields={CANCELED_AT_FIELD: time.time()},
             ):
                 logger.info(
</code_context>
<issue_to_address>
**Re-cancelled task loses tracking**

When an older worker restores an unfinished state over an ended task during a rolling upgrade, and the caller then cancels that task, `cancel_task` changes the task back to `CANCELING` and stores a new cancel time, but leaves `tracking.poll` as `TRACKING_ENDED`. `_claim` cannot claim that sentinel, and `task__resume_tracking` excludes it, so no poll checks the cancel timeout or records the backend’s final state; the task remains `CANCELING` indefinitely.

When starting a new cancellation, clear the ended marker and ensure the task is eligible for a fresh tracking poll.
</issue_to_address>

Linked issues

#437 fix: end tracking of stuck CANCELING tasks · 1 of 1 met

# Requirement Status Notes
1 Decide and implement or document how tracking ends when a CANCELING task’s backend never answers. ✅ Met The configurable timeout ends tracking by setting the task to SYSTEM_ERROR, marking its poll as ended, and logging a warning; legacy cancels are also covered.

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and after the timeout, proTES stores SYSTEM_ERROR and marks tracking ended; if the backend task is still running, it can continue without being monitored. Reverting the code does not restore tracking for those tasks, and the new default timeout silently determines when this happens.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:1015, pro_tes/tasks/track_task_progress.py:549, pro_tes/tasks/track_task_progress.py:501, pro_tes/tasks/track_task_progress.py:749, pro_tes/tasks/track_task_progress.py:501, and 1 more


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

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
During a rolling upgrade, a worker of an earlier version can store an
unfinished state over a task whose cancel timed out, and the task can
then be canceled again; no poll tracks it. Each resume now sets such
tasks back to SYSTEM_ERROR, with a warning. Also document that the
cancel time is stamped on resume when a poll stored CANCELING first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 02c3493 into dev Nov 6, 2026
40 of 50 checks passed
@uniqueg
uniqueg deleted the fix/end-stuck-cancels branch November 6, 2026 18:08
@uniqueg uniqueg mentioned this pull request Nov 7, 2026
6 tasks done
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: end tracking of stuck CANCELING tasks

1 participant