Skip to content

feat: cancel builds, keeping their records - #83

Merged
uniqueg merged 5 commits into
devfrom
feat/cancel-build
Nov 7, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/cancel-build

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

DELETE /repositories/{id}/builds/{build_id}, allowed by the repository's access token (like PUT/DELETE /repositories/{id}), withdraws a build and keeps its record (option A of the issue):

  • New Build status CANCELED (spec enum). The build stays listed; finished_at is set if it hadn't finished.
  • With builds switched on, a running build is stopped like in repository deletion (stop_builds, reused with force=True): pod deleted, files removed. If that fails, the request gets a 500 and the build stays CANCELED with an internal mark; a repeated DELETE stops it again, instead of getting a 409.
  • The internal completion callback (PUT on the build, called by the updater) gets 409 for a canceled build: it doesn't become SUCCEEDED, its image isn't signed, no one is notified, and any pod left over is deleted. The callback now records SUCCEEDED before it triggers the signing (and puts the previous state back if the signing fails), so a cancellation either stops the build first or finds it finished.
  • A build canceled while it starts is stopped once its pod exists, and kept even if its start then fails. Prebuilt images (builds off) canceled during notification stay CANCELED.
  • Finished builds can be canceled too; they are only marked.
  • No re-notification, no undeploy, no registry deletion; the docs say that deployments already notified keep what they pulled.
  • A repeated DELETE gets 409; an unknown build, or one of another repository, gets 404.
  • There is no public PUT for builds: the spec and docs now describe the existing PUT as the internal completion callback, and say that a changed build is a new POST.

Docs: docs/usage.md (new section "Cancel a build"), docs/api.md (endpoint table and notes), docs/deployment.md (Builds section, upgrade notes with the new enum value).

Closes #3

Verification

  • pytest --cov: 596 passed, coverage 100% (unit tests with mongomock, mocked Kubernetes; integration tests with local Git fixtures, no network).
  • MONGODB_TEST_URI=mongodb://127.0.0.1:27093 pytest tests/integration against MongoDB 7.0.34: 22 passed.
  • ruff check, ruff format --check, mypy: clean. mkdocs build --strict: OK.
  • CI on the PR: all checks passed (CI passed, tests with mongomock and MongoDB 7.0, smoke and upgrade tests, image scans, docs, CodeQL, Codecov).
  • Full review: adversarial-reviewer and quality-reviewer, 2 rounds. All high and medium findings fixed (signing race, cancel during start, failed stop leaving a dead QUEUED build, atomic finished_at).
  • Sourcery: three findings fixed in 06c60a8 (repository deletion stops canceled builds whose stop failed; no notification for a prebuilt image canceled before notifications start; controller test checks the stored status). The fourth (no public PUT) is the maintainers' decision; answered in the thread.

Declined review findings

  • Split the force flag out of stop_builds (quality, low): kept as a small flag; both call sites are in this module.
  • Drop the monkeypatch in test_deleteBuild (quality, low): the test config has builds switched on, so stop_builds would call Kubernetes otherwise.
  • Factor out the revert in build_completed (quality, low): only one revert is left after round 2.
  • Notifications already in progress when a build is canceled are delivered (adversarial, low): documented rather than interrupted.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 7, 2026 14:04
DELETE /repositories/{id}/builds/{build_id}, allowed by the repository's
access token, marks a build CANCELED (new status) and keeps it listed.
With builds switched on, a running build's pod and files are removed as
when a repository is deleted; if that fails, the build gets its
previous status back, so that the request can be repeated. Finished
builds are only marked. A repeated request gets a 409, an unknown build
a 404.

The completion callback (PUT) of a canceled build gets a 409, also if
the build is canceled while its completion is processed, so it can't
succeed or notify anyone; the same holds for prebuilt images canceled
while subscribers are notified. Canceled builds count as stopped when
their repository is deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Usage, API and deployment guide: canceling a build, what happens to
running and finished builds and to deployments already notified, and
that the PUT on a build is the internal completion callback. The upgrade
notes name the new status CANCELED.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings on canceling builds:

- The completion callback records SUCCEEDED before it triggers the
  signing (and puts the previous state back if that fails), so a
  cancellation either stops the build before or finds it finished;
  a build canceled after that notifies no one.
- A build canceled while it starts is stopped once its pod exists, and
  kept if its start then fails. The completion of a canceled build
  removes a pod that is left, so the updater stops reporting it.
- Status and finished_at of a canceled build change in one update.
- Docs say what happens in these cases; the Conflict response cites
  RFC 7231 like the others.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A failed stop no longer puts the build's previous status back, which
could leave a build QUEUED without a pod if its completion arrived
meanwhile. The build stays CANCELED with a mark (left out of
responses); a repeated DELETE stops it again instead of getting a 409.
A build that can't start is removed only if it isn't canceled, in one
conditional delete. The docs say that notifications already started
go ahead, and that builds of other repositories get a 404.

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

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Update the OpenAPI contract for the internal build-completion callback and add the authenticated build-cancellation endpoint, its conflict response, and the CANCELED status.

  • pubgrade/api/pubgrade.yaml L396-402, L461-531, L1003-1008 (+1 small edits)

Uses of the API

Expose the cancellation controller and route it to the build-cancellation logic, while clarifying that the existing update controller is an internal completion callback.

  • pubgrade/modules/server.py L10, L145, L157-170

Implementation

Add the cancellation exception and map it to a 409 response.

  • pubgrade/errors/exceptions.py L12, L36-41, L178-182

Implement cancellation and coordinate it with build startup, completion, signing, notifications, and retryable pod and file cleanup.

  • pubgrade/modules/endpoints/builds.py L762-781, L790-888, L1041-1077 (+15 small edits)

Documentation

Document the cancellation endpoint, retained records, completion-callback behavior, cleanup and deployment effects, and the new status value.

  • docs/api.md L18-19, L35-42
  • docs/deployment.md L128-143, L199-203
  • docs/usage.md L94-117

Tests

Test cancellation authorization and responses, retained records, cleanup retries, and lifecycle races across unit and integration coverage.

  • tests/integration/test_api.py L11, L504-631
  • tests/pubgrade/endpoints/test_builds.py L1681-2147 (+4 small edits)
  • tests/pubgrade/test_server.py L14, L356-389

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

read-the-docs-community Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35719934 | 📁 Comparing 06c60a8 against latest (0dae2fb)

  🔍 Preview build  

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

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0dae2fb) to head (06c60a8).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #83   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1408      1471   +63     
=========================================
+ Hits          1408      1471   +63     

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

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

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

## Individual Comments

### Comment 1
<location path="pubgrade/modules/endpoints/builds.py" line_range="956" />
<code_context>
+        else {
+            build["id"]
+            for build in collection("builds").find(
+                {"id": {"$in": build_ids}, "status": {"$nin": [*FINISHED, CANCELED]}},
+                {"id": True, "_id": False},
+            )
</code_context>
<issue_to_address>
**Repository deletion leaves pods running**

When a canceled build still has a pod after cleanup failed, its files directory is absent, and its repository is deleted, `stop_builds` excludes `CANCELED` builds from the pod-cleanup query, so repository deletion removes the build record without stopping the pod, leaving an orphan.

Include canceled builds marked `STOPPING` in the pod-cleanup query used during repository deletion.

Also at `pubgrade/modules/endpoints/builds.py:957`.
</issue_to_address>

### Comment 2
<location path="pubgrade/modules/endpoints/builds.py" line_range="115" />
<code_context>
     failed = any(result["result"] == "failed" for result in results)
     collection("builds").update_one(
-        {"id": build_id},
+        {"id": build_id, **NOT_CANCELED},
         {
             "$set": {
</code_context>
<issue_to_address>
**Canceled builds notify deployments**

When cancellation completes after the completion callback's cancellation check but before dispatch, or before prebuilt-image dispatch begins, `build_completed` checks cancellation separately from notification dispatch, while `publish_prebuilt_image` dispatches before its status update; `notify_all_subscriptions` therefore sends notifications after cancellation completes.

Coordinate notification start with cancellation and check the build status before dispatch in both completion paths.

Also at `pubgrade/modules/endpoints/builds.py:803-807`.
</issue_to_address>

### Comment 3
<location path="tests/pubgrade/test_server.py" line_range="380" />
<code_context>
+        headers={"X-Project-Access-Token": MOCK_REPOSITORIES[1]["access_token"]}
+    ):
+        res = unwrap(deleteBuild)(MOCK_REPOSITORIES[1]["id"], MOCK_BUILD_INFO["id"])
+    assert res == {"id": MOCK_BUILD_INFO["id"]}
+
+
</code_context>
<issue_to_address>
**Build remains active**

When the controller returns the requested ID without canceling the build, `test_deleteBuild` asserts only that the response echoes the requested ID at `tests/pubgrade/test_server.py:380`; a controller that returns that ID without canceling the build passes, leaving its record active.

Assert the stored build is `CANCELED` or verify that `cancel_build` receives the expected arguments.
</issue_to_address>

### Comment 4
<location path="docs/usage.md" line_range="114-116" />
<code_context>
+build. A build that is canceled already gets a 409; an unknown one, or one of
+another repository, gets a 404.
+
+Builds can't be changed: to publish a corrected image, publish it as a new
+build. `PUT /repositories/<repository ID>/builds/<build ID>` is Pubgrade's
+internal callback for finished build pods, not a way to change a build.
+
 ## Change or delete a repository
</code_context>
<issue_to_address>
**Public build update unavailable**

The issue calls for PUT and DELETE methods, but this change uses PUT only as an internal completion callback and says builds cannot be changed. It implements DELETE, leaving the requested public PUT behavior absent.
</issue_to_address>

Linked issues

#3 PUT/DELETE methods for /repositories/{id}/builds · 3 of 4 met

# Requirement Status Notes
1 Implement PUT/DELETE methods for /repositories/{id}/builds 🟡 Partly met DELETE is implemented, but PUT is documented as an internal completion callback rather than a method for modifying a build; corrected builds must be registered with a new POST.
2 Decide what happens if a build is deleted or modified before it starts ✅ Met Canceled builds remain listed with status CANCELED; builds cannot be modified, so a corrected build is registered as a new POST.
3 Decide what happens if a build is started but not finished ✅ Met A running build is canceled and stopped; if stopping fails, it remains canceled and a repeated DELETE retries.
4 Decide what happens if some or all deployments have been notified ✅ Met Already-notified deployments keep what they pulled; the change does not undeploy or notify them again.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and a cancellation can terminate a running build pod, remove its temporary files, and leave the build marked CANCELED, preventing completion and notifications. Reverting the change would not restore that build, but it can be retried as a new build, so the impact is bounded and repairable.

Blocking findings: pubgrade/modules/endpoints/builds.py:956, pubgrade/modules/endpoints/builds.py:115, tests/pubgrade/test_server.py:380, docs/usage.md:116


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

Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread tests/pubgrade/test_server.py Resolved
Comment thread docs/usage.md Resolved
Review findings (Sourcery): repository deletion now also stops canceled
builds whose stop failed (marked), as their pods may be left, and a
prebuilt image canceled before its notifications start notifies no one.
The controller test checks that the build is stored as canceled.

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

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

Linked issues

#3 PUT/DELETE methods for /repositories/{id}/builds · 4 of 5 met

# Requirement Status Notes
1 Provide DELETE/PUT methods for builds. 🟡 Partly met DELETE cancels a build, but PUT is only the internal completion callback; changing a build is handled by registering a new one with POST.
2 Decide what happens when a build is deleted or modified before it starts. ✅ Met Canceled builds stay listed with status CANCELED, including when cancellation happens during startup; a canceled build is kept even if startup then fails.
3 Decide what happens when a build is started but unfinished. ✅ Met Cancellation stops the pod and removes its files; if stopping fails, the build stays canceled and a repeated DELETE retries cleanup.
4 Decide what happens if some or all deployments have been notified. ✅ Met Deployments already notified keep what they pulled; the change does not undeploy, re-notify, or delete registry images.
5 Handle history or revert corner cases after the first build. ✅ Met Cancellation keeps the build record and does not depend on a previous build; users can publish another build to move deployments forward or back.

Comment thread pubgrade/api/pubgrade.yaml Resolved
@uniqueg
uniqueg merged commit f5a3d70 into dev Nov 7, 2026
37 of 46 checks passed
@uniqueg
uniqueg deleted the feat/cancel-build branch November 7, 2026 14:32
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.

PUT/DELETE methods for /repositories/{id}/builds

1 participant