Skip to content

fix: task listing, timestamps and relay bugs - #238

Merged
uniqueg merged 12 commits into
devfrom
fix/task-listing-relay
Oct 22, 2026
Merged

uniqueg merged 12 commits into
devfrom
fix/task-listing-relay

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the bugs of task listing, timestamps and relaying found by the tests of #236.

Closes #208
Closes #165

  • Relay (B1): each TES instance gets its own copy of the validated task. TES instances other than Funnel get the URLs of inputs and outputs without user names and passwords. Inputs with content are kept. The read-only creation_time is no longer relayed.
  • Task listing (B2, S5, Next page cursor loop #165):
    • next_page_token is empty on the last page; before, it was the last task's identifier, so clients kept paging.
    • No matching task gives an empty page, not an error.
    • Invalid page tokens, page sizes and name prefixes with null characters give 400.
    • Pages have 256 tasks by default and at most 2047 (custom.controllers.list_tasks.default_page_size and max_page_size; validated, and max_page_size is at most 2047). The default was 5.
    • name_prefix is matched literally (re.escape), not as a regular expression.
  • BASIC view: it now leaves out task.logs.system_logs, task.logs.logs.stdout and task.logs.logs.stderr. Before, it projected paths that don't exist. The fallback view is MINIMAL, as in the spec (connexion already applied the spec default).
  • Timestamps (B3):
    • creation_time, start_time, end_time and forward_time are in UTC, in RFC 3339 format (utc_now()); they were local-time strings.
    • proTES sets creation_time and rejects tasks that set it (400), as the spec marks it read-only.
  • Cancel:
    • The remote identifier is stored in tes_endpoint.task_id, so tasks can be canceled with storeLogs.execution_trace: False too. That setting no longer writes a metadata dict that cancellation couldn't read.
    • Tasks stored by earlier versions are canceled through their last forward or their remote_task_id.
  • Docs: api.md, configuration.md and upgrading.md, including the behaviour changes below.

Behaviour changes

  • The default page size is 256 instead of 5. proTES doesn't start if default_page_size exceeds max_page_size.
  • Tasks that set creation_time are rejected with 400.
  • Times are UTC RFC 3339 strings. Tasks stored earlier are served as stored.

Verification

  • pytest: 148 tests pass with mongomock and with MongoDB 7 (MONGODB_TEST_URI). 23 of the new tests failed on the old code.
  • ruff check, ruff format --check, mypy pro_tes tests, ast-grep scan, semgrep --config=.semgrep and mkdocs build --strict are clean.
  • Reviews: adversarial (2 rounds) and quality review before pushing; their findings are fixed except those listed below.
  • CI: all checks pass (tests on Python 3.10 and 3.12, MongoDB 7.0, Compose smoke test, docs, static analysis, CodeQL).

Declined review findings

  • Default view changes from BASIC to MINIMAL (breaking): it doesn't change. Connexion applies the spec default (MINIMAL), so the old BASIC fallback in the code was never used. A test now pins the default.
  • Restoring config changed in tests: not needed, because init_app() builds a new configuration for each app fixture.
  • Cancel tasks that have no remote identifier locally: tried and reverted. Tasks get cancelable states only from the TES instance they were forwarded to, so such a task is a corrupt record, and canceling it only locally could leave a task running remotely. The cancel fails (500) as before.
  • Sourcery: end_time set at forwarding, before the task finishes: this PR doesn't change when it is set, only its format. The log's start_time and end_time have always been proTES's own relay times (receipt and forwarding). See the follow-ups.
  • Moving _page_size and _remote_task_id next to the other private helpers: skipped to keep the diff small.

Follow-ups (out of scope)

  • Should the task log's start_time and end_time be the backend's times instead of proTES's relay times?
  • The backend's state fetched right after relaying is discarded: the task stays UNKNOWN until the Celery worker sets it.
  • The unique index of tasks is on task_id/worker_id, but the field is task.id, so duplicate generated task IDs are never detected.

🤖 Generated with Claude Code

uniqueg and others added 11 commits October 22, 2026 22:42
Mirror the package in `tests/` and replace the tests that could not be
collected (`tests/unitTest`) and the integration tests against public
TES instances (`tests/test_integration`):

- conftest: real MongoDB via `MONGODB_TEST_URI` (databases dropped per
  test, refused if present), no network access except to it, no name
  resolution in the distance-based middleware
- TES endpoints with fake backends: relay, fallback to the next
  backend, failures, Funnel, views, cancellation
- task as received stored once and never changed (#142)
- Celery task: states, polling, retries, failures (#149)
- middleware handler and task distribution middlewares (#168)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run all tests in CI (no ignored directories), on Python 3.10 and 3.12,
and against MongoDB 7.0 (`MONGODB_TEST_URI`), with a stable "Run tests"
check, as in cloud-registry.

Replace the integration tests against public TES instances with a
Compose smoke test: a Compose override and config overlay
(`tests/smoke/`) relay tasks to a fake TES backend, and the job checks
that a task is relayed to it and tracked by the Celery worker until it
is complete.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: the Compose smoke checks move from the workflow to
`tests/smoke/check.sh`, which also runs locally; the network guard of the
tests also covers `socket.connect_ex()`; the docs describe the test
layout and the network guard, and require a standalone MongoDB for
`MONGODB_TEST_URI`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The middlewares of the config are lists of alternatives; the Celery
worker refused the flat list of the smoke test overlay. A test now
validates the overlay with the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- GET /tasks: empty `next_page_token` on the last page and empty pages
  instead of errors (#165); `400` for invalid page tokens and page
  sizes; empty tokens list the first page; page sizes default to 256
  and are capped at `max_page_size` (2047), as in the TES specification
- `name_prefix` matched literally (`re.escape()`), not as a regular
  expression
- relay: each backend gets the validated task, not a copy changed for
  another backend; credentials are stripped from input and output URLs
  field by field, keeping the objects and inputs with `content`
- times in UTC, in RFC 3339 format; `creation_time` set by proTES
- BASIC view without system logs and executor stdout/stderr (wrong
  projection paths)
- remote task ID stored in `tes_endpoint.task_id`, so that tasks can
  be canceled with `storeLogs.execution_trace: False` (stored a dict
  that cancellation couldn't read); earlier tasks use their last forward

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use the default view of the spec when no view is given, simplify the
list conversion, and test page size limits and the default view.
Document the creation_time rejection in the API docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Don't relay the read-only creation_time to TES instances, cancel tasks
stored without an execution trace by their remote_task_id, cancel tasks
that were not forwarded locally, and reject name prefixes with null
characters, which MongoDB refuses. Document the page size validation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cancelable states come only from the TES instance a task was forwarded
to, so a cancelable task without a remote identifier is an error, not a
task to cancel locally.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	docs/development.md
#	tests/conftest.py
#	tests/ga4gh/tes/test_server.py
#	tests/test_fixtures.py
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR fixes TES task listing and pagination edge cases, standardizes server-generated timestamps, isolates relay payload mutations with credential sanitization, and makes cancellation robust when execution tracing is disabled or records are from older versions. Configuration, API documentation, and extensive regression tests are updated to codify the new behavior.

Sequence diagram for isolated task relay and timestamp assignment

sequenceDiagram
    participant Client
    participant ProTES
    participant TES
    Client->>ProTES: POST /tasks
    ProTES->>ProTES: utc_now()
    ProTES->>ProTES: TesTask validation
    loop Each TES endpoint
        ProTES->>ProTES: deepcopy(payload_marshalled)
        alt Non-Funnel endpoint
            ProTES->>ProTES: _strip_credentials(task_relayed)
        end
        ProTES->>TES: create_task(task_relayed)
        TES-->>ProTES: remote_task_id
    end
    ProTES-->>Client: task identifier
Loading

Sequence diagram for cancellation with stored remote identifiers

sequenceDiagram
    participant Client
    participant ProTES
    participant TES
    Client->>ProTES: POST /tasks/{id}:cancel
    ProTES->>ProTES: _remote_task_id(document, db_document)
    alt Current record
        ProTES->>ProTES: Read tes_endpoint.task_id
    else Earlier record
        ProTES->>ProTES: Read last forward or remote_task_id
    end
    ProTES->>TES: cancel_task(remote_task_id)
    TES-->>ProTES: Cancellation result
    ProTES-->>Client: Task response
Loading

Flow diagram for validated task listing pagination

flowchart LR
    Request[GET /tasks] --> Validate[_page_size]
    Validate --> Filter[Literal name_prefix and page_token validation]
    Filter --> Query[Query newest tasks]
    Query --> Page[Return up to configured page size]
    Page --> Token{More tasks?}
    Token -->|Yes| Next[next_page_token = last returned task ID]
    Token -->|No| Empty[next_page_token = empty]
Loading

File-Level Changes

Change Details Files
Correct task pagination behavior, validation, literal prefix filtering, page-size configuration, and default view/projection handling.
  • Return empty-page tokens correctly and treat no matches as an empty result.
  • Validate page tokens, positive page sizes, null-containing prefixes, and default/max page-size relationships.
  • Escape name prefixes literally and enforce configured default and maximum page sizes.
  • Use the TES MINIMAL default view and correct BASIC exclusions for nested logs.
pro_tes/config_models.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/config.yaml
docs/api.md
docs/configuration.md
docs/upgrading.md
tests/ga4gh/tes/test_server.py
Make task timestamps server-generated UTC RFC 3339 values and prevent relaying the read-only creation timestamp.
  • Set creation, start, end, and forward times with a shared UTC timestamp helper.
  • Reject client-supplied creation_time and omit creation_time from validated relay payloads.
  • Document the timestamp format and migration behavior for legacy records.
pro_tes/ga4gh/tes/task_runs.py
pro_tes/utils/misc.py
docs/api.md
docs/upgrading.md
tests/ga4gh/tes/test_server.py
Isolate and sanitize relay payloads for each backend while preserving content-based inputs.
  • Deep-copy the validated task before each relay attempt so backend-specific mutations do not leak to later attempts.
  • Strip credentials from input/output URLs for non-Funnel backends while retaining input objects with content.
  • Add coverage for fallback relays, Funnel credential preservation, and per-backend payload independence.
pro_tes/ga4gh/tes/task_runs.py
docs/api.md
tests/ga4gh/tes/test_server.py
Persist remote task identifiers independently of execution tracing and support cancellation of legacy records.
  • Store the backend task ID in tes_endpoint.task_id for every forwarded task.
  • Resolve cancellation IDs from the new field, legacy forward metadata, or legacy remote_task_id metadata.
  • Preserve failure behavior for cancelable records with no remote identifier.
pro_tes/ga4gh/tes/models.py
pro_tes/ga4gh/tes/task_runs.py
docs/configuration.md
docs/upgrading.md
tests/ga4gh/tes/test_server.py
Expand regression coverage and remove the obsolete dateutil typing dependency.
  • Add endpoint tests covering listing, views, relay sanitization, timestamps, cancellation, configuration validation, and legacy compatibility.
  • Remove the unused dateutil type-stub dependency after replacing local-time parsing and formatting.
tests/ga4gh/tes/test_server.py
pyproject.toml

Assessment against linked issues

Issue Objective Addressed Explanation
#165 Return an empty next-page cursor when the task listing has no further tasks, so clients stop paging after the last page. ✅
#208 Make task listing handle empty results and pagination correctly, reject invalid page tokens and page sizes with 400, enforce configured page-size bounds, and match name prefixes literally. ✅
#208 Relay tasks to non-Funnel backends with credentials removed from URL fields while preserving input/output objects and content-only inputs, and give each backend an unchanged copy of the validated payload. ✅
#208 Store task creation, start, and end timestamps as timezone-aware UTC RFC 3339 strings. ✅

Possibly linked issues


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

@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 22: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 2 issues

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

## Individual Comments

### Comment 1
<location path="pro_tes/ga4gh/tes/task_runs.py" line_range="599" />
<code_context>
         """
-        time_now = datetime.now().strftime("%m-%d-%Y %H:%M:%S")
-        tes_endpoint_dict: dict[str, Any] = {"host": tes_url, "base_path": ""}
+        time_now = utc_now()
+        tes_endpoint_dict: dict[str, Any] = {
+            "host": tes_url,
</code_context>
<issue_to_address>
**End time precedes task completion**

When a backend accepts a task that is still running, `_update_doc_in_db` runs as soon as a backend accepts the task and assigns `utc_now()` to every log’s `end_time`, before the task has completed. The task is therefore served with a completion timestamp while it is still running.

Set `end_time` only when the task reaches a terminal state, using the backend’s completion time when available.
</issue_to_address>

### Comment 2
<location path="pro_tes/config_models.py" line_range="112" />
<code_context>

-    default_page_size: int = 5
+    default_page_size: PositiveInt = 256
+    max_page_size: PositiveInt = 2047
+
+    @model_validator(mode="after")
</code_context>
<issue_to_address>
**Oversized pages violate TES**

When an operator configures `max_page_size` above 2047 and a request has enough matching tasks, `_page_size` caps requests at `max_page_size`, so a configured value above 2047 lets `GET /tasks` return more tasks per page than the TES specification permits. Callers receive nonconforming pages.

Constrain `max_page_size` to at most 2047 during configuration validation.

Also at `pro_tes/ga4gh/tes/task_runs.py:685`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and when a non-Funnel backend rejects a task, the next Funnel backend now receives the original input and output URLs, including any embedded credentials; the previous relay path could leave those credentials stripped. Reverting stops future relays from doing this, but credentials already sent cannot be recalled.

Blocking findings: pro_tes/ga4gh/tes/task_runs.py:599, pro_tes/config_models.py:112


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

Comment thread pro_tes/ga4gh/tes/task_runs.py Resolved
Comment thread pro_tes/config_models.py Resolved
The TES specification allows pages of fewer than 2048 tasks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit abecef1 into dev Oct 22, 2026
12 checks passed
@uniqueg
uniqueg deleted the fix/task-listing-relay branch October 22, 2026 22:38
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: task listing, timestamps and relay bugs Next page cursor loop

1 participant