Skip to content

fix: stop tasks cancelled before the taskmaster - #103

Merged
uniqueg merged 5 commits into
devfrom
fix/early-cancel
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/early-cancel

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

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 state CANCELED) and only a taskmaster pod in phase Running. 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 extra get per poll). The job name comes from the pod's batch.kubernetes.io/job-name / job-name label, 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 taskmaster get on jobs (charts/tesk/templates/common/taskmaster-rbac.yaml in 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 at ERROR, later ones at DEBUG, so it shows without --debug but not at every poll) and relies on the pod label until the next poll.
  • run_task also 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).
  • The pod labels file is parsed line by line. Before, a Cancelled label that wasn't the last line didn't match (trailing newline); it only worked because task-status sorts last. Only task-status: Cancelled cancels now (the label the TESK API sets), not any label with the value Cancelled.
  • Docs: docs/taskmaster.md (how cancellation reaches the taskmaster) and docs/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 new tests/unit/test_taskmaster_cancel.py (regression: a job labelled as cancelled with an unlabelled pod cancels; main() exits before run_task in that case; pod label not on the last line; older job-name label; no labels file or job name; API and connection errors, logged once at ERROR; 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: all checks passed (Lint, Docs, Test on Python 3.10-3.13, image scans, CodeQL, CI passed), on the first push and again after the Sourcery fixes.
  • Not run: an end-to-end check on a cluster (cancel while the taskmaster pod is pending); no cluster available to this agent.

Declined review findings

  • Treat a 404 on the taskmaster's own job as cancelled (adversarial, low): declined. A wrong -n namespace would then cancel every task; a job deleted with --cascade=orphan is an operator action outside the TES contract. Documented in docs/taskmaster.md.
  • Read the job label only every few polls (adversarial, low): declined. One get per 5 s per task is small next to the existing status reads, and skipping polls would reopen a window for the race.
  • Delete the task's PVC when the taskmaster stops on cancellation (adversarial, low): out of scope. Every cancel and failure path (exit_cancelled) already leaves the PVC behind before this PR; worth its own issue.
  • Align logging.debug vs logger in the rest of the module (quality, low): out of scope.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits November 7, 2026 18:20
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]>
@uniqueg uniqueg added the type: bug Something isn't working label Nov 7, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Add job-label cancellation checks and parse pod labels by line, including checks before starting subsequent executors and the outputs filer.

  • src/tesk_core/taskmaster.py L29-47, L294-298, L473-562 (+2 small edits)

Documentation

Document job- and pod-based cancellation behavior, API read handling, timeout and RBAC requirements, and the upgrade note for custom roles.

  • docs/taskmaster.md L69-90
  • docs/upgrading.md L9-23

Tests

Add regression tests for early cancellation, label parsing and ordering, API failures, client reuse, and cancellation between jobs.

  • tests/unit/test_taskmaster_cancel.py L1-312

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

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.55%. Comparing base (8f827e0) to head (5883a89).

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.
📢 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 7, 2026 17:30

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


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

Comment thread src/tesk_core/taskmaster.py Resolved
Comment thread src/tesk_core/taskmaster.py Resolved
Comment thread tests/unit/test_taskmaster_cancel.py Resolved
uniqueg and others added 2 commits November 7, 2026 18:36
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]>

@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.

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit f956ccd into dev Nov 7, 2026
43 checks passed
@uniqueg
uniqueg deleted the fix/early-cancel branch November 7, 2026 17:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: early cancel leaves the executor running

1 participant