Repository navigation
fix: track tasks by rescheduled polls - #288
Conversation
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]>
# Conflicts: # pro_tes/config_models.py
Reviewer's GuideThis 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 pollingsequenceDiagram
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
State diagram for failed task pollsstateDiagram-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 --> [*]
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 #288 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 29 29
Lines 2244 2326 +82
=========================================
+ Hits 2244 2326 +82 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
- 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
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.
tasks.track_run_progresspolls 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.polling.attemptsconsecutive failures the state becomesUNKNOWN(cancelable with fix: store and cancel new tasks at backends #275) instead of a finalSYSTEM_ERROR, and polls back off up topolling.max_waitseconds (new, default 600). A storedCANCELEDis kept until the backend reports a finished state.acks_late,reject_on_worker_lost).tracking.poll), claimed by compare-and-set, so that duplicates, redeliveries and resumed polls leave one chain per task.3 * max_wait(tracking.polled_at) when they start and everymax_waitseconds afterwards.worker.terminationGracePeriodSecondscomment invalues.yamland the chart README are corrected.INITIALIZINGwhen it starts tracking a task; the stored state is the one the backend reports.Coordination:
pro_tes/ga4gh/tes/task_runs.pyis not touched (#274/#275 work there).origin/devwith #281 (extra='forbid') is merged:Pollingis now aConfigModeland gets the newmax_waitfield.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.pyagainst 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): passedmkdocs build --strict: passedUNKNOWNand backoff with its capacks_late,max_retriesand prefetch settingsconsumer_timeout); these Celery/RabbitMQ semantics were checked by reading Celery 5.6.3's source.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,
BackendNotConfiguredgave a finalSYSTEM_ERROR, cancels were overwritten,max_retries=Noneonretry()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 loweredattemptsstill lead to UNKNOWN, the failure count is stored so resumed polls keep backing off, an index for the resume query, andwait/max_waitmust be below 1800 s (RabbitMQ's defaultconsumer_timeout). That commit was not reviewed by the subagents again, as the two rounds were used up.Declined review findings
worker_prefetch_multiplierintoconfig.yaml(quality, low): FOCA'sjobsconfig has no Celery settings, so it is set oncelery.confincelery_worker.py.docs/operations.mdinstead.max_wait" is spelled out in the docs rather than namingSTALE_FACTOR(quality, low): the constant is internal.Open questions
None.
Closes #277
Closes #278
Closes #279
🤖 Generated with Claude Code