Skip to content

feat: let admins change a service's ID - #262

Merged
uniqueg merged 4 commits into
devfrom
feat/rename-service
Oct 26, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/rename-service

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Admins can change a service's ID with POST /services/{serviceId}/rename (body {"id": "<new ID>"}). The rename is atomic: the old ID is deleted, and the old and new IDs never exist at the same time. The service keeps its roles, its stored user names, its verification and createdAt; updatedAt is set.

  • Errors:
    • 400: the new ID can't be used in URLs or roles.
    • 404: the service doesn't exist.
    • 409 service-id-taken: the new ID is registered.
    • 409 service-busy: either ID is being renamed or changed.
  • Locks (new collection service_locks):
    • A rename locks both IDs exclusively. PUT/DELETE /services/{serviceId} and granting or revoking roles hold shared locks.
    • Each side waits up to about a second for the other, then returns 409 service-busy.
    • Once both locks are held, the IDs are checked again before anything is changed.
  • Interrupted renames are finished or rolled back when the app starts and before requests (at most every 10 s per worker). Stale locks are claimed once, by a token compare-and-swap.
  • Docs: docs/api.md (endpoint, "Renaming services", conflict codes) and docs/access-control.md (admins).

Closes #243

Verification

  • coverage run --source cloud_registry,scripts -m pytest: 1387 passed, 230 skipped; coverage 100 % (rename.py and locks.py checked again after the last test was added).
  • MongoDB 7 (MONGODB_TEST_URI): tests/ga4gh and tests/test_rename.py, 363 passed.
  • pre-commit run on the changed files: passed.
  • Review:
    • Round 1: adversarial and quality review. Fixed: three races between renames and changes, interrupted renames now also resumed before requests, a docs mismatch, and the quality findings.
    • Round 2: adversarial and quality review. Fixed:
      • the IDs are checked again once both are locked (regression tests test_target_taken_before_lock and test_rename_deleted_before_lock);
      • the Conflict response text;
      • more tests for changes that are retried, fail, or meet interrupted renames.
  • CI: all checks passed (CI passed, Test mongomock and MongoDB 7.0, Lint, Docs, Chart, Smoke test, Scan image, CodeQL, Read the Docs).

Declined review findings

  • ServiceIdTaken stays in rename.py: it is only returned (not raised), and only by renames.
  • Tests patch private module attributes (_claim, _finish, lock waits) to set up races deterministically; kept.
  • A POST /services that generates exactly the new ID while it is being renamed could lose its owner role. Generated IDs are random, so this is not handled. (Sourcery raised the same point.)
  • Sourcery: locks aren't refreshed while an operation runs. They are leases with a one-minute timeout (documented), which only runs out if the database stalls; refreshing them would need a heartbeat per request.
  • Sourcery: verification writes don't wait for renames. They are atomic single-document updates by id, so a request racing a move returns an accurate 404 instead of a 409.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 26, 2026 21:35
Add `POST /services/{serviceId}/rename` (admins only), which moves a
service, with its verification and `createdAt`, its roles and the names
of its users to a new identifier. The service document moves in a single
write, so it is never registered under both identifiers; the roles move
right after it. Renames lock both identifiers (collection
`service_renames`), as MongoDB transactions need a replica set; renames
interrupted after the service moved are finished, and those before it
rolled back, by the next rename after a minute or on startup.

New conflict codes: `service-id-taken`, `rename-in-progress`.

Closes #243

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Changes of a service (PUT, DELETE, granting and revoking roles) could
interleave with a rename: a revoked role moved to the new identifier, a
deletion left the renamed service without roles, and an admin's PUT of
the old identifier took the roles of the renamed service.

Renames now lock both identifiers exclusively, and changes hold shared
locks (collection `service_locks`); each side waits up to about a
second for the other (`409`, code `service-busy`). Interrupted renames
are also resumed before requests (at most every 10 s per worker), not
only on startup, and failures to resume are logged instead of failing
requests. Review findings (adversarial and quality review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The old and new identifiers were checked only before they were locked,
and the roles of the new identifier were then removed unconditionally:
a repeated rename, a rename of another service to the same identifier,
or a registration in between left the service with the new identifier
without roles. Both identifiers are now checked again once locked.

Also from the second review round: the Conflict response names
service-busy for deletions and roles; more tests for changes that wait
for renames, fail, or meet interrupted renames.

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

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds an admin-only service ID rename workflow implemented without MongoDB transactions: both identifiers are exclusively locked, existing service mutations use shared locks, the service document is moved before roles and user names are migrated, and stale or interrupted operations are recovered on startup and periodically before requests. The API, conflict codes, documentation, configuration, and extensive race/failure tests are updated accordingly.

Sequence diagram for atomic service ID rename

sequenceDiagram
    actor Admin
    participant API
    participant Locks as service_locks
    participant Services as services
    participant Roles as roles_and_user_names

    Admin->>API: renameService(serviceId, rename)
    API->>API: _check_id(new_id)
    API->>Locks: _lock(path, source, target)
    Locks-->>API: exclusive tokens for both IDs
    API->>Services: service_exists(source) and service_exists(target)
    API->>Services: update source ID to target
    API->>Roles: _move_roles(path, source, target)
    Roles-->>API: roles and names copied, old entries removed
    API->>Locks: _unlock(source, target, tokens)
    API-->>Admin: 200 new identifier
Loading

Sequence diagram for service mutation synchronization

sequenceDiagram
    participant Client
    participant API
    participant Locks as service_locks
    participant Service

    Client->>API: PUT or DELETE service, or role change
    API->>Locks: changing(serviceId)
    alt rename lock exists
        Locks-->>API: wait up to about one second
        Locks-->>API: ServiceBusy
        API-->>Client: 409 service-busy
    else lock acquired
        API->>Service: perform mutation
        API->>Locks: release shared lock
        API-->>Client: mutation response
    end
Loading

State diagram for interrupted service rename recovery

stateDiagram-v2
    [*] --> Locked: _lock
    Locked --> Moved: _start
    Moved --> Completed: _move_roles
    Completed --> [*]: _unlock
    Moved --> Interrupted: worker failure
    Interrupted --> Resumed: resume_renames
    Resumed --> Completed: _finish
    Resumed --> RolledBack: _finish
    RolledBack --> [*]: unlock
Loading

File-Level Changes

Change Details Files
Adds an admin-only service rename endpoint with identifier validation and documented conflict behavior.
  • Introduces POST /services/{serviceId}/rename accepting a new ID and returning the renamed ID.
  • Preserves service metadata, verification, roles, and stored user names while refreshing updatedAt.
  • Returns 400, 404, and coded 409 responses for invalid IDs, missing services, taken IDs, and busy services.
  • Extends the OpenAPI specification and admin/API documentation.
cloud_registry/api/additions.openapi.yaml
cloud_registry/exceptions.py
cloud_registry/ga4gh/registry/rename.py
docs/api.md
docs/access-control.md
Implements non-transactional, lock-coordinated renames that remain safe across concurrent changes and failures.
  • Adds exclusive identifier locks for renames and shared service locks for PUT, DELETE, and role mutations.
  • Uses ordered writes so the service document moves atomically before roles and user names are migrated.
  • Rechecks source and target state after acquiring both locks to handle races with deletes, registrations, and other renames.
  • Adds stale-lock cleanup, compare-and-swap claiming, interrupted-rename completion or rollback, startup recovery, and periodic pre-request recovery.
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/locks.py
cloud_registry/ga4gh/registry/rename.py
cloud_registry/app.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/permissions.py
Protects all existing service mutations from interleaving with renames.
  • Wraps service replacement and deletion in shared change locks.
  • Wraps granting and revoking user and group roles in shared change locks.
  • Uses the new service-busy conflict response when lock acquisition times out.
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/exceptions.py
Adds comprehensive coverage for successful, concurrent, interrupted, and invalid rename scenarios.
  • Tests metadata and permission migration, admin authorization, validation, conflicts, URL encoding, and logging.
  • Tests lock contention, retry behavior, mutation failures, race conditions, stale locks, and recovery outcomes.
  • Adds mock database configuration for the new lock collection.
tests/test_rename.py
tests/mock_data.py

Assessment against linked issues

Issue Objective Addressed Explanation
#243 Provide an admin-only operation to rename a service while preserving its document metadata, verification, roles, and stored user names under the new ID. ✅
#243 Ensure renames and concurrent changes never expose both IDs or a partially moved service, using safe rollback or recovery without requiring MongoDB transactions. ❌ The service document is moved before its roles and stored names. If the move is interrupted at that point, the service is reachable under the new ID without its roles until stale locks are resumed (potentially after a minute). The locks prevent competing changes, but reads are not blocked, so this exposes the partial state prohibited by the issue’s acceptance criteria.
#243 Return the specified validation, not-found, and conflict errors, log admin renames, and document and test the operation, including failure handling. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #262    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           18        20     +2     
  Lines         1778      1975   +197     
==========================================
+ Hits          1778      1975   +197     

☔ 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 October 26, 2026 21:52

@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="cloud_registry/ga4gh/registry/locks.py" line_range="45" />
<code_context>
+# Age after which locks are stale; renames and changes take a few writes, so
+# they are done by then unless they failed. Keep in sync with "a minute" in
+# `docs/api.md` (Renaming services)
+LOCK_TIMEOUT = timedelta(minutes=1)
+# How long and how often renames and changes wait for each other (in total
+# about a second)
</code_context>
<issue_to_address>
**Live operations lose their locks**

When a legitimate rename or service change runs longer than `LOCK_TIMEOUT`, `lock_exclusive()` and `remove_stale_changes()` treat old shared locks as stale, while `resume_renames()` can claim an active rename using the same unrefreshed timestamp. The original operation then continues without protection and overlaps with another operation, leaving roles, names, or service changes inconsistent.

Refresh lock timestamps while operations are active, or otherwise ensure recovery and lock acquisition cannot treat a live operation as stale.

Also at `cloud_registry/ga4gh/registry/rename.py:145`, `cloud_registry/ga4gh/registry/rename.py:314-328`, `cloud_registry/ga4gh/registry/locks.py:80-83`, `cloud_registry/ga4gh/registry/locks.py:113-121`, `cloud_registry/ga4gh/registry/locks.py:139-140`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/rename.py" line_range="245" />
<code_context>
+            return outcome
+        # As when a service is registered (cf. `_register_service()`); the
+        # new identifier is locked, and isn't registered
+        remove_permissions(target)
+        result = get_collection("services").update_one(
+            {"id": source}, {"$set": {"id": target, UPDATED: format_time(now())}}
</code_context>
<issue_to_address>
**New service loses its owner role**

When a generated-ID registration picks the rename target during the interval between the target check and permission cleanup, `_start()` removes target permissions after checking that the target is unused. If `POST /services` generates that target ID and grants its owner role in between, `remove_permissions(target)` deletes the new service's role, leaving it without an owner.

Make generated-ID registrations coordinate with rename locks or ensure target permissions cannot be removed after a concurrent registration.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/rename.py" line_range="136" />
<code_context>
+    if service_exists(new_id):
+        return problem(ServiceIdTaken())
+    path = services_path()
+    tokens = _lock(path, serviceId, new_id)
+    if tokens is None:
+        return problem(ServiceBusy())
</code_context>
<issue_to_address>
**Verification changes bypass rename locks**

When an admin verifies or removes verification while the service is being renamed, `putServiceVerification()` and `deleteServiceVerification()` do not use `changing()`, so a verification request racing the identifier update can still address the old ID and return `404` after the move instead of applying to the renamed service. Callers see a failed verification change despite the service continuing under its new ID.

Wrap verification writes in `changing(serviceId)` so they wait for the rename or receive `service-busy`.

Also at `cloud_registry/ga4gh/registry/server.py:202-207`.
</issue_to_address>

### Comment 4
<location path="tests/test_rename.py" line_range="265" />
<code_context>
+    after = stored_service(app, NEW_ID)
+    assert after is not None
+    assert after["createdAt"] == before["createdAt"]
+    assert after["updatedAt"] >= before["updatedAt"]
+    assert after[VERIFIED] == before[VERIFIED]
+    assert get(client, NEW_ID).get_json()["id"] == NEW_ID
</code_context>
<issue_to_address>
**Unchanged update timestamp passes**

When the rename leaves `updatedAt` at its existing value, `test_rename` compares timestamps with `>=`, so leaving `updatedAt` unchanged still satisfies the assertion and the test passes.

Make the test prove the timestamp was renewed, for example by setting the stored timestamp to a known earlier value before renaming.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and renaming changes the stored service ID and migrates its roles and user names; if the move is wrong, reverting the code will not restore the old ID or any roles already removed. In particular, roles that fail validation are skipped before the old resource is deleted, so restoring lost access may require manual reconstruction.

Blocking findings: cloud_registry/ga4gh/registry/locks.py:45, cloud_registry/ga4gh/registry/rename.py:245, cloud_registry/ga4gh/registry/rename.py:136, tests/test_rename.py:265


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

Comment thread cloud_registry/ga4gh/registry/locks.py Resolved
Comment thread cloud_registry/ga4gh/registry/rename.py Resolved
Comment thread cloud_registry/ga4gh/registry/rename.py Resolved
Comment thread tests/test_rename.py Resolved
The test accepted an unchanged timestamp; it now starts from an earlier
one (Sourcery review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 4e2c9fe into dev Oct 26, 2026
17 checks passed
@uniqueg
uniqueg deleted the feat/rename-service branch October 26, 2026 22:04
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.

feat: let admins change a service's ID

1 participant