Repository navigation
fix: refuse cancellation of finished runs - #175
Conversation
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]>
Reviewer's GuideAPIDeclare the new
Introduce
ImplementationCheck stored state and usable remote endpoint before forwarding cancellation, allowing forwarded
DocumentationDocument cancellation eligibility, the new conflict response, missing-endpoint behavior, and the known limit for proWES-set
TestsExercise the declared cancellation error and verify forwarding or refusal across run states and missing or incomplete remote endpoints.
Update the smoke check to expect
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
…d-cancel # Conflicts: # docs/api.md # pro_wes/ga4gh/wes/workflow_runs.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit beb3bf1 #171 fix: refuse cancellation of finished runs · 3 of 3 met
|
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_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
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]>
Summary
POST /runs/{run_id}/cancelnow checks the stored state of the run before contacting the WES instance:State.is_cancelable:QUEUED,INITIALIZING,RUNNING,PAUSED), and runs of stateUNKNOWNthat have a remote run. proWES stores runs asUNKNOWNuntil a worker starts tracking them (which can take long when all worker slots are busy), and a WES instance may reportUNKNOWNfor a live run, so these stay cancelable.409 Conflictas problem details ("The run can't be canceled in its current state."; newRunNotCancelable, derived from FOCA'sConflict), without contacting the WES instance: finished runs (COMPLETE,EXECUTOR_ERROR,SYSTEM_ERROR,CANCELED,PREEMPTED),CANCELING, andUNKNOWNruns not forwarded yet. Stored states that are missing,nullor invalid count asUNKNOWN.nullor incompletewes_endpoint) get500withWesEndpointProbleminstead of the generic500of aKeyError(the issue names this case). Documented indocs/upgrading.md.403whatever their state.409is declared forPOST /runs/{run_id}/cancelinadditions.openapi.yaml(proWES extension; added toALLOWED_DEVIATIONSand the deviations table ofdocs/api.md).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;409among the declared statuses).409.Known limit, documented: runs that proWES itself sets to
SYSTEM_ERRORbecause it fails to track them may still run at the WES instance; their cancellations are refused too (the issue listsSYSTEM_ERRORas finished). Users cancel them at the WES instance. A follow-up issue is drafted for the main session.Verification
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:409as declared): 11 failed before the fix, all pass after.coverage run -m pytest --deselect tests/test_chart.py: 366 passed;coverage report: 100 %. After mergingdev: 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 exceptactionlint, which fails locally only because the localshellcheckshim has no version set (no workflow is changed); it runs in CI.mkdocs build --strict: passes.tests/smoke/check.sh, Docker Compose) not run locally.devwith 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).adversarial-reviewerandquality-reviewer(round 1),adversarial-reviewer(round 2), Sourcery (endpoint values withnullnow count as no remote run, upgrade note corrected; beb3bf1: 408 passed, 100 %).Declined review findings
Move the
500for 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 missingwes_endpoint"); now documented indocs/upgrading.md.Forward cancellations of
SYSTEM_ERRORruns (adversarial, medium): the issue listsSYSTEM_ERRORas a finished state to refuse; telling proWES-set from WES-reportedSYSTEM_ERRORneeds 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_ENDPOINTconstant 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, notrun_log.run_id; follow-up issue drafted);TypeErrorfor unhashable states (Enum raisesValueError, covered by a test).Open questions
None.
Closes #171
🤖 Generated with Claude Code