Skip to content

build: move to FOCA 0.21 and Python 3.13 - #63

Merged
uniqueg merged 7 commits into
devfrom
build/foca-0.21
Nov 6, 2026
Merged

uniqueg merged 7 commits into
devfrom
build/foca-0.21

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Summary

Moves Pubgrade off the FOCA 0.7 / Python 3.9 base image to FOCA 0.21 on elixircloud/foca:0.21.0-py3.13 (same digest as cloud-registry and Pubgrade-Sidecar), with the dependencies that come with it, makes the scan of the app's image blocking again, and drops the Dependabot ignores that held packages back for Python 3.9.

  • Dependencies: foca==0.21.0, gitpython~=3.2.1, gunicorn~=26.2.0, kubernetes~=37.0.2; setuptools dropped; test extras pytest==9.2.0, coverage==7.17.2, mongomock==4.3.0 (unchanged); python_requires=">=3.13".
  • FOCA API (migration guides 0.14 to 0.21): config read with get_config() / app.config.foca instead of config["FOCA"]; named API spec with a path relative to the config file; exceptions.mapping with problem details (RFC 9457, application/problem+json) instead of msg/status_code; server.environment and use_reloader removed; server.max_content_length 1 MiB (413).
  • App factory pubgrade.app:create_app(); the image serves it with Gunicorn and FOCA's settings (pubgrade/gunicorn_config.py: FOCA's foca.gunicorn_config, port 8080, one worker), but with 16 threads instead of 4, as a publish holds its thread until the subscribers answer, and a graceful timeout of 28 s, so a running publish can finish within Kubernetes' default grace period. GUNICORN_CMD_ARGS stays free for deployments. python -m pubgrade.app runs the development server.
  • Timestamps: FOCA 0.21 validates responses, and date-time values need a time zone. New timestamps are UTC with offset; a build's finished_at is null until it finishes (was the string "NULL"). At startup, pubgrade/timestamps.py brings stored builds and subscriptions into that format (naive values get +00:00, "NULL" becomes null): it reads only documents that need repair, updates them only while they still hold the values it read, and logs how many it changed. Builds and subscriptions are also returned repaired, for objects that a pod of the previous version writes during a rolling update.
  • API version 2.0.0 (error format, nullable finished_at). Unverified users get the 403 of the mapping as before; their exception now derives from Forbidden (was Unauthorized), and a test checks that each exception's status matches its problem details.
  • Dockerfile: uv installs the requirements (the FOCA image has no pip), then uv pip check; git installed for GitPython; OCI labels; runs as the FOCA image's user 1000 with read-only app files and /pubgrade_temp_files writable for group 0 (any UID works, as on OpenShift). .dockerignore is now an allowlist.
  • CI: tests run on Python 3.13; the scan of the pubgrade image fails on fixable critical and high findings again (as in cloud-registry). The scan of pubgrade-updater (based on python:3, not FOCA) stays report-only: its only finding is a setuptools vendored by pip in the base image, which this PR leaves to a separate decision.
  • Dependabot: ignores for Python 3.9 (setuptools, pytest, coverage, gunicorn, kubernetes; added in chore: add CODEOWNERS, CITATION and Dependabot #53 and build: ignore updates that need a newer Python #60) removed; those packages are bumped here.
  • Docs: problem details, 413 and timestamps (docs/api.md); upgrade notes "Upgrading to FOCA 0.21 (API 2.0.0)" (docs/deployment.md: config migration, errors, timestamps, Gunicorn, user 1000, MongoDB 4.4 or newer); tests on Python 3.13 and bumping FOCA (docs/development.md); README badge.

Closes #62

Verification

  • make test (Python 3.13): 192 passed, 100% coverage, pubgrade/app.py no longer omitted (new: tests/test_timestamps.py, tests/test_app.py, tests/test_exceptions.py, tests/test_image.py checks the base image's FOCA against requirements.txt, the Gunicorn command, threads and user; config tests load the config with FOCA 0.21 and check the body limit; endpoint tests for builds and subscriptions in the old format).
  • helm lint helm --strict and tests/chart.sh: OK.
  • mkdocs build --strict: OK.
  • docker build and tests/smoke.sh on the image as UID 12345, group 0, as in CI: passed; Gunicorn settings in the image: 1 worker, 16 threads, graceful timeout 28 s (also checked by tests/test_image.py).
  • Startup repair against MongoDB 7: old-format builds (also in notifications) and subscriptions repaired, values with zone left alone, nothing left on a second run; served and validated afterwards.
  • Trivy 0.75.0 on the pubgrade image (--ignore-unfixed --severity CRITICAL,HIGH): 0 findings.
  • tests/e2e/upgrade.sh (k3s, two sites, Pubgrade-Sidecar from dev on the new base, including the unreachable subscriber): "Upgrade test passed".
  • CI: all checks passed (PR title, Lint, Test, Chart, Docs, Smoke test, Upgrade test, Scan image (pubgrade, blocking; pubgrade-updater, report-only), CodeQL, Codecov, Read the Docs), CI passed.

Review

Full review (adversarial-reviewer and quality-reviewer, two rounds). Round 1 fixed: unverified users' status, problem-detail texts, tests for the factory and the mapping, read-time repair for rolling updates, a filtered compare-and-set repair, 16 Gunicorn threads with docs on a buffering proxy, and a note on stored callback URLs without scheme. Round 2 fixed: Gunicorn settings in a module of the app (so GUNICORN_CMD_ARGS isn't taken) with a shutdown time for publishes, a test of the effective settings, and a compare-and-set test for notifications.

Sourcery: 7 threads answered and resolved. 413 for oversized bodies holds (FOCA 0.21 uses the exception's own status before the catch-all; checked on the image and now pinned in tests/test_exceptions.py). The window in a rolling update in which the old pod answers new unfinished builds with 500 is now in the upgrade notes. Unchanged behaviour of dev (Git in the image for builds, notifier deadlines and ordering, completion idempotence, interrupted publishes) is beyond this PR.

Declined review findings

  • Unverified users' status undocumented (medium): it is 403 as on dev, whose mapping already answered 403; only the exception's base class changed to match. The spec lists 403 for these operations.
  • Python version check in make test (low): pip already refuses with python_requires>=3.13.
  • current_app kept in notify_all_subscriptions (low): its threads need the app object for an app context; unchanged by this PR.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits November 6, 2026 16:41
Build the image on elixircloud/foca:0.21.0-py3.13 instead of FOCA 0.7
on Python 3.9, with GitPython 3.2, Gunicorn 26 and kubernetes 37, and
drop the unused mock, setuptools and yq.

- Adapt to FOCA 0.21: config via get_config(), named API spec,
  problem details instead of msg/status_code (API 2.0.0), no
  server.environment/use_reloader, a 1 MiB limit on request bodies.
- Add an app factory (pubgrade.app:create_app) that the image serves
  with Gunicorn and FOCA's settings, instead of the development server.
- Write timestamps in UTC with time zone and null for unfinished
  builds, as FOCA checks responses against date-time, and repair
  stored ones at start.
- Install the requirements with uv, as the FOCA image has no pip; add
  git for GitPython; run with read-only app files; allowlist the
  build context.
- Bump pytest and coverage, add mongomock to the test dependencies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run the unit tests on the runner with Python 3.13, the version of the
new base image, as the FOCA image has no pip to install the test
dependencies with; make the scan of the app's image fail on critical
and high vulnerabilities that have a fix (the updater's image, not
built on FOCA, is still reported only); and drop the Dependabot
ignores for Python 3.9 (pytest, coverage, gunicorn, kubernetes and
setuptools, which is no longer a requirement).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe problem details, timestamps and the 413 of API 2.0.0, the
upgrade notes for configurations of deployments, the test setup on
Python 3.13 and how FOCA is bumped, and the blocking image scan.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Answer unverified users with the 403 of the mapping: their exception
  derives from Forbidden now, not Unauthorized (401).
- Fix typos and punctuation in the problem details, and check that each
  entry is complete and matches the status of its exception.
- Test the app factory and the entry point (no longer omitted from the
  coverage), timestamps with time zone, and the image's user.
- Say what happens to values the startup repair can't bring into the
  format.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Return builds and subscriptions with repaired timestamps, as an
  instance of the previous version can still write the old format
  during a rolling update, after the repair at start.
- Repair at start only documents that need it, and only while their
  values are still the ones read, so a concurrent write is kept.
- Serve with 16 Gunicorn threads instead of FOCA's 4: a publish holds a
  thread until its subscribers answer, and a slow client while it sends.
- Document the threads, a buffering proxy, and subscriptions whose
  callback URL isn't a URI.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Move the Gunicorn settings into pubgrade/gunicorn_config.py (FOCA's,
  with 16 threads), so GUNICORN_CMD_ARGS stays free for deployments,
  and give running publishes 28 s on shutdown, within Kubernetes'
  default grace period.
- Check the effective settings in a test, loaded as the image's command
  does.
- Compute repaired values once, and test that concurrent writes to
  started_at and notifications are kept.
- Document the shutdown limit and the margin of a publish.

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

sourcery-ai Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Add the compatibility migration and read-time repair for legacy stored timestamps, including null unfinished-build values and compare-and-set updates that preserve concurrent writes.

  • pubgrade/timestamps.py L1-169

API

Revise the OpenAPI contract to version 2.0.0, use RFC 9457 problem details, and allow a null build completion timestamp; align exception mappings and the unverified-user status with that contract.

  • pubgrade/api/pubgrade.yaml L951-954 (+8 small edits)
  • pubgrade/errors/exceptions.py L58, L110-242

Uses of the API

Adapt the endpoint handlers to FOCA 0.21 configuration access and the new timestamp representation, while returning legacy build and subscription records in the API format.

  • pubgrade/modules/endpoints/builds.py L137-141 (+18 small edits)
  • pubgrade/modules/endpoints/repositories.py L53-63 (+7 small edits)
  • pubgrade/modules/endpoints/subscriptions.py L81-85 (+20 small edits)
  • pubgrade/modules/endpoints/users.py L51-59 (+9 small edits)

Implementation

Create the FOCA app factory and development entry point, synchronize configured admin users, repair stored timestamps at startup, and set the image's Gunicorn concurrency and shutdown behavior.

  • pubgrade/app.py L1-24, L51-75 (+2 small edits)
  • pubgrade/gunicorn_config.py L1-14

Configuration

Move the application image and dependency installation to FOCA 0.21/Python 3.13, configure its runtime and metadata, and update the test and vulnerability-scan workflows and dependency update policy.

  • .dockerignore L1-21
  • .github/dependabot.yml L7, L17 (removed lines)
  • .github/workflows/ci.yml L93-97, L276-280, L294-297 (+1 small edits)
  • Dockerfile L1-64
  • Makefile L19-24
  • pubgrade/config.yaml L4-6, L12-14, L53-69
  • requirements.txt L1, L3 (removed lines)
  • setup.cfg L5 (removed lines), L8-11
  • setup.py L29-37

Documentation

Document the API error and timestamp changes, the FOCA 0.21 deployment upgrade requirements, and the Python 3.13 development and CI setup.

  • README.md L83
  • docs/api.md L34-53
  • docs/deployment.md L72-115
  • docs/development.md L10-29, L50-52

Tests

Update endpoint tests for FOCA's configuration interface and add checks for legacy timestamp responses, app startup, problem-detail mappings, image runtime settings, and timestamp repair concurrency.

  • tests/mock_data.py L97, L108
  • tests/pubgrade/endpoints/test_builds.py L153-166, L309-329, L696-700 (+10 small edits)
  • tests/pubgrade/endpoints/test_repositories.py L36-43, L83-86, L95-98 (+2 small edits)
  • tests/pubgrade/endpoints/test_subscriptions.py L66-94, L218-243, L305-322 (+21 small edits)
  • tests/pubgrade/endpoints/test_users.py L37-49, L86-89, L142-148 (+5 small edits)
  • tests/pubgrade/test_server.py L224-240, L286-305, L323-339 (+16 small edits)
  • tests/smoke.sh L35, L62-64
  • tests/test_app.py L1-94
  • tests/test_config.py L34-45 (+3 small edits)
  • tests/test_exceptions.py L1-79
  • tests/test_image.py L1-79
  • tests/test_timestamps.py L1-174

Other changes

Files not grouped.

  • requirements.txt L4

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

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35703262 | 📁 Comparing ef55655 against latest (a22344e)

  🔍 Preview build  

3 files changed
± api/index.html
± deployment/index.html
± development/index.html

@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (a22344e) to head (65cdd43).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #63   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            7        10    +3     
  Lines          669       745   +76     
=========================================
+ Hits           669       745   +76     

☔ 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 6, 2026 16:55
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 6, 2026 16:55

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

Fixed security issues:

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

## Individual Comments

### Comment 1
<location path="Dockerfile" line_range="29-30" />
<code_context>
-COPY --chown=1000:1000 ./ /app
+## Git, which GitPython needs to clone repositories for builds (and to be
+## imported at all); the FOCA image has none
+RUN apt-get update \
+  && apt-get install -y --no-install-recommends git \
+  && rm -rf /var/lib/apt/lists/*

</code_context>
<issue_to_address>
**Builds can reach internal hosts**

When builds are enabled and an external caller registers a repository URL pointing to an internal host, then submits a build with the token returned at registration, `register_repository` stores the caller-supplied URL without validating it, and `git_clone_and_checkout` clones that URL from the Pubgrade pod. Installing Git makes this path available to callers who can register a repository and submit a build, allowing them to make the pod connect to internal hosts or services.

Validate repository URLs against an allowed scheme and host policy, and restrict the build pod's network egress to prevent access to internal services.
</issue_to_address>

### Comment 2
<location path="pubgrade/gunicorn_config.py" line_range="13" />
<code_context>
+
+from foca.gunicorn_config import *  # noqa: F401,F403
+
+threads = 16
+graceful_timeout = 28
</code_context>
<issue_to_address>
**Slow subscribers exhaust notifier threads**

When a subscriber slowly trickles response headers without exceeding the per-read inactivity timeout, and publishes continue to that subscriber, `requests` treats the configured timeout as a connect/read inactivity timeout, not a total deadline; a subscriber that keeps its response headers trickling can therefore hold a notifier thread after `notify_all_subscriptions()` has returned and shut down its executor without waiting. Repeated publishes accumulate those threads until Pubgrade can no longer serve requests.

Enforce a true total deadline for subscriber calls and ensure timed-out work is cancelled or otherwise bounded so lingering notifier threads cannot accumulate.
</issue_to_address>

### Comment 3
<location path="pubgrade/modules/endpoints/subscriptions.py" line_range="366" />
<code_context>
-    subscription_object["updated_at"] = str(
-        datetime.datetime.now().isoformat()
-    )
+    subscription_object["updated_at"] = now()
     db_collection_subscriptions.update_one(
         {"id": subscription_id}, {"$set": subscription_object}
</code_context>
<issue_to_address>
**Older build can overwrite newer deployment**

When two builds matching the same subscription complete concurrently and the older build's callback is processed last, the older build's callback can finish after the newer build's callback, so `notify_subscriptions` sends the older image last and stores its `build_id` and state over the newer result. The subscriber ends up running a stale image while Pubgrade records that older build as the latest notification.

Serialize notifications per subscription or reject a notification when its build is older than the one already applied.
</issue_to_address>

### Comment 4
<location path="pubgrade/modules/endpoints/builds.py" line_range="93" />
<code_context>
             "$set": {
                 "status": "FAILED" if failed else "SUCCEEDED",
-                "finished_at": datetime.datetime.now().isoformat(),
+                "finished_at": now(),
             }
         },
</code_context>
<issue_to_address>
**Delivered builds can remain queued**

When the process stops after a subscriber applies the update but before the final build update, `publish_prebuilt_image` sends subscriber updates before it records the build's terminal status and `finished_at`. A process termination after subscribers apply the image but before that database update leaves the build stored as `QUEUED` with no completion marker, despite the external update having taken effect.

Persist a recoverable notification/completion state or reconcile unfinished prebuilt builds after interruption.
</issue_to_address>

### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="593" />
<code_context>
         data['status'] = "SUCCEEDED"
-        data['finished_at'] = str(
-            datetime.datetime.now().isoformat())
+        data['finished_at'] = now()

-        intermediate_registry_format = current_app.config["FOCA"].endpoints["builds"]["intermediate_registery_format"]
</code_context>
<issue_to_address>
**Retried completion repeats notifications**

When the completion callback is retried or delivered concurrently for the same build, both `build_completed` calls pass the repository check, trigger image signing, and call `notify_all_subscriptions` because completion does not check the build's current status or claim the transition atomically. The subscriber receives duplicate updates, and the later call overwrites the build's notification results.

Make completion an atomic, idempotent state transition and only dispatch signing and notifications for the request that claims it.
</issue_to_address>

### Comment 6
<location path="pubgrade/errors/exceptions.py" line_range="114" />
<code_context>
+# in the configuration); exceptions that aren't listed get those of their
+# closest listed base class
 exceptions = {
     Exception: {
-        "msg": "An unexpected error occurred.",
-        "status_code": "500",
</code_context>
<issue_to_address>
**Oversized requests return 500**

When a request body exceeds the advertised 1 MiB limit, werkzeug raises `RequestEntityTooLarge`, but the exception mapping has no entry for it or its `HTTPException` base, so it falls back to the generic `Exception` mapping and returns status 500 instead of 413.

Add a mapping for `RequestEntityTooLarge` or its `HTTPException` base that returns status 413.

Also at `pubgrade/config.yaml:14`.
</issue_to_address>

### Comment 7
<location path="pubgrade/modules/endpoints/builds.py" line_range="178" />
<code_context>
         try:
-            build_data["finished_at"] = "NULL"
-            build_data["started_at"] = str(datetime.datetime.now().isoformat())
+            build_data["finished_at"] = None
+            build_data["started_at"] = now()
             build_data["status"] = "QUEUED"
</code_context>
<issue_to_address>
**Old replicas reject unfinished builds**

When a new replica creates an unfinished build while an old replica is still serving requests for it, an old FOCA 0.7 replica serving a build created by the new version returns `finished_at: null`; its API schema requires a non-null date-time, so response validation fails and the caller receives an error during the rolling upgrade.

Use a cutover that prevents old replicas from serving new-format records, or otherwise delay writing nullable `finished_at` values until all old replicas are gone.
</issue_to_address>

Linked issues

#62 build: move to a current FOCA base image · 3 of 3 met

# Requirement Status Notes
1 The image builds on a current FOCA image and passes the tests. ✅ Met The Dockerfile uses FOCA 0.21.0 on Python 3.13; the PR reports a successful image build and passing tests.
2 The image scan fails CI on fixable critical and high findings. ✅ Met The CI scan matrix enables failure for the pubgrade image; the updater image remains report-only.
3 The Dependabot ignores for Python 3.9 are gone, and those packages are bumped. ✅ Met The Python-version package ignores are removed; pytest, coverage, Gunicorn, and Kubernetes are upgraded, while the unused setuptools dependency is dropped.

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and on startup, the app rewrites legacy timestamps in MongoDB, adding UTC offsets and changing unfinished-build values from "NULL" to null; those stored changes remain after a revert, though they are bounded and can be normalized. The image and API runtime also change substantially, but ordinary deployment or response bugs can be fixed by reverting.

Blocking findings: Dockerfile:30, pubgrade/gunicorn_config.py:13, pubgrade/modules/endpoints/subscriptions.py:366, pubgrade/modules/endpoints/builds.py:93, pubgrade/modules/endpoints/builds.py:593, and 2 more


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

Comment thread Dockerfile Resolved
Comment thread pubgrade/gunicorn_config.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/errors/exceptions.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Check that a body over the limit gets 413 and other werkzeug errors
keep their status, as FOCA skips the catch-all Exception for exceptions
with an HTTP status. Document that a pod of the previous version
answers unfinished builds of the new one with 500 during a rolling
update.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit dd9ab9d into dev Nov 6, 2026
35 of 42 checks passed
@uniqueg
uniqueg deleted the build/foca-0.21 branch November 6, 2026 17:10
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.

build: move to a current FOCA base image

1 participant