Skip to content

feat: complete repository PUT and DELETE - #80

Merged
uniqueg merged 7 commits into
devfrom
feat/repository-put-delete
Nov 7, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/repository-put-delete

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Summary

Completes PUT and DELETE /repositories/{id}, as the API specification describes. Only the repository's access token allows either (unchanged).

  • PUT changes only the URL. Before, it replaced the whole document, so the repository lost its build_list and subscription_list: its builds were no longer listed and its subscribers no longer notified. A request without url gets a 400; an unknown repository gets a 404.
  • DELETE deletes the repository permanently, with its builds and subscriptions; the subscriptions also leave their users' lists. Before, builds and subscriptions were left behind. The spec already said that delete "removes available builds and discard[s] administrator's subscription". Deployments that were notified keep their images; Pubgrade doesn't undeploy.
    • With builds switched on, Pubgrade first deletes the pods and files of unfinished builds, and the files left by finished builds whose cleanup failed. If a pod can't be deleted, the request gets a 500. The repository, its builds and subscriptions stay, so the request can be repeated.
    • Concurrent registrations: the repository is marked first. New builds and subscriptions then get a 404. A build or subscription registered meanwhile removes itself again (document, list entry, pod and files). If the deletion fails, the mark is removed.
  • The spec adds 404 responses to PUT and DELETE of /repositories/{id}, and to POST /repositories/{id}/builds and POST /subscriptions. Their descriptions now state these semantics.
  • Docs: docs/usage.md gets a new section, "Change or delete a repository". docs/api.md gets a note. docs/deployment.md describes the effect on builds and adds a note to the upgrade notes for API 2.0.0.

Build-level PUT and DELETE (#3) are not part of this PR; they wait for a product decision.

Closes #6

Verification

  • uv run --locked pytest --cov: 570 passed, coverage 100%. This includes new unit tests (cascade, stopping builds, failure and rollback, deletion races) and integration tests (PUT keeps builds and subscriptions; DELETE cascade with 401 and 404; a running build stopped, using local Git fixtures and mocked Kubernetes).
  • Integration tests against MongoDB 7.0.34 (MONGODB_TEST_URI): 20 passed.
  • ruff check, ruff format --check, mypy .: clean.
  • mkdocs build --strict: OK.
  • CI: all checks passed on bec6920, including CI passed, CodeQL (no open alerts), the upgrade test and the Sourcery review.

Review

Full review: adversarial-reviewer and quality-reviewer, 2 rounds. Fixed:

  • races with concurrent registrations, handled with a deletion mark;
  • dangling build_list entries after a withdrawal;
  • a pod whose creation failed during a deletion;
  • the mark left set after a failure;
  • doc wording on partial failure;
  • docstrings;
  • the API table;
  • CodeQL path findings: build directories are resolved within BASE_DIR only, checked where files are removed, as when a build is created.

Sourcery (13 threads, all answered and resolved). Fixed in 01a8b96:

  • a mark per deletion, so a failed one doesn't reopen an overlapping one;
  • errors removing build files now fail the deletion, which can be repeated;
  • a 10-second timeout for pod deletion;
  • an index on subscriptions.repository_id, with an upgrade note for deployments with their own configuration.

Declined, with reasons in the threads: transactions (MongoDB isn't guaranteed to be a replica set; a repeated DELETE finishes the deletion), old replicas during a rollout, builds dropped from the list by the earlier PUT bug, cleanup with builds switched off, $in size, notifications in flight, and undeploying notified deployments (Pubgrade doesn't control deployments; docs/usage.md now says how operators remove them).

Declined review findings

  • Function-local import of stop_builds in delete_repository (noqa: PLC0415): builds imports from repositories, so a module-level import would be circular. Removing the cycle means moving shared helpers (generate_id and others) into a new module, which touches every endpoint module. That is a separate refactor.
  • A shared helper for the subscription and build withdrawal: builds use one helper, ensure_accepting. The subscription rollback differs (user list, then repository list) and stays inline in its only caller.
  • Refusing PUT while a repository is being deleted: changing the URL during a deletion is harmless; the repository is gone afterwards either way.
  • A finished build whose pod deletion failed in build_completed: its files are already gone, so a later repository deletion doesn't find it. Deleting a pod per build of the whole history was dropped again for its cost. This cleanup gap is older than this PR.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 7, 2026 11:42
DELETE /repositories/{id} now also deletes the repository's builds and
subscriptions (also from their users' lists), as the API specification
describes. With builds switched on, unfinished builds are stopped first:
their pods are deleted and their files removed. If a pod can't be
deleted, nothing else is, so the request can be repeated.

PUT /repositories/{id} now changes only the URL; it replaced the whole
document before, so the repository lost its builds and subscriptions.

Refs #6

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deleting a repository now marks it first. Builds and subscriptions
registered meanwhile get a 404 and remove themselves again, including a
build pod that started during the deletion. Deletion removes the pods
and files of all the repository's builds, also finished ones whose
cleanup failed. If a pod can't be deleted, the mark is removed again.

Review findings: doc wording on partial failure, docstrings, the API
table, and 404 responses of the build and subscription registrations.

Refs #6

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A build withdrawn because its repository is being deleted now also
leaves the repository's list, so a failed deletion leaves no dangling
entry. A build whose pod creation failed is withdrawn too. The mark is
removed on any failure of the deletion, not only of pod deletion.
Deletion stops only unfinished builds and those with files left, so a
long history needs no Kubernetes calls per build.

Refs #6

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

Schema and migrations

Add the repository lookup index on subscriptions so repository-scoped limits and cascading deletion can find subscriptions efficiently.

  • pubgrade/config.yaml L40-42

API

Specify URL-only repository updates, cascading deletion semantics, and the 404 responses for missing repositories on the affected endpoints.

  • pubgrade/api/pubgrade.yaml L199-206 (+5 small edits)

Uses of the API

Return a success message after deletion completes, with the endpoint delegating token validation and cascading cleanup to the repository handler.

  • pubgrade/modules/server.py L73, L89-90, L98-99

Implementation

Make repository updates preserve unrelated fields and implement marked, retryable deletion that cleans up repository builds, subscriptions, and user lists.

  • pubgrade/modules/endpoints/repositories.py L205-248, L254-261, L269-319 (+7 small edits)

Coordinate build and subscription registration with repository deletion, withdrawing concurrent additions and stopping any build pod or files that were started.

  • pubgrade/modules/endpoints/builds.py L644-655, L782-788, L793-910 (+11 small edits)

Reject subscription registration once deletion begins and roll back a subscription and its user-list entry if deletion races with the repository-list update.

  • pubgrade/modules/endpoints/subscriptions.py L113-132 (+4 small edits)

Documentation

Document repository URL changes and cascading deletion for API users, deployments, and the API 2.0.0 upgrade.

  • docs/api.md L30-33
  • docs/deployment.md L119-127, L175-182
  • docs/usage.md L94-120

Tests

Cover the repository endpoint’s URL-only update, cascading deletion, cleanup failures, and concurrent registration races at unit and integration levels.

  • tests/integration/test_api.py L348-503
  • tests/pubgrade/endpoints/test_builds.py L1306-1343
  • tests/pubgrade/endpoints/test_repositories.py L34-66, L293-620, L634-879 (+4 small edits)
  • tests/pubgrade/test_server.py L12, L142-154, L465 (removed lines)
  • tests/test_config.py L40-47

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7cfe152) to head (bec6920).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #80   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1322      1408   +86     
=========================================
+ Hits          1322      1408   +86     

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

@read-the-docs-community

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

Copy link
Copy Markdown

Documentation build overview

📚 Pubgrade | 🛠️ Build #35718052 | 📁 Comparing bec6920 against latest (7cfe152)

  🔍 Preview build  

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

Repository deletion resolves the directories of builds within
BASE_DIR only, as creating a build does, and skips any other.

Refs #6

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review November 7, 2026 11:14
@uniqueg
uniqueg requested a review from akash2237778 as a code owner November 7, 2026 11:14

@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 13 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="828" />
<code_context>
+        delete_pod(build_id, namespace, missing_ok=True)
+        build_dir = build_dirs[build_id]
+        if build_dir is not None:
+            remove_build_dir(build_dir, build_id)
+        logger.info("Stopped build %s.", build_id)
+
</code_context>
<issue_to_address>
**Build secrets remain on disk**

When removing a build directory raises an OSError, `remove_build_dir` suppresses the error, so `stop_builds` continues and `delete_repository` removes the build and repository records while files—including registry credentials and the project access token—remain without a record to retry cleanup.

Make directory-removal failures stop the deletion and preserve the records needed to retry cleanup.

Also at `docs/deployment.md:119-121`.
</issue_to_address>

### Comment 2
<location path="pubgrade/modules/endpoints/repositories.py" line_range="297" />
<code_context>
+                {"subscription_list": {"$in": subscription_ids}},
+                {"$pull": {"subscription_list": {"$in": subscription_ids}}},
+            )
+            db_collection_subscriptions.delete_many({"id": {"$in": subscription_ids}})
+        if build_ids:
+            collection("builds").delete_many({"id": {"$in": build_ids}})
</code_context>
<issue_to_address>
**Failed deletes leave partial cleanup**

When a database operation fails after a cascade write succeeds, `delete_repository` clears only the `deleting` mark in its exception handler; earlier user-list or subscription deletions remain committed while the repository remains, so the caller gets a failed request and a retry cannot restore the original subscriptions.

Run the cascade in a transaction or otherwise roll back its earlier writes when a later operation fails.

Also at `pubgrade/modules/endpoints/repositories.py:301-305`.
</issue_to_address>

### Comment 3
<location path="pubgrade/modules/endpoints/repositories.py" line_range="270" />
<code_context>
-    return is_deleted.deleted_count
+    # The builds as of the mark: builds registered later remove themselves
+    data = db_collection.find_one_and_update(
+        {"id": repo_id},
+        {"$set": {"deleting": True}},
+        return_document=ReturnDocument.AFTER,
</code_context>
<issue_to_address>
**Concurrent delete reopens registrations**

When two DELETE requests overlap and one fails while the other is still processing, both requests can mark the repository, and the failing request unsets the shared `deleting` mark while the other uses its earlier cleanup snapshot. Registrations then pass `ACCEPTING` after that snapshot, leaving orphaned builds or subscriptions when the repository is removed.

Claim deletion atomically and clear the mark only when it is still owned by the failing request.

Also at `pubgrade/modules/endpoints/repositories.py:269`, `pubgrade/modules/endpoints/repositories.py:271`, `pubgrade/modules/endpoints/repositories.py:277`, `pubgrade/modules/endpoints/repositories.py:302-305`.
</issue_to_address>

### Comment 4
<location path="pubgrade/modules/endpoints/builds.py" line_range="176-177" />
<code_context>
-        db_collection_repositories.update_one(
-            {"id": repository_id}, {"$push": {"build_list": build_data["id"]}}
+        pushed = db_collection_repositories.update_one(
+            {"id": repository_id, **ACCEPTING},
+            {"$push": {"build_list": build_data["id"]}},
         )
+        if pushed.matched_count == 0:
</code_context>
<issue_to_address>
**Old replicas create orphan records**

When a registration reaches an old application replica during a rolling deployment, the old replica does not check `deleting`, so it can add a build or subscription after the new replica takes its cleanup snapshot; deletion then removes the repository without removing that new data.

Ensure old replicas cannot register against a repository being deleted before enabling this deletion flow.

Also at `pubgrade/modules/endpoints/repositories.py:269-273`.
</issue_to_address>

### Comment 5
<location path="pubgrade/modules/endpoints/builds.py" line_range="887-891" />
<code_context>
+    )
+    try:
+        stop_builds([build_id])
+    except Exception as error:
+        logger.error(
+            "Build %s could not be stopped: %s", build_id, type(error).__name__
+        )
+    collection("builds").delete_one({"id": build_id})
+    logger.info("Removed build %s, whose repository is being deleted.", build_id)
+
</code_context>
<issue_to_address>
**Failed withdrawal loses cleanup record**

When deletion misses an in-flight build and its later pod-deletion request fails, `withdraw_build` suppresses the `stop_builds` failure and deletes the build document anyway, leaving the pod and files without a record to retry cleanup.

Keep the build document until stopping the build succeeds.
</issue_to_address>

### Comment 6
<location path="pubgrade/modules/endpoints/repositories.py" line_range="276" />
<code_context>
+    )
+    if data is None:
+        raise RepositoryNotFound
+    build_ids: list[str] = data.get("build_list", [])
+    subscription_ids = list(data.get("subscription_list", []))
+    try:
</code_context>
<issue_to_address>
**Older builds survive repository deletion**

When a repository has build records whose IDs were erased from `build_list` by an earlier PUT, `delete_repository` gets build IDs only from `build_list`, so it skips stopping those builds and deleting their documents; their pods and files can remain after the repository is removed.

Find and clean up the repository’s build records even when their IDs are missing from `build_list`.

Also at `pubgrade/modules/endpoints/repositories.py:298-299`.
</issue_to_address>

### Comment 7
<location path="pubgrade/modules/endpoints/builds.py" line_range="817-818" />
<code_context>
+    stopping = [
+        build_id
+        for build_id, build_dir in build_dirs.items()
+        if build_id in unfinished
+        or (build_dir is not None and os.path.isdir(build_dir))
+    ]
+    if not stopping:
</code_context>
<issue_to_address>
**Failed pod cleanup leaves pods running**

When a completed build's directory was removed but its pod deletion failed during completion, a finished build's files were removed before its pod deletion failed, so `stop_builds` excludes it when its directory is absent and never retries deleting the pod; repository deletion then succeeds with the pod still running.

Track or otherwise check for pods left by failed completion cleanup so repository deletion retries deleting them even when their files are gone.

Also at `docs/deployment.md:119-121`.
</issue_to_address>

### Comment 8
<location path="pubgrade/modules/endpoints/builds.py" line_range="825" />
<code_context>
+    load_cluster_config()
+    namespace = os.getenv("NAMESPACE") or "default"
+    for build_id in stopping:
+        delete_pod(build_id, namespace, missing_ok=True)
+        build_dir = build_dirs[build_id]
+        if build_dir is not None:
</code_context>
<issue_to_address>
**Pod API stalls deletion indefinitely**

When the Kubernetes API connection stalls rather than returning an error, `delete_pod` calls Kubernetes without a request timeout, so a stalled API call blocks the synchronous delete request while the repository remains marked as deleting; the exception handler never runs to clear the mark.

Set a bounded timeout on pod deletion and ensure a timed-out request leaves the repository in a recoverable state.
</issue_to_address>

### Comment 9
<location path="pubgrade/modules/endpoints/builds.py" line_range="804" />
<code_context>
+        DeletePodError: Raised when a pod can't be deleted; the builds after
+            it are left as they are.
+    """
+    if not builds_enabled() or not build_ids:
+        return
+    unfinished = {
</code_context>
<issue_to_address>
**Disabled builds leave pods behind**

When builds are switched off while a repository still has builds or build files, `stop_builds` returns without inspecting or stopping existing builds, but `delete_repository` continues deleting their build records and the repository; pods and build files from when builds were enabled are orphaned.

Determine whether a repository has build artifacts independently of the current setting, and clean them up or refuse deletion when cleanup is unavailable.
</issue_to_address>

### Comment 10
<location path="pubgrade/modules/endpoints/builds.py" line_range="808-809" />
<code_context>
+        return
+    unfinished = {
+        build["id"]
+        for build in collection("builds").find(
+            {"id": {"$in": build_ids}, "status": {"$nin": FINISHED}},
+            {"id": True, "_id": False},
+        )
</code_context>
<issue_to_address>
**Large build histories block deletion**

When a repository has accumulated enough build IDs for the query to exceed MongoDB's command-size limit, the unbounded `build_ids` list becomes one MongoDB `$in` query; once the query exceeds MongoDB's BSON command-size limit, `stop_builds` fails and the repository cannot be deleted through this path.

Process build IDs in bounded batches when querying and stopping builds.
</issue_to_address>

### Comment 11
<location path="pubgrade/modules/endpoints/builds.py" line_range="202" />
<code_context>
     if not build_path:
+        # The repository's deletion may have started after the build was
+        # listed, and missed it in the database
+        ensure_accepting(repository_id, build_data["id"])
         publish_prebuilt_image(
             build_data["id"],
</code_context>
<issue_to_address>
**Notifications race with deletion**

When a prebuilt build passes `ensure_accepting` just before a concurrent deletion marks the repository, `ensure_accepting` can pass just before deletion marks the repository, after which `publish_prebuilt_image` still notifies the saved subscription IDs. A deployment can therefore receive an image notification while its repository is being deleted.

Coordinate prebuilt publication with deletion so deletion cannot complete while a previously admitted build is still notifying subscriptions.
</issue_to_address>

### Comment 12
<location path="pubgrade/modules/endpoints/repositories.py" line_range="287" />
<code_context>
+                *(
+                    subscription["id"]
+                    for subscription in db_collection_subscriptions.find(
+                        {"repository_id": repo_id}, {"id": True, "_id": False}
+                    )
+                ),
</code_context>
<issue_to_address>
**Repository deletion scans subscriptions**

When the subscriptions collection grows large, the `subscriptions.find` query filters on `repository_id`, but the configured subscription indexes cover only `id`. Deleting a repository therefore scans the entire subscriptions collection, making deletion increasingly slow as subscriptions accumulate.

Add an index on `subscriptions.repository_id` for this deletion query.
</issue_to_address>

### Comment 13
<location path="pubgrade/modules/endpoints/repositories.py" line_range="297" />
<code_context>
+                {"subscription_list": {"$in": subscription_ids}},
+                {"$pull": {"subscription_list": {"$in": subscription_ids}}},
+            )
+            db_collection_subscriptions.delete_many({"id": {"$in": subscription_ids}})
+        if build_ids:
+            collection("builds").delete_many({"id": {"$in": build_ids}})
</code_context>
<issue_to_address>
**Existing deployments remain**

The issue asks how to remove deployments that have already been notified. The change deletes subscriptions, stopping future notifications, but does not remove or selectively remove those existing deployments.
</issue_to_address>

Linked issues

#6 PUT/DELETE methods for /repositories/{id} · 2 of 3 met

# Requirement Status Notes
1 Provide a useful PUT alternative to deleting and re-registering a repository. ✅ Met PUT changes the URL while preserving the repository's identifier, access token, builds, and subscriptions.
2 Delete a repository and its builds and subscriptions. ✅ Met DELETE removes the repository's builds and subscriptions, including subscription entries in users' lists.
3 Remove some or all deployments that have already been notified. 🟡 Partly met Deleting the subscription stops future notifications, but already-notified deployments and their images remain.

Sourcery assessment

Needs a human reviewer. 13 findings to address first, and deleting a repository now permanently removes its build and subscription records, build files, and associated build pods; reverting will not restore those records or files. The deletion is scoped to the repository explicitly named in the request, but lost data may need to be recovered from backups.

Blocking findings: pubgrade/modules/endpoints/builds.py:828, pubgrade/modules/endpoints/repositories.py:297, pubgrade/modules/endpoints/repositories.py:270, pubgrade/modules/endpoints/builds.py:177, pubgrade/modules/endpoints/builds.py:891, and 8 more


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 pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Comment thread pubgrade/modules/endpoints/builds.py Resolved
Each deletion sets its own mark and removes only that one when it
fails, so an overlapping deletion keeps its mark. Files of builds that
can't be removed now fail the deletion, which can then be repeated.
Pod deletion waits at most 10 seconds for the Kubernetes API. The
subscriptions get an index on repository_id.

Refs #6

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

#6 PUT/DELETE methods for /repositories/{id} · 1 of 2 met

# Requirement Status Notes
1 Explain when PUT is useful instead of DELETE and registering a new repository. ✅ Met PUT changes the URL while preserving the repository identifier, access token, builds, and subscriptions, and the usage documentation describes this behavior.
2 Explain how to remove some or all deployments that have already been notified. ❌ Not addressed The change explicitly says notified deployments keep their images; it adds no way to remove deployments that already received a notification.

The check that build directories stay in BASE_DIR now sits next to
the removal itself. The usage docs say how notified deployments are
removed.

Refs #6

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 654e344 into dev Nov 7, 2026
46 checks passed
@uniqueg
uniqueg deleted the feat/repository-put-delete branch November 7, 2026 11:41
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}

2 participants