Skip to content

fix: refuse cancellation of finished runs - #175

Merged
uniqueg merged 4 commits into
devfrom
fix/171-refuse-finished-cancel
Nov 18, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/171-refuse-finished-cancel

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

POST /runs/{run_id}/cancel now checks the stored state of the run before contacting the WES instance:

  • Forwarded: runs in a cancelable state (State.is_cancelable: QUEUED, INITIALIZING, RUNNING, PAUSED), and runs of state UNKNOWN that have a remote run. proWES stores runs as UNKNOWN until a worker starts tracking them (which can take long when all worker slots are busy), and a WES instance may report UNKNOWN for a live run, so these stay cancelable.
  • Refused with 409 Conflict as problem details ("The run can't be canceled in its current state."; new RunNotCancelable, derived from FOCA's Conflict), without contacting the WES instance: finished runs (COMPLETE, EXECUTOR_ERROR, SYSTEM_ERROR, CANCELED, PREEMPTED), CANCELING, and UNKNOWN runs not forwarded yet. Stored states that are missing, null or invalid count as UNKNOWN.
  • Cancelable runs without a remote run (no, null or incomplete wes_endpoint) get 500 with WesEndpointProblem instead of the generic 500 of a KeyError (the issue names this case). Documented in docs/upgrading.md.
  • The access check still comes first, so other users' runs get 403 whatever their state.
  • 409 is declared for POST /runs/{run_id}/cancel in additions.openapi.yaml (proWES extension; added to ALLOWED_DEVIATIONS and the deviations table of docs/api.md).
  • Docs: docs/api.md (Run states table gets a "Cancelable" column; cancellation rules, including the limit below; pointer from Errors; endpoint table), docs/upgrading.md (new "Cancellation" section under 0.20.0; 409 among the declared statuses).
  • Smoke test: canceling the completed run expects 409.

Known limit, documented: runs that proWES itself sets to SYSTEM_ERROR because it fails to track them may still run at the WES instance; their cancellations are refused too (the issue lists SYSTEM_ERROR as finished). Users cancel them at the WES instance. A follow-up issue is drafted for the main session.

Verification

  • Regression tests first (tests/ga4gh/wes/test_workflow_runs.py: each refused state with a remote run, UNKNOWN/missing/null/invalid state without remote run, each cancelable state and each unknown-state variant with a remote run, missing/null/incomplete endpoint; tests/ga4gh/wes/test_error_responses.py: 409 as declared): 11 failed before the fix, all pass after.
  • coverage run -m pytest --deselect tests/test_chart.py: 366 passed; coverage report: 100 %. After merging dev: 404 passed, 100 %. The chart tests (tests/test_chart.py) don't run locally (library chart not built, helm dependency build); they run in CI.
  • pre-commit run --all-files: all hooks pass except actionlint, which fails locally only because the local shellcheck shim has no version set (no workflow is changed); it runs in CI.
  • mkdocs build --strict: passes.
  • Smoke test (tests/smoke/check.sh, Docker Compose) not run locally.
  • CI (after merging dev with feat!: configure WES backends #173): all checks pass (Lint, Docs, Test, Chart, Chart install, Smoke test, codecov patch/project, CI passed; Push image skipped as intended).
  • Reviews: adversarial-reviewer and quality-reviewer (round 1), adversarial-reviewer (round 2), Sourcery (endpoint values with null now count as no remote run, upgrade note corrected; beb3bf1: 408 passed, 100 %).

Declined review findings

  • Move the 500 for runs without remote run to its own issue (quality, medium): kept, as the issue names this case ("runs without a remote run ... may fail on the missing wes_endpoint"); now documented in docs/upgrading.md.

  • Forward cancellations of SYSTEM_ERROR runs (adversarial, medium): the issue lists SYSTEM_ERROR as a finished state to refuse; telling proWES-set from WES-reported SYSTEM_ERROR needs a new field, so it is documented as a limit and drafted as a follow-up issue.

  • Check-then-act race between reading the state and forwarding (adversarial, low): unavoidable without a conditional update, harmless; the docs say the check uses the state stored at the time of the request.

  • Extract a helper for inserting run documents in tests (quality, low): the documents differ per test; a shared REMOTE_ENDPOINT constant covers the repetition.

  • Sourcery: recover runs whose remote identifier was never stored (pre-existing, needs a change of forwarding); uniqueness of run identifiers in MongoDB (pre-existing, the unique index is on top-level run_id/task_id, not run_log.run_id; follow-up issue drafted); TypeError for unhashable states (Enum raises ValueError, covered by a test).

Open questions

None.

Closes #171

🤖 Generated with Claude Code

uniqueg and others added 2 commits November 18, 2026 16:00
POST /runs/{run_id}/cancel now checks the stored state of the run
(State.is_cancelable) before contacting the WES instance. Runs that
aren't cancelable (finished, CANCELING, UNKNOWN) get 409 Conflict as
problem details (RunNotCancelable); cancelable runs without a remote
run get 500 (WesEndpointProblem) instead of a KeyError.

Declares the 409 in additions.openapi.yaml (allowed deviation), adds a
smoke check, and documents it in docs/api.md and docs/upgrading.md.

Closes #171

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Runs stay UNKNOWN after forwarding until a worker starts tracking them,
and the WES instance may report UNKNOWN for live runs: forward their
cancellations once they have a remote run; refuse only runs not
forwarded yet. Stored states that are null or invalid count as UNKNOWN.

Docs: the UNKNOWN window, the limit for runs that proWES itself set to
SYSTEM_ERROR, the new 500 for runs without remote run, and a pointer
from Errors. Drops a test that only restated State.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Declare the new 409 Conflict response for cancellation in the OpenAPI additions and include it in the specification-deviation check.

  • pro_wes/api/additions.openapi.yaml L131-141
  • tests/ga4gh/wes/test_spec.py L133-135

Introduce RunNotCancelable as a 409 Conflict problem-details error for cancellation requests.

  • pro_wes/exceptions.py L124-131, L252-256 (+2 small edits)

Implementation

Check stored state and usable remote endpoint before forwarding cancellation, allowing forwarded UNKNOWN runs and refusing non-cancelable runs.

  • pro_wes/ga4gh/wes/workflow_runs.py L413-417, L429-432, L459-488 (+3 small edits)

Documentation

Document cancellation eligibility, the new conflict response, missing-endpoint behavior, and the known limit for proWES-set SYSTEM_ERROR runs.

  • docs/api.md L101-113, L122-139 (+4 small edits)
  • docs/upgrading.md L108-127

Tests

Exercise the declared cancellation error and verify forwarding or refusal across run states and missing or incomplete remote endpoints.

  • tests/ga4gh/wes/test_error_responses.py L17-21, L267-279
  • tests/ga4gh/wes/test_workflow_runs.py L25, L706-860

Update the smoke check to expect 409 when canceling a completed run.

  • tests/smoke/check.sh L108-109

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

…d-cancel

# Conflicts:
#	docs/api.md
#	pro_wes/ga4gh/wes/workflow_runs.py
@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (f4a99d9) to head (beb3bf1).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #175   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           19        19           
  Lines          942       955   +13     
=========================================
+ Hits           942       955   +13     

☔ 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 18, 2026 18:01
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit beb3bf1

#171 fix: refuse cancellation of finished runs · 3 of 3 met

# Requirement Status Notes
1 Refuse cancellation of finished runs with an error, without contacting the WES instance. ✅ Met cancel_run rejects non-cancelable states before creating the WES client or forwarding cancellation.
2 Document the cancellation behavior in docs/api.md (Run states) and docs/upgrading.md. ✅ Met docs/api.md documents cancelable states and refusal behavior; docs/upgrading.md describes the cancellation change.
3 Test cancellation of each finished state and of a cancelable state. ✅ Met Parameterized tests cover every non-cancelable state, including each finished state, and each cancelable state.

@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_wes/ga4gh/wes/workflow_runs.py" line_range="460" />
<code_context>
         )

+        wes_endpoint: dict[str, str] = document.get("wes_endpoint") or {}
+        has_remote_run = {"host", "base_path", "run_id"} <= wes_endpoint.keys()
+
+        # ensure workflow run is cancelable; runs stored without (valid) state
</code_context>
<issue_to_address>
**Cancellation reports success without canceling**

When a stored `wes_endpoint` has all required keys but a required value is null or empty, `has_remote_run` checks only for keys, so `cancel_run` treats the endpoint as usable. A null `run_id` is sent in the request path and the returned WES error is ignored, while a null `base_path` fails during client construction; callers can see success without cancellation or an error instead of `WesEndpointProblem`.

Set `has_remote_run` only when the required endpoint values are usable, and reject incomplete endpoints with `WesEndpointProblem`.
</issue_to_address>

### Comment 2
<location path="pro_wes/ga4gh/wes/workflow_runs.py" line_range="467-468" />
<code_context>
+        # cancelable once they have a remote run (e.g., forwarded, but not yet
+        # tracked, or reported as `UNKNOWN` by the WES instance)
+        try:
+            state = State(document["run_log"].get("state") or State.UNKNOWN)
+        except ValueError:
+            state = State.UNKNOWN
+        if not (state.is_cancelable or (state is State.UNKNOWN and has_remote_run)):
</code_context>
<issue_to_address>
**Invalid stored state causes cancellation failure**

When `run_log.state` contains an unhashable value such as a list or document, `State(...)` raises `TypeError`, but the handler catches only `ValueError`; cancellation returns 500 instead of treating the state as `UNKNOWN` and applying the remote-run check.

Catch `TypeError` as well as `ValueError` and treat either as `State.UNKNOWN`.
</issue_to_address>

### Comment 3
<location path="pro_wes/ga4gh/wes/workflow_runs.py" line_range="470-472" />
<code_context>
+            state = State(document["run_log"].get("state") or State.UNKNOWN)
+        except ValueError:
+            state = State.UNKNOWN
+        if not (state.is_cancelable or (state is State.UNKNOWN and has_remote_run)):
+            logger.error("Run '%s' not cancelable in state '%s'.", run_id, state.value)
+            raise RunNotCancelable
+
+        # ensure workflow run has a remote run
</code_context>
<issue_to_address>
**Orphaned runs appear unforwarded**

When the process stops after the WES accepts `post_run` but before `upsert_fields_in_root_object` stores the remote run ID, the WES can accept the run before proWES stores its remote run ID; if the API process stops in that gap, the stored run remains `UNKNOWN` without a remote endpoint. `cancel_run` then raises `RunNotCancelable` with `409`, so the caller cannot cancel the live remote run through proWES.

Add a recovery or idempotent forwarding mechanism that can discover and persist the remote run ID before treating an `UNKNOWN` run without an endpoint as unforwarded.
</issue_to_address>

### Comment 4
<location path="pro_wes/ga4gh/wes/workflow_runs.py" line_range="470" />
<code_context>
+            state = State(document["run_log"].get("state") or State.UNKNOWN)
+        except ValueError:
+            state = State.UNKNOWN
+        if not (state.is_cancelable or (state is State.UNKNOWN and has_remote_run)):
+            logger.error("Run '%s' not cancelable in state '%s'.", run_id, state.value)
+            raise RunNotCancelable
</code_context>
<issue_to_address>
**Cancellation reaches another run**

When two proWES instances share MongoDB but use separate storage paths and generate the same run ID, `find_one` can return either document for a duplicated run ID, so the state check and subsequent endpoint lookup can forward cancellation to a different run than the caller intended.

Enforce uniqueness of `run_log.run_id` in MongoDB and retry insertion when that constraint is hit.
</issue_to_address>

### Comment 5
<location path="docs/upgrading.md" line_range="121" />
<code_context>
+`SYSTEM_ERROR`, `CANCELED`, `PREEMPTED`), runs being canceled
+(`CANCELING`) and runs of state `UNKNOWN` that aren't forwarded yet.
+Before, every cancellation was forwarded, and the response was whatever
+the WES instance answered. Runs without a run at the WES instance (no or
+incomplete `wes_endpoint`) now get `500` with the problem details of
+`WesEndpointProblem` ("No/few requirements provided for WES endpoint.";
</code_context>
<issue_to_address>
**Migration notes misstate old responses**

The old controller ignored the value returned by `WesClient.cancel_run` and returned its own run ID, even when the WES response parsed as an error. This sentence therefore gives upgrading clients a false account of the response behavior they previously observed.

Clarify that cancellations were forwarded before, but proWES returned its own run-ID response and did not propagate structured WES error responses.
</issue_to_address>

Sourcery assessment

Approval pending. 4 findings to address first.

Blocking findings: pro_wes/ga4gh/wes/workflow_runs.py:460, pro_wes/ga4gh/wes/workflow_runs.py:468, pro_wes/ga4gh/wes/workflow_runs.py:472, pro_wes/ga4gh/wes/workflow_runs.py:470


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

Comment thread pro_wes/ga4gh/wes/workflow_runs.py Resolved
Comment thread pro_wes/ga4gh/wes/workflow_runs.py Resolved
Comment thread pro_wes/ga4gh/wes/workflow_runs.py Resolved
Comment thread pro_wes/ga4gh/wes/workflow_runs.py Resolved
Comment thread docs/upgrading.md Resolved
A stored wes_endpoint counts as a remote run only if host and run_id
are set and base_path isn't null; before, keys with null values passed
the check and were forwarded. Also corrects the upgrade note on how
cancellations were answered before (200 even on WES errors).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 0ebcc03 into dev Nov 18, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/171-refuse-finished-cancel branch November 18, 2026 18:29
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: refuse cancellation of finished runs

1 participant