Skip to content

refactor!: upgrade to FOCA 0.15 - #219

Merged
uniqueg merged 7 commits into
devfrom
refactor/foca-0-15
Oct 22, 2026
Merged

uniqueg merged 7 commits into
devfrom
refactor/foca-0-15

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Upgrades proTES to FOCA 0.15, following FOCA's migration guides for 0.14 and 0.15. foca>=0.12.1 had no upper bound, so fresh installs already got FOCA 0.15, with which proTES did not start (removed config options, pydantic 2) and CI was bound to fail; only the 2022 base image kept the image working.

  • Dependencies: foca>=0.15.0,<0.16, connexion>=2.15.1,<3, py-tes>=1.1; no pymongo pin; test and typing packages moved to the dev requirements.
  • Image: elixircloud/foca:0.15.0-py3.12, pinned by digest; installs as root, runs as UID 1000 (FOCA image). Dependency wheels are built in a build stage with gcc, as ip2geotools requires typed-ast, which has no wheels for Python 3.12; the final image has no build tools.
  • Config: no removed options; server.debug: False (S7); request bodies limited to 1 MiB (max_content_length, S9); problem details (title, status, detail) sent as application/json (GA4GH); literal task ID charset; fully qualified controller module (pro_tes.ga4gh.tes.server).
  • Service info: served by FOCA (foca.api.service_info) from service_info.service, with the version of the installed package; the app's controller, its service_info collection and custom.service_info are gone. The values are unchanged for now; neutral defaults follow in fix: use neutral service-info defaults #205.
  • Middleware management API: no longer registered, as its controller module doesn't exist (B4); it comes back with feat!: run task plugins with FOCA #194.
  • Code: pydantic 2 (ConfigDict, RootModel, model_dump(mode="json"), fixed defaults of TesExecutor.command and TesTask.executors, B5); foca.get_config() and a typed get_custom_config(); foca.get_collection() in the Celery task instead of FOCA's removed private client factory and the hard-coded database taskStore (B6; MONGO_DBNAME applies now); the worker validates the custom config too.
  • fix: infinite loop with jsonschema>3.2.0 #173: logs[].metadata.forwarded_to is a non-recursive list of tesForward (id, url, forward_time in RFC 3339), in the order of forwarding; proTES appends its forward and cancels tasks at the last one. Forwards nested by earlier versions (stored tasks, or other instances running them) are read and served as lists (without forward_time), so such tasks can still be canceled and tracked.
  • Output sizes: py-tes returns size_bytes as integers, which pydantic 2 rejects for the string field; the converter converts them (found in review: the Celery task failed for every finished task with outputs).
  • fix: add ignore_error executor field #176: ignore_error of executors is relayed to backends and kept when converting backend tasks.
  • Update Mongo image version #171: MongoDB 7.0 in Compose.
  • Specs: the GA4GH service info schemas are copied into additions.openapi.yaml (renamed from additional_logs.yaml), so startup no longer fetches them from GitHub (needed to test without network; as in cloud-registry#93).
  • Tests and CI: first tests in tests/ (app startup and config, service info, problem details, body limit, task create/list/get/cancel with a fake backend, the Celery task with and without MONGO_DBNAME, models and forwarding log); CI lints on Python 3.10 and 3.12 and runs them. The tests in tests/unitTest stay uncollectable until test: add app test harness and fix the tests #207.

Deviation from the issue: security.auth.issuers stays empty instead of listing LS Login, because FOCA 0.15 refuses issuers without an audience, and authentication is still disabled (disable_auth: True). LS Login and the audience come with #212.

Closes #203, closes #171, closes #173, closes #176. Supersedes #172 (to be closed after merge).

Upgrade notes (breaking changes)

  • Errors are problem details ({"title", "status", "detail"}, application/json) instead of {"message", "code"}.
  • The service info is configured in service_info.service (FOCA) instead of custom.service_info, and is no longer stored in MongoDB; the service_info collection can be dropped.
  • logs[].metadata.forwarded_to is a list of {id, url, forward_time} instead of a nested tesNextTes object; tasks stored with the old shape are served as lists (without forward_time).
  • Configs must apply FOCA 0.15's changes (e.g., exceptions.mapping, no validation_methods, validation_checks, environment, use_reloader); with MONGO_DBNAME set, the Celery worker now uses that database too.
  • Request bodies larger than 1 MiB are rejected (413).
  • The middleware management API (/protes/v1/middlewares) is not served.
  • Compose: MongoDB 7.0 can't open data directories of MongoDB 3.6; remove PROTES_DATA_DIR/db (default ../data/pro_tes/db) or upgrade it one major version at a time.

How it was verified

  • pytest tests --ignore=tests/unitTest --ignore=tests/test_integration: 20 passed on Python 3.10 and 3.12 (fresh venvs from requirements*.txt, without network).
  • flake8 pro_tes/ setup.py, pylint pro_tes/ setup.py (10.00/10), mypy pro_tes/: clean on Python 3.10 and 3.12.
  • Not run locally: Docker Compose and the integration tests (docker run isn't available here).
  • CI (proTES checks, CodeQL): all green on the final head, including linting and unit tests on Python 3.10 and 3.12 and the Compose integration tests (Run tests); the first run failed on the image build (typed-ast), fixed by the build stage.

Declined review findings

Reviewed by the adversarial and quality reviewer subagents (two adversarial rounds); fixed: output sizes, nested forwards (cancel, tracking, responses), null fields in updates, dead TaskRuns.foca_config, inconsistent issue references, split endpoint tests, cancel at the last of several forwards, missing-document test. Declined:

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Upgrade proTES to FOCA 0.15 with compatible configuration, containerization, task handling, and validation coverage.

New Features:

  • Add compatibility for FOCA 0.15 and Pydantic 2 across the application and worker.
  • Represent task forwarding history as an ordered, non-recursive list while remaining compatible with legacy nested records.
  • Serve GA4GH service information through FOCA configuration and provide locally bundled OpenAPI schemas.

Bug Fixes:

  • Preserve executor error-handling settings and normalize backend output sizes during task conversion.
  • Use the configured MongoDB database consistently for Celery task tracking.
  • Return legacy nested forwarding records as lists and cancel tasks at the most recent forward.

Enhancements:

  • Adopt FOCA 0.15 configuration, error responses, request-size limits, typed custom configuration, and updated database APIs.
  • Run the service as the FOCA-provided non-root user and remove build tooling from the runtime image.
  • Upgrade the Compose MongoDB version and stop registering the unavailable middleware management API.

Build:

  • Pin the FOCA 0.15 Python 3.12 image and build dependency wheels in a dedicated stage for the runtime image.
  • Update application dependencies for FOCA 0.15, Connexion, and py-tes 1.1 while moving development-only packages to dev requirements.

CI:

  • Run linting, type checks, and unit tests on Python 3.10 and 3.12 with restricted workflow permissions.

Documentation:

  • Document the FOCA 0.15 configuration and update OpenAPI schema references for offline startup.

Tests:

  • Add application, model, task endpoint, forwarding, and Celery tracking tests using an in-memory MongoDB and fake TES backends.

uniqueg and others added 5 commits October 22, 2026 04:43
proTES required `foca>=0.12.1` without an upper bound, so fresh
installs got FOCA 0.15, with which the app did not start; only the
2022 base image kept the image working.

- Require `foca>=0.15.0,<0.16`, `connexion>=2.15.1,<3` and
  `py-tes>=1.1` (supports `ignore_error`, #176); drop the `pymongo`
  pin and move `pytest-ordering`, `celery-types` and the type stubs
  to the dev requirements (plus `setuptools` for linting `setup.py`
  on Python 3.12).
- Build the image on `elixircloud/foca:0.15.0-py3.12`, pinned by
  digest; install as root, as the FOCA image runs as UID 1000. The
  API directory no longer needs to be writable (FOCA does not write
  specs).
- CI: lint on Python 3.10 and 3.12, and run the new unit tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Follow FOCA's migration guides for 0.14 and 0.15:

- Config: no removed options (`validation_methods`,
  `validation_checks`, `environment`, `use_reloader`, the old
  exception members), `server.debug: False`, a 1 MiB request body
  limit (`max_content_length`), problem details sent as
  `application/json` (GA4GH), a literal task ID charset, and fully
  qualified controller modules. No trusted token issuers yet: FOCA
  requires an `audience` with issuers, and authentication stays
  disabled until #212.
- Service info: served by FOCA from `service_info` (version of the
  installed package), instead of the app's controller and its
  `service_info` collection.
- The middleware management API is no longer registered: its
  controller module does not exist (#194).
- Code: pydantic 2 (`ConfigDict`, `RootModel`, `model_dump(mode=
  "json")`, executors and commands default to empty lists),
  `foca.get_config()`, a typed `get_custom_config()`, and
  `foca.get_collection()` in the Celery task, which no longer uses
  FOCA's private client factory or a hard-coded database name
  (`MONGO_DBNAME` applies). The worker validates the custom config.
- Specs: the GA4GH service info schemas are local, so the app starts
  without fetching them.
- `ignore_error` of executors is relayed in both directions (#176).
- Forwards: the recursive `tesNextTes` schema made startup hang with
  jsonschema 4 (#173). As suggested there,
  `logs[].metadata.forwarded_to` is a list of `tesForward` objects
  (`id`, `url`, `forward_time` in RFC 3339), in the order of
  forwarding; proTES appends its own forward and cancels tasks at the
  last one.

Tests (in `tests/`, run in CI) cover startup, config, service info,
problem details, the body limit, task relay with a fake backend, the
Celery task and the models.

BREAKING CHANGE: errors are problem details (`title`, `status`,
`detail`) instead of `message` and `code`; the service info is
configured in `service_info.service` and no longer stored; configs
must apply FOCA 0.15's changes; the middleware management API is not
served; `logs[].metadata.forwarded_to` is a list of forwards instead
of a nested `tesNextTes` object.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Current PyMongo releases refuse to connect to MongoDB 3.6 (#171);
MongoDB 8.0 does not start on Linux kernels 6.19 to 7.0.13
(SERVER-121912).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings on the FOCA 0.15 migration:

- py-tes returns output sizes as integers, which pydantic 2 no longer
  converts to strings, so the Celery task failed for every finished
  task with outputs; the converter converts them (sizes may be
  missing).
- Tasks stored by earlier versions, and tasks of other instances
  running them, have forwards nested as `tesNextTes` objects; they
  are read as lists, so such tasks can still be canceled and tracked.
  `forward_time` is optional for these.
- Remove the unused `TaskRuns.foca_config`, and name #212 wherever
  the config says when authentication is enabled.
- Tests: split the endpoint tests, cancel at the last of several
  forwards, outputs of tracked tasks, missing documents.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tasks stored by earlier versions were served with forwards nested as
`tesNextTes` objects, against the new spec; GET and list responses
now flatten them. Task updates no longer store `null` for unset
fields (e.g., `forward_time` of such forwards, missing output sizes).

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

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This breaking-change PR upgrades proTES to FOCA 0.15 and Python 3.12-era dependencies, refactors configuration, Pydantic models, database access, service-info routing, and error handling, modernizes forwarding and backend conversion behavior, rebuilds the container with a compiled dependency stage, and adds cross-version unit and integration coverage.

Sequence diagram for task forwarding and progress tracking

sequenceDiagram
    participant Client
    participant API as proTES API
    participant Backend as TES backend
    participant Mongo as MongoDB
    participant Worker as Celery worker

    Client->>API: CreateTask
    API->>Backend: create_task
    Backend-->>API: remote task ID
    API->>Mongo: model_dump and store forwarded_to
    API-->>Client: task ID
    Worker->>Backend: get_task
    Backend-->>Worker: task state and outputs
    Worker->>Mongo: upsert_fields_in_root_object
    Client->>API: GetTask or CancelTask
    API->>Mongo: get_collection
    API->>Backend: cancel_task using last forwarded ID
    Backend-->>API: cancellation result
    API-->>Client: task response
Loading

Flow diagram for FOCA service-info and API configuration

flowchart TD
    Config[service_info.service in config.yaml]
    Specs[additions.openapi.yaml]
    FOCA[FOCA service-info controller]
    Endpoint[GET /service-info]
    Version[Installed pro-tes package version]

    Config --> FOCA
    Version --> FOCA
    Specs --> Endpoint
    FOCA --> Endpoint
    Endpoint --> Response[GA4GH Service response]
Loading

File-Level Changes

Change Details Files
Migrate the application, configuration, models, and runtime integrations to FOCA 0.15 and Pydantic 2.
  • Update runtime dependency ranges and move development-only packages out of production requirements.
  • Adopt FOCA 0.15 configuration APIs, typed custom configuration access, new exception mapping, service-info handling, fully qualified controllers, and the removed middleware API behavior.
  • Replace Pydantic 1 constructs with Pydantic 2 models, configuration, serialization, validators, and safe default factories.
  • Use FOCA collection access for API and Celery database operations, including support for MONGO_DBNAME and missing-document errors.
requirements.txt
requirements_dev.txt
pro_tes/app.py
pro_tes/celery_worker.py
pro_tes/config.yaml
pro_tes/config_models.py
pro_tes/exceptions.py
pro_tes/ga4gh/tes/models.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/tasks/track_task_progress.py
pro_tes/utils/db.py
pro_tes/utils/misc.py
pro_tes/gunicorn.py
pro_tes/middleware/middleware_handler.py
pro_tes/plugins/middlewares/task_distribution/base.py
pro_tes/plugins/middlewares/task_distribution/distance.py
pro_tes/plugins/middlewares/task_distribution/random.py
Revise task forwarding and backend conversion for the new TES behavior and compatibility with legacy stored tasks.
  • Represent forwarded destinations as an ordered, non-recursive list with RFC 3339 timestamps and flatten legacy nested records on read.
  • Cancel forwarded tasks at the most recent destination while preserving tracking and response compatibility.
  • Preserve executor ignore_error and convert backend output sizes from integers to string values accepted by the models.
pro_tes/api/additions.openapi.yaml
pro_tes/ga4gh/tes/models.py
pro_tes/ga4gh/tes/task_runs.py
pro_tes/utils/models.py
Move service-info schemas and routing into local OpenAPI additions and remove the application-owned service-info implementation.
  • Serve service info through FOCA configuration using the installed package version.
  • Inline GA4GH service schemas to eliminate startup-time network fetching and update task-log forwarding schemas.
  • Remove the persisted service_info collection and legacy controller/model implementation.
pro_tes/api/9e9c5aa.task_execution_service.openapi.yaml
pro_tes/api/additions.openapi.yaml
pro_tes/api/additional_logs.yaml
pro_tes/ga4gh/tes/service_info.py
pro_tes/ga4gh/tes/server.py
pro_tes/config.yaml
Rebuild the container for the pinned FOCA 0.15 Python 3.12 image without build tooling in the runtime image.
  • Build dependency wheels in a root build stage with compiler dependencies required by typed-ast.
  • Install application dependencies as root, then run the service as UID 1000 using the pinned base-image digest.
Dockerfile
Expand automated verification across supported Python versions and application integration paths.
  • Run linting, type checking, and collected tests on Python 3.10 and 3.12.
  • Add startup/configuration, service-info, error, request-limit, model, forwarding, task endpoint, Celery tracking, database selection, and fake-backend tests.
  • Use mongomock fixtures and local OpenAPI schemas to test without network or external services.
.github/workflows/checks.yaml
tests/conftest.py
tests/test_app.py
tests/test_models.py
tests/test_tasks.py
tests/test_track_task_progress.py
Upgrade the Compose database version for the supported deployment environment.
  • Use MongoDB 7.0 and document the kernel-related image choice and data-directory migration consideration.
docker-compose.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#171 Update the MongoDB image used by Docker Compose to a version that provides a linux/arm64 image, allowing docker compose up to run on Apple Silicon. ✅
#173 Remove the recursive tesNextTes schema reference that causes startup to hang during schema validation or reference resolution with jsonschema versions newer than 3.2.0. ✅
#176 Add the TES v1.1 ignore_error attribute to executor models so requests containing it no longer fail validation or construction. ✅
#176 Preserve and relay an executor’s ignore_error value when forwarding tasks to backends and when converting backend tasks into proTES models. ✅
#203 Upgrade proTES and its container/runtime dependencies to FOCA 0.15 and migrate the application code and configuration for compatibility, including the service-info and problem-details changes. ✅
#203 Apply the requested FOCA security and server configuration, including trusting the specified LS Login issuer while leaving TES authentication disabled for now. ❌ The PR leaves security.auth.issuers empty instead of configuring the LS Login issuer requested by the issue. Its stated reason is that FOCA requires an audience when issuers are configured; the issuer and audience are deferred to #212.
#203 Implement the scoped behavior and deployment fixes: non-recursive forwarding logs compatible with existing stored tasks, ignore_error relay, FOCA-supported database access, MongoDB 7.0, and verification of the requested task and service-info flows. ✅

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

Comment thread .github/workflows/checks.yaml Fixed
`ip2geotools` requires `typed-ast`, which has no wheels for Python
3.12, and the FOCA image has no compiler, so the image build failed.
Wheels are now built in a build stage with gcc and installed from
there, so the final image has no build tools.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 03:07

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

Fixed security issues:

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

## Individual Comments

### Comment 1
<location path="pro_tes/tasks/track_task_progress.py" line_range="112-113" />
<code_context>
     # updating the database
-    db_client.upsert_fields_in_root_object(root="task", **document.task.dict())
+    db_client.upsert_fields_in_root_object(
+        root="task", **document.task.model_dump(mode="json", exclude_none=True)
+    )
</code_context>
<issue_to_address>
**Successful cancellation is overwritten**

When a cancel request reads a cancelable state and its backend cancellation succeeds after the tracker reads a terminal response but before the tracker’s final MongoDB write, the tracker writes its previously fetched task state and full task snapshot after the cancel handler sets the state to `CANCELED`, replacing that update with the stale remote state. The caller sees the task as completed or running despite the successful cancellation.

Make the final update conditional on the current state or update only fields that cannot overwrite a concurrent cancellation.
</issue_to_address>

### Comment 2
<location path="pro_tes/ga4gh/tes/models.py" line_range="260" />
<code_context>
-    size_bytes: str = Field(
-        ...,
+    # required by the specs, but py-tes may return none
+    size_bytes: Optional[str] = Field(
+        default=None,
         description=(
</code_context>
<issue_to_address>
**Output logs omit required sizes**

When a backend returns an output log whose `size_bytes` is missing, `convert_output_file_logs` preserves a missing backend size as `None`, and the task update serializes with `exclude_none=True`, so the stored output log lacks `size_bytes` and GET responses violate the TES schema; clients receive malformed task data.

Ensure output logs remain schema-valid when the backend omits a size, or explicitly change the API schema and response contract to allow its omission.

Also at `pro_tes/utils/models.py:242-244`, `pro_tes/tasks/track_task_progress.py:112`.
</issue_to_address>

### Comment 3
<location path="tests/test_models.py" line_range="110" />
<code_context>
+            remote_task_id="task-1",
+        )
+    assert document.task.logs is not None
+    for log, previous in zip(document.task.logs, [[earlier], []]):
+        assert log.metadata is not None
+        assert log.metadata.forwarded_to is not None
</code_context>
<issue_to_address>
**Dropped logs pass the test**

When `_update_task_metadata` returns an empty `logs` list, `test_forward_logged` line 110 iterates with `zip`, so if `_update_task_metadata` drops all logs, the loop runs zero times and never checks that any forward was appended.

Assert that the returned logs contain the expected two entries before checking their forwards.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and changing the Compose MongoDB image from 3.6 to 7.0 affects existing persisted database volumes; MongoDB requires supported upgrade steps, so an existing deployment may fail to start or become inaccessible. Reverting the image may not be enough if the database upgrade has progressed, so verify the upgrade path and backups before deploying.

Blocking findings: pro_tes/tasks/track_task_progress.py:113, pro_tes/ga4gh/tes/models.py:260, tests/test_models.py:110


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

Comment thread pro_tes/tasks/track_task_progress.py Resolved
Comment thread pro_tes/ga4gh/tes/models.py Resolved
Comment thread tests/test_models.py Resolved
- CI: read-only token permissions by default (CodeQL).
- Test that forwards are logged for every task log (Sourcery).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 7d63fb0 into dev Oct 22, 2026
10 checks passed
@uniqueg
uniqueg deleted the refactor/foca-0-15 branch October 22, 2026 11:27
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.

refactor!: upgrade to FOCA 0.15 fix: add ignore_error executor field fix: infinite loop with jsonschema>3.2.0 Update Mongo image version

2 participants