Repository navigation
fix: stop tasks cancelled before the taskmaster - #103
Conversation
The TESK API cancels a task by labelling the taskmaster's job and only a running taskmaster pod. A task cancelled while the pod was pending, or before the pod existed, had the label on its job only: the API reported it as CANCELED, but the taskmaster never saw the label and ran all executors. The taskmaster now also reads its job's cancel label from the Kubernetes API (job name from the pod's job-name label), before it creates the first job and at every poll. The pod labels are parsed per line, so a cancel label that isn't the last line counts too; only task-status: Cancelled cancels a task now. Refs elixir-cloud-aai/TESK#219 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings: one BatchV1Api client for all polls, a warning instead of a crash when the API server can't be reached, tests for the labels parser and the logged warnings, and docs on the extra request per poll, the chart's role and the missing labels file. Refs elixir-cloud-aai/TESK#219 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without --debug, the taskmaster logs only errors, so the warning about an unreadable job (e.g. a role without get on jobs) never showed. Log the first such error at ERROR and later ones at DEBUG, so that it shows once without flooding the log at every poll. Refs elixir-cloud-aai/TESK#219 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideImplementationAdd job-label cancellation checks and parse pod labels by line, including checks before starting subsequent executors and the outputs filer.
DocumentationDocument job- and pod-based cancellation behavior, API read handling, timeout and RBAC requirements, and the upgrade note for custom roles.
TestsAdd regression tests for early cancellation, label parsing and ordering, API failures, client reuse, and cancellation between jobs.
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 #103 +/- ##
==========================================
+ Coverage 89.42% 91.55% +2.12%
==========================================
Files 10 10
Lines 1135 1172 +37
==========================================
+ Hits 1015 1073 +58
+ Misses 120 99 -21 ☔ 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="src/tesk_core/taskmaster.py" line_range="550" />
<code_context>
+ job_name = next((labels[key] for key in job_name_labels if key in labels), None)
+ if job_name is None:
+ return False
+ return is_job_cancelled(job_name)
</code_context>
<issue_to_address>
**Cancelled tasks advance executors**
When cancellation arrives after a poll's cancellation check and the child job reaches Complete before the next status read, `Job.run_to_completion()` checks `check_cancelled()` only while the child job is Running, so it accepts the Complete status without checking the job label again and advances to later executors. The cancelled task can finish executor side effects and continue despite TESK reporting CANCELED.
Check for cancellation when the child job is Complete before accepting completion or advancing to later executors.
</issue_to_address>
### Comment 2
<location path="src/tesk_core/taskmaster.py" line_range="522" />
<code_context>
+ if batch_api is None:
+ batch_api = client.BatchV1Api()
+ try:
+ job = batch_api.read_namespaced_job(job_name, args.namespace)
+ except (ApiException, HTTPError) as ex:
+ log_job_read_error(job_name, ex)
</code_context>
<issue_to_address>
**Slow API stalls cancellation checks**
When the Kubernetes API accepts the job-read request but does not respond, `read_namespaced_job` has no explicit request timeout, so a Kubernetes API call that stalls blocks `check_cancelled()` before it can return; the taskmaster remains stuck at startup or keeps an executor running instead of observing cancellation.
Set a finite request timeout for the job read so a stalled API cannot block cancellation checks indefinitely.
</issue_to_address>
### Comment 3
<location path="tests/unit/test_taskmaster_cancel.py" line_range="17" />
<code_context>
+
+# As the Downward API writes them: one `key="value"` per line, sorted by key,
+# without a newline after the last line
+POD_LABELS = 'batch.kubernetes.io/job-name="task-1234"\njob-name="task-1234"'
+
+
</code_context>
<issue_to_address>
**Modern job label is masked**
When the Kubernetes 1.27 job-name label is ignored while legacy `job-name` support remains, when the code ignores `batch.kubernetes.io/job-name` but still supports `job-name`, `test_check_cancelled_job_label` passes because `POD_LABELS` supplies both keys with the same value and the legacy key still finds the cancelled job. The Kubernetes 1.27 label path can therefore be broken without this test failing.
Use only `batch.kubernetes.io/job-name` in the main job-label test fixture, keeping the legacy-only case separate.
</issue_to_address>Linked issues
#219 fix: early cancel leaves the executor running · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Canceling a task before its taskmaster pod runs stops the task, or it never starts. | ✅ Met | The taskmaster checks cancellation during initialization before calling run_task, and check_cancelled reads the taskmaster job's cancel label when the pod has no cancel label. |
| 2 | A test covers it. | ✅ Met | test_main_cancelled_before_start verifies that a cancelled job with an unlabelled pod makes main exit before run_task is called. |
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if a taskmaster job is incorrectly marked task-status: Cancelled, the taskmaster exits before creating its task job, so that task will not run. Reverting stops future early exits but does not automatically replay tasks already skipped; those tasks can be rerun.
Blocking findings: src/tesk_core/taskmaster.py:550, src/tesk_core/taskmaster.py:522, tests/unit/test_taskmaster_cancel.py:17
Address Sourcery's review: an executor job that completes between two polls was never checked for cancellation, so a cancelled task started its next executor or the outputs filer. Check before each executor and before the outputs filer. Bound the job read with a request timeout, so that a stalled API server can't block the check, and test the label of Kubernetes 1.27+ on its own. Refs elixir-cloud-aai/TESK#219 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Kubernetes client retries the job read up to 3 times, so the timeouts apply per attempt. Refs elixir-cloud-aai/TESK#219 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
A task cancelled before its taskmaster pod runs was reported as
CANCELED, but its executors kept running.Cause: the TESK API cancels a task by labelling the taskmaster's job (
task-status: Cancelled, which gives the stateCANCELED) and only a taskmaster pod in phaseRunning. The taskmaster checked only its own pod's labels (/podinfo/labels, Downward API). A task cancelled while that pod was pending, or before the job controller created it (also a pod restarted after an eviction), had the label on its job only, so the taskmaster never saw it.Fix (tesk-core only; no change in tesk-api or the chart needed):
check_cancelled()also reads the cancel label of the taskmaster's own job from the Kubernetes API (one client, reused; one extragetper poll). The job name comes from the pod'sbatch.kubernetes.io/job-name/job-namelabel, the namespace from-n. The check runs before the first job is created and at every poll, as before. TESK's Helm chart already grants the taskmastergetonjobs(charts/tesk/templates/common/taskmaster-rbac.yamlin elixir-cloud-aai/TESK). If the job can't be read (API error, missing job, API server unreachable), the taskmaster logs an error (the first one atERROR, later ones atDEBUG, so it shows without--debugbut not at every poll) and relies on the pod label until the next poll.run_taskalso checks for cancellation before each executor and before the outputs filer: an executor job that completed between two polls was never checked, so a cancelled task could start the next one (from Sourcery's review). The job read has a request timeout (5 s connect, 10 s read, per attempt).Cancelledlabel that wasn't the last line didn't match (trailing newline); it only worked becausetask-statussorts last. Onlytask-status: Cancelledcancels now (the label the TESK API sets), not any label with the valueCancelled.docs/taskmaster.md(how cancellation reaches the taskmaster) anddocs/upgrading.md(Unreleased: the new behaviour and the RBAC note for custom roles).Upgrade order: none. The fix works with any TESK API release (incl. 1.1.0); deploy the new taskmaster image.
Closes elixir-cloud-aai/TESK#219
Verification
pytest: all tests pass, incl. the newtests/unit/test_taskmaster_cancel.py(regression: a job labelled as cancelled with an unlabelled pod cancels;main()exits beforerun_taskin that case; pod label not on the last line; olderjob-namelabel; no labels file or job name; API and connection errors, logged once atERROR; client reuse; labels parser edge cases). 394 tests pass.pre-commit run --all-files(ruff, ruff format, mypy, gitleaks, actionlint, ...): passed.mkdocs build --strict: passed.CI passed), on the first push and again after the Sourcery fixes.Declined review findings
-nnamespace would then cancel every task; a job deleted with--cascade=orphanis an operator action outside the TES contract. Documented indocs/taskmaster.md.getper 5 s per task is small next to the existing status reads, and skipping polls would reopen a window for the race.exit_cancelled) already leaves the PVC behind before this PR; worth its own issue.logging.debugvsloggerin the rest of the module (quality, low): out of scope.Open questions
None.
🤖 Generated with Claude Code