Skip to content

fix: cancel runs proWES lost track of - #183

Merged
uniqueg merged 4 commits into
devfrom
fix/176-cancel-lost-runs
Nov 18, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/176-cancel-lost-runs

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Since #175, POST /runs/{run_id}/cancel refuses all SYSTEM_ERROR runs with 409. proWES sets SYSTEM_ERROR itself when it gives up tracking a run (WES instance unreachable or answering errors for longer than polling_attempts, tracking exceeding timeout_job), without knowing the remote state, so such runs could not be canceled through proWES.

  • The run document records whether proWES itself set SYSTEM_ERROR (system_error_by_prowes): DbDocumentConnector.set_system_error() sets the state and the mark, update_run_state() (states reported by the WES instance) clears it. All places where proWES sets SYSTEM_ERROR (run request failures, attachment write failures, tracking failures) use set_system_error().
  • cancel_run forwards cancellations of runs that proWES itself set to SYSTEM_ERROR and that have a remote run; the stored state stays SYSTEM_ERROR (no worker tracks the run any longer). Other SYSTEM_ERROR runs keep getting 409: reported by the WES instance, failed before forwarding (no remote run), or stored by earlier versions without the mark.
  • Tracking time limit (custom.post_runs.timeout_job): the handler now decides by the stored state. Runs whose stored state is final (e.g., the limit is hit while the final run log is read) keep it instead of being set to SYSTEM_ERROR (which would now also make them cancelable); the handler covers the whole task, so a limit hit before polling no longer leaves the run INITIALIZING.
  • Docs: docs/api.md (Run states table and cancellation rules), docs/operations.md (Run tracking), docs/upgrading.md (Cancellation), and the 409 description in additions.openapi.yaml.

Verification

  • pytest --ignore=tests/test_chart.py: 538 passed; coverage report: 100 %.
  • CI: all checks passed on 4563710 (Lint, Test, Docs, Chart, Chart install, Smoke test, codecov, CI passed); see the checks of the latest commit.
  • Sourcery: two threads on the time-limit handler (stale local state; limit before the try), fixed in 4ca33eb with regression tests test_track_run_soft_time_limit_after_store and test_track_run_soft_time_limit_first_log.
  • Review: adversarial + quality reviewers, round 1; fixed the tracking time-limit overwrite (regression test test_track_run_soft_time_limit_final_log), the upgrade note (no backfill, mongosh query to list affected runs), 409 description, naming. Round 2 (both reviewers, no high/medium): the tracker now stores a new state before it counts as tracked (time limit during the write), docstring and doc wording fixes.
  • New tests: forwarded cancellation of a proWES SYSTEM_ERROR with remote run; 409 for SYSTEM_ERROR reported by WES, unmarked (earlier versions), null mark, and proWES SYSTEM_ERROR without endpoint or remote run; the mark set by set_system_error() and cleared by update_run_state(); the tracker leaves a remote SYSTEM_ERROR unmarked; existing SYSTEM_ERROR tests of POST /runs and the tracker assert the mark.
  • pre-commit run --all-files: all hooks pass except actionlint, which can't run locally (mise has no shellcheck/actionlint version set); this PR changes no workflows, CI runs it.
  • mkdocs build --strict: passed.
  • Not run locally: tests/test_chart.py (needs helm dependency build; this PR doesn't touch the chart).

Declined review findings

  • Adversarial (medium): cancel_run ignores error responses of the WES instance and answers 200. The bug is older and already tracked in fix: cancel runs at the backend #86 (scope addition there); documented in docs/api.md with a link to fix: cancel runs at the backend #86 instead.
  • Quality (low): no end-to-end test of pro_wes/tasks/utils.py clearing the mark, nor of repeated cancels; the connector tests cover the clearing, and repeated cancels take the same path.

Open questions

None.

Closes #176

🤖 Generated with Claude Code

uniqueg and others added 2 commits November 18, 2026 23:36
proWES now records in the run document whether it set SYSTEM_ERROR
itself (system_error_by_prowes, via DbDocumentConnector.
set_system_error()) or the WES instance reported it (update_run_state()
clears the mark). POST /runs/{run_id}/cancel forwards cancellations of
runs that proWES itself set to SYSTEM_ERROR (e.g., the WES instance was
unreachable for too long, or tracking exceeded timeout_job) if they
have a remote run, as they may still be running; the stored state is
kept. Other SYSTEM_ERROR runs, including those stored by earlier
versions without the mark, keep getting 409.

Docs: run states, run tracking and the upgrade note on cancellation.

Closes #176

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes (#176):

- Runs that have finished when tracking hits custom.post_runs.
  timeout_job (e.g., while the final run log is read) keep their final
  state instead of being set to SYSTEM_ERROR, which would now also
  make them cancelable.
- Upgrade note: no backfill of system_error_by_prowes for runs of
  earlier versions, and a mongosh query to list them; reflowed.
- API docs: proWES still answers 200 to forwarded cancellations that
  the WES instance refuses (#86).
- Clearer 409 description and local name in cancel_run; keyword-only
  arguments of DbDocumentConnector._set_state().

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg self-assigned this Nov 18, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Persist whether proWES itself set SYSTEM_ERROR, and clear that marker whenever a state reported by the WES instance is stored.

  • pro_wes/utils/db.py L72-75, L86-112

Data structures

Add the persisted provenance marker to the run document model so callers can distinguish proWES-generated errors from remote ones.

  • pro_wes/ga4gh/wes/models.py L417-419, L429-431, L441

API

Allow cancellation of proWES-marked SYSTEM_ERROR runs only when a remote run exists, while leaving their stored state unchanged.

  • pro_wes/ga4gh/wes/workflow_runs.py L414-417, L471-475, L480-484 (+1 small edits)

Implementation

Mark errors caused by failed forwarding or attachment handling as proWES-generated, and handle tracking timeouts across the task while preserving an already-final stored state.

  • pro_wes/ga4gh/wes/workflow_runs.py L158, L201-204
  • pro_wes/tasks/track_run_progress.py L91-115, L159-164, L171-192 (+4 small edits)

Documentation

Explain the revised cancellation eligibility, timeout behavior, and upgrade implications for older unmarked SYSTEM_ERROR records.

  • docs/api.md L111, L125-151
  • docs/operations.md L33-37
  • docs/upgrading.md L187-189, L196-219
  • pro_wes/api/additions.openapi.yaml L136-138

Tests

Verify provenance marking, cancellation outcomes, and final-state preservation when tracking reaches its time limit.

  • tests/ga4gh/wes/test_run_request_limits.py L430
  • tests/ga4gh/wes/test_workflow_runs.py L878-946 (+3 small edits)
  • tests/tasks/test_track_run_endpoint.py L91
  • tests/tasks/test_track_run_progress.py L14-17, L173-184, L326-458 (+4 small edits)
  • tests/test_utils.py L74-94

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a2542ce) to head (4ca33eb).
⚠️ Report is 2 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #183   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           19        19           
  Lines          978       993   +15     
=========================================
+ Hits           978       993   +15     

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

Review fixes, round 2 (#176): the tracker stores a new state before it
counts as tracked, so that a time limit hit during the write still sets
SYSTEM_ERROR. Docstring of the time limit, the exception for proWES's
own SYSTEM_ERRORs in the upgrade note, and reflowed paragraphs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review November 18, 2026 23:19
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 4ca33eb

#176 fix: allow canceling runs proWES failed to track · 4 of 4 met

# Requirement Status Notes
1 Record whether SYSTEM_ERROR was set by proWES or reported by the WES instance. ✅ Met set_system_error() records proWES-originated errors, while update_run_state() clears the mark for states reported by the WES instance.
2 Forward cancellations of proWES-set SYSTEM_ERROR runs that have a remote run; keep refusing other SYSTEM_ERROR runs. ✅ Met cancel_run forwards marked runs with a remote endpoint and refuses unmarked or WES-reported SYSTEM_ERROR runs.
3 Test both kinds of SYSTEM_ERROR. ✅ Met Tests cover proWES-marked errors, WES-reported errors, and other refused cases, including unmarked earlier-version records.
4 Update the API Run states and upgrading documentation. ✅ Met The changes document cancellation behavior in docs/api.md and upgrade handling in docs/upgrading.md.

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="pro_wes/tasks/track_run_progress.py" line_range="148-149" />
<code_context>
             if response.state != run_state:
+                # stored first, so that a state counts as tracked only once
+                # it is stored (cf. the time limit below)
+                db_client.update_run_state(state=response.state.value)
                 run_state = response.state
-                db_client.update_run_state(state=run_state.value)

</code_context>
<issue_to_address>
**Finished runs become cancelable**

When a soft-time-limit signal arrives after the terminal-state MongoDB write commits but before `run_state` is assigned, the `SoftTimeLimitExceeded` handler sees the previous nonfinal `run_state`, calls `set_system_error()`, and overwrites the terminal MongoDB state, so callers see `SYSTEM_ERROR` and can cancel a finished run.

Assign `response.state` to `run_state` before writing it to MongoDB so the timeout handler sees the terminal state.
</issue_to_address>

### Comment 2
<location path="pro_wes/tasks/track_run_progress.py" line_range="113" />
<code_context>

     # track workflow run progress, from the state stored last (so that a
     # remote `UNKNOWN` is stored, too)
+    run_state: State = State.INITIALIZING
     try:
-        run_state: State = State.INITIALIZING
</code_context>
<issue_to_address>
**Timeout leaves run initializing**

When the soft-time-limit signal is delivered between the assignment and entering the `try`, the assignment executes outside the `try` that handles `SoftTimeLimitExceeded`, so a timeout delivered after it and before entering the `try` escapes without `set_system_error()`. The task ends while the stored run remains `INITIALIZING` instead of recording that tracking stopped.

Move the `run_state` initialization inside the `try` so this timeout is handled.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and a run marked as a proWES-set SYSTEM_ERROR can now have its cancellation forwarded to the remote WES, which may terminate work that is still running. Reverting stops future cancellations but cannot undo one already accepted by the WES instance.

Blocking findings: pro_wes/tasks/track_run_progress.py:149, pro_wes/tasks/track_run_progress.py:113


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

Comment thread pro_wes/tasks/track_run_progress.py Resolved
Comment thread pro_wes/tasks/track_run_progress.py Resolved
Sourcery review (#176): the soft time limit may be hit anywhere in the
task, also between storing a state and tracking it. The handler now
reads the stored state and keeps it if it is final; otherwise it sets
SYSTEM_ERROR. The handler covers the whole task, so a limit hit before
polling (e.g., during the first run-log fetch) no longer leaves the run
INITIALIZING.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 94c8b82 into dev Nov 18, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/176-cancel-lost-runs branch November 18, 2026 23:41
uniqueg added a commit that referenced this pull request Nov 19, 2026
* feat!: require access tokens from clients

The WES API now requires access tokens of the trusted issuers
(`security.auth`, none by default), as in proTES; `GET /service-info`,
the specification and the Swagger UI stay public. Requests without a
valid token get `401` with a Bearer challenge.

Each run belongs to the caller that created it: the subject of its
token, namespaced by its issuer (`<issuer>|<subject>`, or the issuer's
`namespace`), as FOCA 0.23 does, so that owners survive that upgrade.
The controllers set it as `user_id`, replacing any value of the
request, so that the existing owner checks of the run store apply.

A warning is logged on startup if no issuer is trusted. The tests trust
FOCA's local identity provider and send its tokens by default.

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

* test(smoke): run with authentication on

The fake WES is also the identity provider of the smoke test: it serves
its discovery document and keys over HTTPS below `/oidc/`, and tokens of
any user at `GET /oidc/token` (`fake_wes.py token <user>`). The test
sends them with every request but the service info, and checks `401`
without and with an invalid token, and that another user can't list,
read or cancel the runs of the first.

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

* test: own the runs of the merged cancel tests

The runs that the tests of #183 store get the owner of the test user,
as the run store now checks owners. Also from the review: tests of
`_set_owner`, of `user_id` in requests and of the startup check; no
private FOCA helper in `TokenClient`; uniform `Raises` of the
controllers; clearer comments and docs.

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

* fix(chart): warn without token issuers

The chart's notes, README, deployment and development docs no longer say
that the WES API is served without authentication; the notes warn while
`config.security.auth.issuers` is unset instead. The fake WES of the
smoke test gets a key ID per start, so that proWES fetches its new key
after a restart, and tokens that last an hour.

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

* docs: rewrap auth paragraphs

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

* fix: refuse owners of issuers with a separator

Issuers are the namespace of their subjects by default, and FOCA 0.22
refuses `|` in explicit namespaces only, so an issuer URL with `|` could
yield the same owner as another issuer's subject with `|`. Such issuers
own no runs now. Also test that tokens without a subject get `401`.

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

* docs: clarify owner migration and namespaces

Give the owner for migrated runs per configured namespace (also bare),
say to scale proWES down before upgrading so that old pods create no
ownerless runs, and that namespaces must differ and lack `|`.

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

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
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: allow canceling runs proWES failed to track

1 participant