Skip to content

feat: report the CANCELING and PREEMPTED states - #151

Merged
uniqueg merged 12 commits into
devfrom
feat/144-canceling-preempted
Nov 12, 2026
Merged

uniqueg merged 12 commits into
devfrom
feat/144-canceling-preempted

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

Was stacked on #149, which is merged; dev is merged into this branch.

Summary

TES 1.1 narrows CANCELED to cancelled tasks whose resources are gone, and adds CANCELING and PREEMPTED.

  • CANCELING: a task whose taskmaster job is labelled cancelled is CANCELING while a job of the task (taskmaster, executors, outputs filer) has a pod that hasn't ended (pending, running, terminating, Unknown, no status yet) or that Kubernetes counts as active; then CANCELED.
    • A pod still listed a minute after its deletion time (the end of its grace period, e.g. on a node that is gone) counts as ended, so it doesn't keep the task CANCELING until the node is removed. The minute allows for clock differences between TESK API and the API server.
    • Getting a single cancelled task also reads the outputs filer's pods (the list path reads all pods already).
    • The inputs filer's job isn't read; documented: a task cancelled during input staging can be CANCELED before the inputs filer's pod ended.
  • Cancel requests: cancelling a CANCELING task answers 200; it only labels a pending or running taskmaster pod that lacks the label (labelling failed before, or Kubernetes restarted the taskmaster), as only the pod's label stops the taskmaster. A pod that is gone (404) is skipped; other errors fail the request. (The issue says "patches nothing"; this deviation is decided: accepted by the maintainer, see the Sourcery thread.) CANCELED and PREEMPTED tasks have ended: 400.
  • PREEMPTED: a failed executor counts as disrupted if at least one of its pods has DisruptionTarget=True with PreemptionByScheduler, TerminationByKubelet, DeletionByTaintManager or EvictionByEvictionAPI, and every pod in phase Failed has it. The task is PREEMPTED if every failed executor was disrupted, otherwise EXECUTOR_ERROR. Pods without the condition (or already deleted) stay EXECUTOR_ERROR.
  • PREEMPTED is in COMPLETED_STATES; TesState got both states in feat: filter tasks by state and tags #149 already.
  • Docs: docs/index.md (state rules, a CANCELING paragraph, the PREEMPTED paragraph incl. that Kubernetes deletes most disrupted pods soon, cancelling) and docs/api.md (the state filter links to the rules).

Closes #144

Verification

  • ./mvnw -B spotless:apply clean verify checkstyle:check spotless:check with Temurin 8: all unit and integration tests pass, BUILD SUCCESS.
  • Tests written first:
    • TaskStateResolverTest: the decision table gets CANCELING rows per job and PREEMPTED executor rows; each disruption reason; retried executors; executor error winning over preempted; a failed pod without disruption next to a disrupted running one; pods without status or in Unknown; pods past/within/just after their deletion time; active count without pods.
    • TesServiceImplCancelTest: canceling task not patched again; unlabelled running and pending taskmaster pods labelled; a pod that is gone skipped, other errors fail; pod without status skipped; canceled and preempted tasks give 400; a running outputs filer keeps the task canceling; filer pods not read for tasks that aren't cancelled.
    • TesServiceImplListTest, TesKubernetesConverterTest, NoAuthIT: expectations moved from CANCELED to CANCELING where pods still run; state=CANCELED on a canceling task lists none.
  • Patch coverage of the changed main lines against feat: filter tasks by state and tags #149's branch (JaCoCo, unit + IT): 100%.
  • mkdocs build --strict: passes.
  • CI: all checks pass after merging dev (with feat: filter tasks by state and tags #149 and fix: accept a null type of inputs and outputs #150), including codecov/patch and codecov/project.

Declined review findings

  • Reading the inputs filer's job and pods for CANCELING: needs a new job lookup in the single and the list path; documented instead (see above).
  • Phase Unknown without a deletion timestamp still keeps a task CANCELING (documented); timing those out would need a configurable limit.
  • From Sourcery: applying the deletion-time rule to pods already Succeeded/Failed (they hold no resources), and resolving the state once for filter and response (both use the same snapshot, milliseconds apart).
  • Extracting pod/job builders in TesServiceImplCancelTest and flattening the Stream.concat in hasActiveJob: style; left as is.

Open questions

None. Possible follow-up outside this repo: tesk-core could set a podFailurePolicy on executor jobs, so that a disruption stays visible on the job after Kubernetes deletes the pod.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV

Summary by Sourcery

Add TES 1.1 reporting for task cancellation progression and Kubernetes-preempted executor failures.

New Features:

  • Report CANCELING for cancelled tasks while task resources remain active, transitioning to CANCELED once they have ended.
  • Report PREEMPTED for tasks whose failed executors were disrupted by recognized Kubernetes preemption or eviction events.
  • Handle repeated cancellation requests for CANCELING tasks by completing any necessary taskmaster pod labeling and returning appropriate errors for ended tasks.

Bug Fixes:

  • Ensure cancelled task state reflects active taskmaster, executor, and outputs-filer resources, including active job counts and terminating pods.
  • Treat disruption conditions consistently across executor retries while preserving EXECUTOR_ERROR when any failed executor was not disrupted.

Enhancements:

  • Update task state resolution and cancellation behavior to align with TES 1.1 state semantics.
  • Document the new cancellation and preemption state rules and state-filter behavior.

Documentation:

  • Document CANCELING, CANCELED, and PREEMPTED state rules, cancellation behavior, and Kubernetes disruption handling.

Tests:

  • Add unit, service, converter, list, and integration coverage for cancellation progression, repeated cancellation, pod lifecycle timing, filer activity, and preemption reasons.

uniqueg and others added 8 commits November 12, 2026 07:54
GET /tasks accepts the TES 1.1 filters state, tag_key and tag_value.
Before, Spring ignored them and listed all tasks.

- state takes every tesState of TES 1.1; TesState gets CANCELING and
  PREEMPTED so that they are accepted (TESK doesn't report them yet).
  Other values give 400 naming the parameter.
- tag_key/tag_value are zipped into tags, matched as in the
  specification's table; more values than keys give 400. Commas stay
  part of a key or value (Spring would split a single value).
- Name and tags filter the taskmaster jobs of a page before the other
  jobs are listed, the state once they are; pages can be shorter, as
  with name_prefix.
- The parameters are in the API description, the arrays with
  collectionFormat multi.

Closes #143

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Review fixes for the task filters:

- A repeated tag_key is one more tag that must match, instead of its
  last value replacing the others (an empty one widened the filter).
- Empty tag_key and empty extra tag_value parameters filter nothing,
  like an empty name_prefix or state.
- The converter reads the tags of the stored task, with the parser it
  uses for the number of executors, instead of a second ObjectMapper
  in the service.
- PREEMPTED counts as ended for cancelling; TaskFilter gets hasState.
- Tests for null tag values and for invalid states not being echoed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
Round-2 review fixes: converter tests for extractTags, a null filter
value matches any value (as an empty one) instead of failing, and the
docs say that values keep their positions after an empty tag_key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
The patch coverage of Codecov needs both branches of the null checks
in zipTags.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
As the issue asks, more tag_values than tag_keys give 400, also empty
ones. The docs say that the state filter uses the state the response
reports, read with several requests to Kubernetes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
TES 1.1 narrows CANCELED to cancelled tasks whose resources are gone,
and adds CANCELING and PREEMPTED.

- A cancelled task is CANCELING while any of its jobs (taskmaster,
  executors, outputs filer) has a pod that hasn't ended, or one that
  Kubernetes counts as active; then CANCELED. Getting a single task now
  also reads the outputs filer's pods.
- Cancelling a CANCELING task answers 200 and patches nothing; a
  PREEMPTED task has ended and can't be cancelled.
- A failed executor is PREEMPTED if its pods have DisruptionTarget=True
  with PreemptionByScheduler, TerminationByKubelet,
  DeletionByTaintManager or EvictionByEvictionAPI, and every failed pod
  has it; if any failed executor failed otherwise, EXECUTOR_ERROR.
- The decision table of TaskStateResolverTest covers the new rules;
  docs/index.md describes them, and that Kubernetes deletes most
  disrupted pods soon, after which the task is EXECUTOR_ERROR.

Closes #144

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
From the review of the CANCELING state:

- Cancelling a CANCELING task labels a running taskmaster pod that
  lacks the label (labelling it failed before, or Kubernetes restarted
  the taskmaster), instead of answering 200 without effect.
- A pod still listed after its deletion time (the end of its grace
  period, e.g. on a node that is gone) counts as ended, so it doesn't
  keep a cancelled task CANCELING until the node is removed.
- Getting a task reads the outputs filer's pods only if the task is
  cancelled, the only rule that needs them.
- Tests: a failed pod without disruption next to a disrupted running
  one is EXECUTOR_ERROR; the tested disruption reasons are all of them;
  cancel-test helpers set the job status explicitly.
- docs/index.md: the deletion time, that the inputs filer isn't read,
  the re-labelling; the retries paragraph is its own paragraph again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
From the second review:

- Relabelling a running taskmaster pod of a CANCELING task skips a pod
  that can't be patched (e.g. gone in between), like pending pods, so
  the request still answers 200: the job's label decides.
- A pod counts as ended one minute after its deletion time, not right
  at it, to allow for clocks of TESK API and the API server that
  differ.
- TaskStateResolver.isLabelledCancelled holds the label check for jobs
  and pods.
- docs/index.md: rules 1 and 2 are short again; what keeps a task
  CANCELING has its own paragraph; paragraphs are re-wrapped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Resolve cancelled tasks as CANCELING until their jobs’ pods have ended, and classify disrupted executor failures as PREEMPTED.

  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolver.java L44-136, L161-168, L213-218 (+3 small edits)
  • src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java L215-225, L362-372, L392-428 (+4 small edits)

Define the Kubernetes pod phases used by the resolver to distinguish ended pods.

  • src/main/java/uk/ac/ebi/tsc/tesk/k8s/constant/K8sConstants.java L11-14

Documentation

Document the CANCELING and PREEMPTED state rules, cancellation behavior, and the state-filter reference.

  • docs/api.md L41-46
  • docs/index.md L130-140, L146-166, L171-179 (+3 small edits)

Tests

Update state-resolution tests to cover cancellation until pods end and the disruption criteria for PREEMPTED.

  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolverTest.java L161-176, L468-621, L684-735 (+8 small edits)

Adjust converter tests and expectations for tasks newly reported as CANCELING.

  • src/test/java/uk/ac/ebi/tsc/tesk/k8s/convert/TesKubernetesConverterTest.java L594, L620

Verify cancellation behavior for CANCELING tasks, outputs-filer pods, and ended PREEMPTED tasks.

  • src/test/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImplCancelTest.java L10-15, L27, L221-435

Update list-filter tests to expect CANCELING for tasks whose cancellation is still in progress.

  • src/test/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImplListTest.java L280, L300

Check integration filtering for CANCELING and confirm those tasks are not returned under CANCELED.

  • src/integration-test/java/uk/ac/ebi/tsc/tesk/NoAuthIT.java L345, L350-354

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 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 73.66%. Comparing base (cfd3cfe) to head (a400352).

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #151      +/-   ##
==========================================
+ Coverage   72.98%   73.66%   +0.68%     
==========================================
  Files          70       70              
  Lines        2946     3019      +73     
  Branches      330      345      +15     
==========================================
+ Hits         2150     2224      +74     
  Misses        655      655              
+ Partials      141      140       -1     

☔ 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 12, 2026 10:10
@sourcery-ai

sourcery-ai Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit a400352

#144 feat: report the CANCELING and PREEMPTED states · 5 of 6 met

# Requirement Status Notes
1 Add CANCELING and PREEMPTED to TesState. ✅ Met Both enum values are present.
2 Report CANCELING while a cancelled task still has active resources, then CANCELED. ✅ Met The resolver checks the taskmaster, executor, and outputs-filer jobs for active counts or pods that have not ended; the single-task path reads outputs-filer pods for cancelled tasks.
3 Cancelling a CANCELING task answers 200 OK and patches nothing. 🟡 Partly met The request returns successfully, but it labels pending or running taskmaster pods that lack the cancellation label. The PR description says this deviation was accepted by the maintainer.
4 Report PREEMPTED for disrupted failed executors, otherwise EXECUTOR_ERROR. ✅ Met The resolver recognizes all four disruption reasons and requires each failed executor to qualify; an executor failure without a recognized disruption remains EXECUTOR_ERROR.
5 Cover the new rules in TaskStateResolverTest's decision table. ✅ Met The table includes CANCELING outcomes for each job position and PREEMPTED executor outcomes; additional tests cover pod conditions and cancellation timing.
6 Update docs/index.md with the state rules, cancelling behavior, and eviction explanation. ✅ Met The documentation covers the revised state rules, cancellation lifecycle, and disruption reasons and pod-deletion behavior.

@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="src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java" line_range="401" />
<code_context>
+    private void labelPodAsCancelledIfPossible(String podName, String why) {
         try {
             this.kubernetesClientWrapper.labelPodAsCancelled(podName);
         } catch (KubernetesException e) {
             logger.info(
-                    "Pending pod {} of a cancelled task not labelled (HTTP {}); its job ends anyway",
</code_context>
<issue_to_address>
**Cancellation succeeds after label failure**

When the pod-label PATCH fails for a reason other than the pod being gone, `labelPodAsCancelledIfPossible` catches the `KubernetesException`, so `cancelTask` returns successfully without delivering the pod label and the taskmaster keeps running its executors.

Propagate Kubernetes errors other than a missing-pod error from `labelPodAsCancelledIfPossible` so `cancelTask` does not report success.

Also at `src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java:402-406`.
</issue_to_address>

### Comment 2
<location path="src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java" line_range="388" />
<code_context>
+        boolean running =
+                pod.getStatus() != null
+                        && PodPhase.RUNNING.getCode().equals(pod.getStatus().getPhase());
+        return running && !TaskStateResolver.isLabelledCancelled(pod.getMetadata());
     }

</code_context>
<issue_to_address>
**Replacement taskmaster misses cancellation**

When a repeated cancel arrives while a replacement taskmaster pod is pending, `isRunningAndNotLabelledCancelled` excludes that pod from the `cancelTask` stream, so no pod label is applied and the taskmaster continues processing after the pod starts.

Include pending replacement pods that lack the cancellation label when selecting pods to label.

Also at `src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java:351`.
</issue_to_address>

### Comment 3
<location path="src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolver.java" line_range="96" />
<code_context>
+     * canceling. The slack allows for clocks of TESK API and the API server that differ.
+     */
+    private static boolean hasEnded(V1Pod pod) {
+        if (pod.getStatus() != null && ENDED_POD_PHASES.contains(pod.getStatus().getPhase())) {
+            return true;
+        }
</code_context>
<issue_to_address>
**Terminal pods skip deletion grace**

When a cancelled pod reaches `Succeeded` or `Failed` before its deletion timestamp plus 60 seconds, `hasEnded` returns true for `Succeeded` or `Failed` before checking the deletion timestamp, so the resolver reports `CANCELED` while that pod is still within its deletion grace period and terminating.

When a pod has a deletion timestamp, apply the deletion-time grace rule before treating its phase as ended.
</issue_to_address>

### Comment 4
<location path="src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolver.java" line_range="103" />
<code_context>
+                Optional.ofNullable(pod.getMetadata())
+                        .map(V1ObjectMeta::getDeletionTimestamp)
+                        .orElse(null);
+        return deletion != null && deletion.plusSeconds(DELETION_SLACK_SECONDS).isBeforeNow();
+    }
+
</code_context>
<issue_to_address>
**Filtered state differs from response**

When A task has a pod whose deletion timestamp is within the one-minute cutoff of the two state-resolution calls, `listTasks` resolves state once to apply the filter, then the task converter resolves it again to build the response. If the deletion-time cutoff passes between those calls, a task can match `CANCELING` but be returned as `CANCELED` (or vice versa), contrary to the documented filter behavior.

Resolve each task's state once and reuse that value for both filtering and response conversion.
</issue_to_address>

### Comment 5
<location path="src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java" line_range="346-358" />
<code_context>
+        if (state == TesState.CANCELING) {
</code_context>
<issue_to_address>
**Repeated cancel patches pod**

The issue requires a `CANCELING` cancellation to patch nothing, but this branch labels a running taskmaster pod when its cancellation label is missing. Already-labeled pods are left untouched, but the requirement is not met in every case.
</issue_to_address>

Sourcery assessment

Approval pending. 5 findings to address first.

Blocking findings: src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java:401, src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java:388, src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolver.java:96, src/main/java/uk/ac/ebi/tsc/tesk/k8s/convert/TaskStateResolver.java:103, src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java:358


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

uniqueg and others added 4 commits November 12, 2026 11:20
From Sourcery: cancelling a CANCELING task also labels a pending
taskmaster pod without the label (e.g. a restarted taskmaster), and
only a pod that is gone (404) is skipped; other errors fail the
request, as only the pod's label stops the taskmaster.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMpmDCfbACLj3uy6xV
… feat/144-canceling-preempted

# Conflicts:
#	src/main/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImpl.java
…empted

# Conflicts:
#	docs/api.md
#	src/integration-test/java/uk/ac/ebi/tsc/tesk/NoAuthIT.java
#	src/test/java/uk/ac/ebi/tsc/tesk/tes/api/TasksApiControllerTest.java
#	src/test/java/uk/ac/ebi/tsc/tesk/tes/service/TesServiceImplListTest.java

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

New gaps against the linked issues

@uniqueg
uniqueg merged commit ec0fcf9 into dev Nov 12, 2026
34 checks passed
@uniqueg
uniqueg deleted the feat/144-canceling-preempted branch November 12, 2026 11:05
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.

feat: report the CANCELING and PREEMPTED states

1 participant