Repository navigation
feat: complete repository PUT and DELETE - #80
Conversation
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]>
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]>
Reviewer's GuideSchema and migrationsAdd the repository lookup index on subscriptions so repository-scoped limits and cascading deletion can find subscriptions efficiently.
APISpecify URL-only repository updates, cascading deletion semantics, and the 404 responses for missing repositories on the affected endpoints.
Uses of the APIReturn a success message after deletion completes, with the endpoint delegating token validation and cascading cleanup to the repository handler.
ImplementationMake repository updates preserve unrelated fields and implement marked, retryable deletion that cleans up repository builds, subscriptions, and user lists.
Coordinate build and subscription registration with repository deletion, withdrawing concurrent additions and stopping any build pod or files that were started.
Reject subscription registration once deletion begins and roll back a subscription and its user-list entry if deletion races with the repository-list update.
DocumentationDocument repository URL changes and cascading deletion for API users, deployments, and the API 2.0.0 upgrade.
TestsCover the repository endpoint’s URL-only update, cascading deletion, cleanup failures, and concurrent registration races at unit and integration levels.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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]>
There was a problem hiding this comment.
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
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]>
There was a problem hiding this comment.
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]>
Summary
Completes
PUTandDELETE /repositories/{id}, as the API specification describes. Only the repository's access token allows either (unchanged).build_listandsubscription_list: its builds were no longer listed and its subscribers no longer notified. A request withouturlgets a 400; an unknown repository gets a 404./repositories/{id}, and toPOST /repositories/{id}/buildsandPOST /subscriptions. Their descriptions now state these semantics.docs/usage.mdgets a new section, "Change or delete a repository".docs/api.mdgets a note.docs/deployment.mddescribes 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).MONGODB_TEST_URI): 20 passed.ruff check,ruff format --check,mypy .: clean.mkdocs build --strict: OK.bec6920, includingCI passed, CodeQL (no open alerts), the upgrade test and the Sourcery review.Review
Full review:
adversarial-reviewerandquality-reviewer, 2 rounds. Fixed:build_listentries after a withdrawal;BASE_DIRonly, checked where files are removed, as when a build is created.Sourcery (13 threads, all answered and resolved). Fixed in
01a8b96: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,
$insize, notifications in flight, and undeploying notified deployments (Pubgrade doesn't control deployments;docs/usage.mdnow says how operators remove them).Declined review findings
stop_buildsindelete_repository(noqa: PLC0415):buildsimports fromrepositories, so a module-level import would be circular. Removing the cycle means moving shared helpers (generate_idand others) into a new module, which touches every endpoint module. That is a separate refactor.ensure_accepting. The subscription rollback differs (user list, then repository list) and stays inline in its only caller.PUTwhile a repository is being deleted: changing the URL during a deletion is harmless; the repository is gone afterwards either way.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