Skip to content

fix: track tasks by rescheduled polls - #288

Merged
uniqueg merged 7 commits into
devfrom
fix/track-by-rescheduling
Oct 24, 2026
Merged

uniqueg merged 7 commits into
devfrom
fix/track-by-rescheduling

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Redesigns how Celery workers track forwarded tasks at their TES backends (findings 3, 4 and 5 of the v0.3.0 pre-release review). The three issues change the same loop, so they are fixed together.

  • No blocked workers (fix: track tasks without blocking workers #277): each run of tasks.track_run_progress polls the backend once and, while the task is unfinished, schedules the next poll (countdown). A few worker processes now track many tasks. worker_prefetch_multiplier=1.
  • Failed polls don't fail tasks (fix: keep tracking tasks after failed polls #278): only consecutive failed polls count, and a successful poll resets the count. The first poll is retried too, and so are polls of backends that are not (or no longer) configured or discovered. After polling.attempts consecutive failures the state becomes UNKNOWN (cancelable with fix: store and cancel new tasks at backends #275) instead of a final SYSTEM_ERROR, and polls back off up to polling.max_wait seconds (new, default 600). A stored CANCELED is kept until the backend reports a finished state.
  • Restarts don't lose tracking (fix: keep tracking tasks across worker restarts #279):
    • Polls are acknowledged late (acks_late, reject_on_worker_lost).
    • Polls that fail because MongoDB is down are retried without limit, with backoff; polls whose next poll can't be published go back to the broker.
    • Each poll has an identifier (tracking.poll), claimed by compare-and-set, so that duplicates, redeliveries and resumed polls leave one chain per task.
    • Workers resume the tracking of unfinished tasks not polled for 3 * max_wait (tracking.polled_at) when they start and every max_wait seconds afterwards.
    • The false worker.terminationGracePeriodSeconds comment in values.yaml and the chart README are corrected.
  • Docs: operations (task tracking, worker sizing), configuration, access control, getting started, upgrading, and the chart README.
  • The worker no longer sets INITIALIZING when it starts tracking a task; the stored state is the one the backend reports.

Coordination: pro_tes/ga4gh/tes/task_runs.py is not touched (#274/#275 work there). origin/dev with #281 (extra='forbid') is merged: Polling is now a ConfigModel and gets the new max_wait field.

Verification

  • coverage run -m pytest -W ignore::DeprecationWarning (mongomock, Helm 3.22.1 chart tests included): 999 passed, 2 skipped (after merging dev with fix: submit tasks to backends exactly once #282); coverage report --fail-under=100: 100%
  • MONGODB_TEST_URI=mongodb://127.0.0.1:27311 pytest tests/tasks tests/ga4gh/tes/test_server.py against MongoDB 7.0: 104 passed (before the last review round's fixes)
  • pre-commit run --all-files (ruff, ruff format, semgrep, gitleaks, actionlint, ast-grep, mypy): passed
  • mkdocs build --strict: passed
  • New tests cover:
    • one poll per run
    • retry of the first poll
    • reset of consecutive failures
    • UNKNOWN and backoff with its cap
    • unknown backends
    • MongoDB retry and broker requeue
    • superseded, redelivered and taken-over polls (worker lost between scheduling and storing)
    • stale-only resume, and resume at start and periodically
    • cancels kept, also against a concurrent cancel
    • the acks_late, max_retries and prefetch settings
  • Not run: RabbitMQ end to end (redelivery of ETA messages on shutdown, consumer_timeout); these Celery/RabbitMQ semantics were checked by reading Celery 5.6.3's source.
  • CI (before 1b69ba2): all checks passed (tests with mongomock and MongoDB 7.0, Helm chart, Docker Compose smoke test, docs, static analysis, image scan, CodeQL)

Reviews

Full lane (real logic): two rounds of the adversarial and quality reviewers. All high and medium findings are fixed: errors after the claim ended chains, BackendNotConfigured gave a final SYSTEM_ERROR, cancels were overwritten, max_retries=None on retry() still meant 3, and a failed broker retry was rejected without requeue. Cheap lows were fixed too. Sourcery then raised five medium findings, all fixed in 1b69ba2: a retry that cannot be published is requeued, failure counts above a lowered attempts still lead to UNKNOWN, the failure count is stored so resumed polls keep backing off, an index for the resume query, and wait/max_wait must be below 1800 s (RabbitMQ's default consumer_timeout). That commit was not reviewed by the subagents again, as the two rounds were used up.

Declined review findings

  • Move worker_prefetch_multiplier into config.yaml (quality, low): FOCA's jobs config has no Celery settings, so it is set on celery.conf in celery_worker.py.
  • Resume canceled tasks whose tracking was lost before the backend finished them (adversarial, low): this needs a separate "canceled, not final" marker. It is documented as a limitation in docs/operations.md instead.
  • "Three times max_wait" is spelled out in the docs rather than naming STALE_FACTOR (quality, low): the constant is internal.

Open questions

None.

Closes #277
Closes #278
Closes #279

🤖 Generated with Claude Code

uniqueg and others added 5 commits October 24, 2026 02:18
Each run of the tracking Celery task now polls the backend once and,
while the task is unfinished, schedules the next poll (countdown), so
no worker process is held for the runtime of a task (#277).

Failed polls are retried, the first one too; only consecutive failures
count, and a successful poll resets them. After `polling.attempts`
consecutive failures, the state is set to UNKNOWN instead of a final
SYSTEM_ERROR, and polls back off up to `polling.max_wait` seconds
(new, default 600) until the backend answers again (#278).

Polls are acknowledged late (acks_late, reject_on_worker_lost), with
a prefetch multiplier of 1, and workers resume the tracking of stored
unfinished tasks with a remote identifier when they start. Each poll
has an identifier, stored in `tracking.poll`, which ensures that one
chain of polls tracks each task: superseded and redelivered polls do
nothing (#279).

The worker no longer sets INITIALIZING when it starts tracking; the
state is the one reported by the backend.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document how tasks are tracked, how to size the workers, and that
worker restarts and upgrades no longer stop the tracking (operations,
configuration, getting started, upgrading, chart README). Correct the
comment on `worker.terminationGracePeriodSeconds` in values.yaml,
which said that killed tasks were delivered again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes from the review of the rescheduled tracking:

- Polls that fail because MongoDB or the broker is unavailable are
  retried with backoff (max_retries=None) instead of failing, which
  acknowledged the message and ended the chain.
- Polls of tasks whose backend is not configured or not discovered
  count as failed polls (UNKNOWN, backoff) instead of a final
  SYSTEM_ERROR, e.g., after a worker restart while the registry is
  unreachable.
- A stored CANCELED is kept until the backend reports a finished
  state, instead of being overwritten by RUNNING.
- The resume sweep only resumes tasks not polled for three times
  `max_wait` (`tracking.polled_at`), so restarts don't supersede
  live chains; it schedules the new poll before storing it, so that
  it can take over, and runs at worker start and then periodically.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes from the second review round:

- Set max_retries=None on the tracking task: on retry() it means the
  task's limit (3 by default), so MongoDB outages ended chains.
- Return polls whose next poll can't be published to the broker
  (Reject with requeue) instead of retrying, which would be rejected
  without requeue.
- Store states of unfinished tasks only if the stored state is not
  CANCELED, also on the failure path (UNKNOWN) and for a cancel that
  commits while a poll runs.
- Share the backoff computation, and document that canceled tasks
  are not resumed.

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 redesigns Celery task tracking around short, independently scheduled polls with resilient retry and compare-and-set chain ownership, allowing workers to track many tasks without blocking and to recover tracking after backend, broker, MongoDB, or worker failures; configuration, documentation, and comprehensive tests are updated accordingly.

Sequence diagram for resilient task polling

sequenceDiagram
    participant Broker
    participant Worker
    participant MongoDB
    participant TES

    Broker->>Worker: task__track_task_progress
    Worker->>MongoDB: _claim(poll, previous)
    alt poll is current
        Worker->>TES: get_task(task_id)
        alt unfinished task
            Worker->>MongoDB: _store_state(state)
            Worker->>Broker: _schedule(next poll, countdown)
            Worker->>MongoDB: pass tracking to successor
        else finished task
            Worker->>MongoDB: _store_final(response)
        end
    else duplicate or superseded poll
        Worker-->>Worker: stop chain
    end
    Note over Broker,Worker: acks_late and reject_on_worker_lost enable redelivery
Loading

State diagram for failed task polls

stateDiagram-v2
    [*] --> Polling
    Polling --> Polling: successful poll / reset failures
    Polling --> Polling: failed poll / retry after wait
    Polling --> Unknown: attempts consecutive failures
    Unknown --> Unknown: failed poll / exponential backoff to max_wait
    Unknown --> Polling: successful poll
    Polling --> Finished: backend reports finished state
    Unknown --> Finished: backend reports finished state
    Finished --> [*]
Loading

File-Level Changes

Change Details Files
Reworked task tracking from long-running worker loops into individually scheduled, retryable polls.
  • Polls perform one backend request and schedule the next unfinished-task poll with configurable backoff.
  • Added late acknowledgements, worker-loss rejection, single-message prefetch, and infrastructure retry behavior.
  • Added poll identifiers and compare-and-set claims so duplicate, redelivered, resumed, and superseded polls converge on one chain.
  • Added worker-start and periodic recovery of stale unfinished task tracking.
  • Preserved canceled states until the backend reports a finished state and stopped setting INITIALIZING during tracking.
pro_tes/tasks/track_task_progress.py
pro_tes/celery_worker.py
Extended polling configuration and documented the new tracking and recovery behavior.
  • Added positive validation and a default max_wait cap for exponential polling backoff.
  • Documented UNKNOWN state semantics, consecutive failure resets, worker sizing, restart recovery, cancellation limitations, and upgrade behavior.
  • Updated access-control, getting-started, deployment, and Helm chart guidance.
pro_tes/config_models.py
pro_tes/config.yaml
docs/configuration.md
docs/operations.md
docs/access-control.md
docs/getting-started.md
docs/upgrading.md
deployment/README.md
deployment/values.yaml
Expanded automated coverage for polling lifecycle, failure handling, concurrency safety, and recovery.
  • Replaced sleep-based loop tests with scheduled-poll assertions.
  • Covered first-poll retries, consecutive-failure reset and capped backoff, unknown backends, MongoDB retries, broker requeue, cancellation preservation, and final-state storage.
  • Covered duplicate and lost-worker chains, stale-task resume, periodic startup recovery, task deletion, and Celery acknowledgement settings.
tests/tasks/test_track_task_progress.py
tests/ga4gh/tes/test_server.py

Assessment against linked issues

Issue Objective Addressed Explanation
#277 Track each unfinished task with one backend poll per Celery task run, scheduling the next poll with a countdown instead of blocking a worker in a sleep loop. ✅
#277 Set Celery's worker prefetch multiplier to 1 so workers do not reserve a large backlog of tracking messages. ✅
#277 Document how to size worker capacity using concurrency and replicas in the operations documentation and Helm chart. ✅
#278 Retry the initial backend poll and track consecutive poll failures, resetting the failure count after each successful poll. ✅
#278 After the configured number of consecutive failures, keep tracking rather than setting a final error: store UNKNOWN, back off polling up to a configurable maximum, and restore the backend-reported state when it responds. ✅
#278 Update the polling configuration documentation to describe consecutive failures and the non-final UNKNOWN/backoff behavior. ✅
#279 Make tracking polls recoverable across worker loss or restart by acknowledging them late, resuming stale unfinished tasks that have a backend, and ensuring each task has only one active chain of polls. ✅
#279 Correct the worker termination-grace-period comment and update the chart README, operations documentation, and upgrading documentation to describe tracking and restart behavior accurately. ✅

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 (b674f9f) to head (1b69ba2).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #288   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         2244      2326   +82     
=========================================
+ Hits          2244      2326   +82     

☔ 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:43

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

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

## Individual Comments

### Comment 1
<location path="pro_tes/config_models.py" line_range="98" />
<code_context>

-    wait: int = 3
-    attempts: int = 100
+    wait: PositiveInt = 3
+    attempts: PositiveInt = 100
+    max_wait: PositiveInt = 600
</code_context>
<issue_to_address>
**Scheduled polls are repeatedly redelivered**

When `polling.wait` or `polling.max_wait` meets or exceeds RabbitMQ's consumer acknowledgement timeout, celery keeps countdown polls unacknowledged until they are due, so RabbitMQ closes the channel and redelivers them before their scheduled interval elapses, disrupting tracking.

Constrain both polling settings to remain below the broker's acknowledgement timeout.

Also at `docs/configuration.md:182`, `pro_tes/config_models.py:99-100`, `pro_tes/tasks/track_task_progress.py:75`, `pro_tes/tasks/track_task_progress.py:93`.
</issue_to_address>

### Comment 2
<location path="pro_tes/tasks/track_task_progress.py" line_range="367" />
<code_context>
+            exc,
+        )
+        # retried until MongoDB is available (`max_retries=None`)
+        raise self.retry(exc=exc, countdown=countdown) from exc

-    # create database client
</code_context>
<issue_to_address>
**Failed retries end the poll chain**

When mongoDB raises `PyMongoError` and publishing the Celery retry also fails, `self.retry()` raises `OperationalError` from inside the `PyMongoError` handler, outside the sibling handler that covers `_poll`; the late-acknowledged delivery then fails and is acknowledged, leaving tracking to the stale-task sweep.

Handle retry-publication `OperationalError` so the failed delivery does not end the poll chain.
</issue_to_address>

### Comment 3
<location path="pro_tes/tasks/track_task_progress.py" line_range="253" />
<code_context>
+            exc,
+        )
+        if failures == get_custom_config().controllers.post_task.polling.attempts:
+            logger.error(
+                "[%s] %d consecutive polls failed; the state is unknown until"
+                " the backend answers again",
</code_context>
<issue_to_address>
**Tasks never become unknown**

When `polling.attempts` is lowered below the failure count carried by a queued poll, the equality check against `polling.attempts` is already false, so the task keeps its previous state instead of becoming `UNKNOWN` while failures continue.

Use a threshold check that also handles failure counts already above the configured limit.

Also at `pro_tes/tasks/track_task_progress.py:252`.
</issue_to_address>

### Comment 4
<location path="pro_tes/tasks/track_task_progress.py" line_range="407-413" />
<code_context>
+        # scheduled first, so that the poll can take over if storing it fails
+        task__track_task_progress.apply_async(
+            kwargs={
+                "worker_id": document["worker_id"],
+                "remote_host": endpoint["host"],
+                "remote_base_path": endpoint.get("base_path") or "",
+                "remote_task_id": endpoint["task_id"],
+                "poll": poll,
+                "previous": current,
+            },
+        )
+        collection.update_one(
</code_context>
<issue_to_address>
**Restart resets poll backoff**

When a task has accumulated consecutive failed polls and its tracking chain is later lost and resumed, `task__resume_tracking` starts the resumed poll without its failed-poll count, so `task__track_task_progress` uses its default of zero. After a lost tracking chain during a backend outage, polls run at the short `polling.wait` interval for another `polling.attempts` failures instead of retaining their backoff, increasing load on the unavailable backend.

Persist the consecutive failure count with the task’s tracking metadata and pass it into resumed polls.
</issue_to_address>

### Comment 5
<location path="pro_tes/tasks/track_task_progress.py" line_range="388-395" />
<code_context>
+    polling = get_custom_config().controllers.post_task.polling
+    stale = time.time() - STALE_FACTOR * max(polling.max_wait, polling.wait)
+    collection = get_collection(TASK_DB, TASK_COLLECTION)
+    query = {
+        "task.state": {"$in": States.UNFINISHED},
+        "tes_endpoint.host": {"$nin": ["", None]},
+        "tes_endpoint.task_id": {"$type": "string"},
+        "$or": [
+            {POLLED_AT_FIELD: {"$exists": False}},
+            {POLLED_AT_FIELD: {"$lt": stale}},
+        ],
+    }
+    resumed = 0
</code_context>
<issue_to_address>
**Resume sweep scans all tasks**

When the task collection grows large and resume sweeps continue running, `task__resume_tracking` filters on task state, TES endpoint and `tracking.polled_at`, but the configured indexes cover only `task.id` and `worker_id`. MongoDB therefore scans the task collection on each sweep, adding increasing database load as retained tasks accumulate.

Add an index appropriate to the resume query, and verify its use with the supported MongoDB query plan.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and a defect in the poll chains could leave a task with a stale or incorrect stored state, or delay its final logs and outputs. Those task records are persisted, but the state can generally be refreshed from the TES backend; reverting restores the previous tracking behavior, though it does not undo state changes already stored.

Blocking findings: pro_tes/config_models.py:98, pro_tes/tasks/track_task_progress.py:367, pro_tes/tasks/track_task_progress.py:253, pro_tes/tasks/track_task_progress.py:413, pro_tes/tasks/track_task_progress.py:395


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

Comment thread pro_tes/config_models.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
uniqueg and others added 2 commits October 24, 2026 04:04
- Requeue polls whose MongoDB retry can't be published (Celery
  rejects them without requeue otherwise).
- Set UNKNOWN for any failure count at or above `polling.attempts`,
  also if it was lowered meanwhile.
- Store the consecutive failure count (`tracking.failures`), so that
  resumed polls keep backing off.
- Index `task.state` and `tracking.polled_at` for the resume sweep.
- Require `wait` and `max_wait` below 1800 seconds, RabbitMQ's
  default acknowledgement timeout.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	pro_tes/config.yaml
#	pro_tes/config_models.py
@uniqueg
uniqueg merged commit 9e3ff28 into dev Oct 24, 2026
19 checks passed
@uniqueg
uniqueg deleted the fix/track-by-rescheduling branch October 24, 2026 02:25
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: keep tracking tasks across worker restarts fix: keep tracking tasks after failed polls fix: track tasks without blocking workers

1 participant