Skip to content

fix: bound pending and unused service types - #254

Merged
uniqueg merged 5 commits into
devfrom
fix/bound-service-types
Oct 26, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/bound-service-types

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Bounds what pending and unused service types cost, and how many of them users can add.

Pending flag on services

  • Pending services now carry an internal, indexed flag (_pending, sparse index). It is never served, because PROJECTION excludes it.
  • Reads filter by this flag instead of an $or over every pending type. The old filter grew with the number of pending types and could exceed MongoDB's 16 MB BSON limit. The new filter has the same size for any number of them.
  • How the flag is kept in sync with the type:
    • Registrations validate the service, store its pending type, and write the flag from the type's state.
    • After the write, the registration syncs the flag again. The sync only touches the service if it still has that type, and it checks the type again after setting the flag, so neither concurrent type changes nor approvals are undone.
    • Approvals, and types restored after a failed removal, sync the flags of the type's services the same way (also when the type was already approved): write, check the type again, and write again until its state is stable.
    • On startup, sync_pending_services() reconciles the flags of the pending types and of the types of flagged services.
  • GET /approvals, visible_services() (used by GET /services, GET /services/{id} and GET /verifications) and the pending-update check all use the flag.

Limit on unused types

  • New option custom.access_control.max_unused_service_types, default 10; null means no limit and 0 means only admins can add new types.
  • It limits how many types without any service a user other than an admin may have added, in every mode. Approved types count too.
  • When the limit is reached, POST /services/types returns 409, and so do POST and PUT /services with a new type. The detail says what to do.
  • Counting runs one aggregation per 100 of the user's types.

Validation before pending types are stored

  • Services are validated before their pending type is stored, so registrations that fail validation leave no pending type behind.
  • Unstorable strings in a service's type are now reported as type.<field>.

Indexes

service_types.pending (sparse), service_types.created_by, and services._pending (sparse).

Docs

  • docs/configuration.md:
    • Fixes the rolling-update note: 0.4.0 stores no types, and the startup backfill adds them as approved.
    • Documents the limit.
    • Documents the remaining abuse vector (per-user limits against accounts anyone can create) and recommends rate limits for POST /services/types and POST /services, linking Rate limits.
  • docs/api.md (pending approvals, limits) and the OpenAPI descriptions of POST /services, PUT /services/{id} and POST /services/types are updated to match.

Closes #246

Verification

All checks below passed locally.

Check Result
pytest against MongoDB 7.0.34, with coverage 1254 passed, 228 skipped; coverage 100%
pytest with mongomock passed (MongoDB-only tests skip)
ruff check, ruff format passed
mypy cloud_registry tests passed
mkdocs build --strict passed
pre-commit run --all-files (includes semgrep and ast-grep) passed

The 228 Helm chart tests did not run locally because Helm isn't installed; CI runs them.

New tests:

  • 60000 long pending types: reads stay well under the BSON limit.
  • The flag is set, not served, cleared on approval (also on a repeated approval), and follows type changes.
  • An approval during a registration, and an approval during the flag sync.
  • A concurrent type change.
  • Startup reconciliation.
  • The limit in modes open and moderated, with admins exempt, null, 0, changes of service types, deletions, batches and approved types.
  • Index creation.
  • A concurrent duplicate type.
  • No pending type left after failed validation.

Declined review findings

  • Rolling upgrade from 0.4.0 replicas writing unflagged pending services: 0.4.0 has no moderated mode, and the docs say to switch to moderated only once all instances support it.
  • Fast path in visible_services(): if no service is flagged, it returns no filter, so a pending service stored between that check and the read could be served once. The old code had the same window (no pending type at check time). The handler unit tests also call reads outside an API request, where FOCA's resource_filter() can't run.
  • validate() runs twice per registration (in the server and in register_metadata()): the duplicate work is one indexed query. It keeps register_metadata() safe to call on its own.
  • Two code paths return "The service type is registered." in POST /services/types: the pre-check keeps the limit from rejecting types that already exist, and the insert still handles races.
  • The index test and the 60000-types test skip with mongomock: CI runs the suite against MongoDB 7.0 too.
  • _count_unused_types doesn't use $lookup: CI also runs with mongomock, which doesn't support $lookup with pipelines, so counting is batched instead.

Declined Sourcery findings (answered in their threads):

  • A crash between the write and the flag sync can leave a service hidden. It never leaves one visible. Any later write of the service, a repeated approval or the next startup corrects it. Atomic writes would need transactions, which need a replica set.
  • Deleting services leaves more types unused than the limit. A delete can't be rejected; each such type takes one registration, which rate limits bound. This is now documented in configuration.md.
  • The $ne: true filter can't use the sparse index. Listings scan all services anyway, and lookups by id use the unique index on id.
  • Counting work grows with a user's used types. One aggregation per 100 types; each used type takes one registration.
  • Long types could exceed the BSON limit in a batch. Type fields are limited to 256 characters, so a batch stays at about 80 kB.

CI on 90184d4 (before the Sourcery fixes): all checks passed, including CI passed.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 26, 2026 01:29
Mark pending services with an indexed internal flag, set when they are
stored and cleared by approvals, and reconciled on startup, so that the
visibility filter no longer lists every pending type and stays the same
size for any number of them.

Limit how many types that no service has each user other than an admin
may have added (custom.access_control.max_unused_service_types, 10 by
default), in every mode, and validate services before storing their
pending type, so that failed registrations leave none behind. Index
pending types and their creators, and document the remaining abuse
vector with a recommendation to rate-limit writes.

Closes #246

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only change the flag of a service that still has the type that was
checked, so that a concurrent change of its type isn't overwritten, and
check the type again after setting flags, so that an approval meanwhile
isn't undone. Correct the API and configuration docs on pending types
and rate limits, and test changes of types against the limit, indexes
and the races.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Count a user's unused types with one aggregation per 100 types instead
of one query per type, as users may have added any number of types that
services have. Approved types count too: drop "approve" from the 409
detail and the docs. Make the test of deleted services tell the states
apart.

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

The PR bounds pending-service read filters with an indexed _pending flag, keeps that derived state consistent through registrations, approvals, concurrent changes, and startup reconciliation, and limits non-admin users’ unused service types across all creation paths; it also validates before persisting pending types, updates API/docs, adds supporting indexes, and provides extensive regression coverage.

Sequence diagram for pending service registration and flag synchronization

sequenceDiagram
    participant Client
    participant Server
    participant Types as service_types
    participant Services as services

    Client->>Server: POST /services
    Server->>Server: validate()
    Server->>Types: check_service_type()
    Server->>Types: store_pending_type()
    Server->>Types: is_pending()
    Server->>Services: register_metadata()
    Server->>Services: sync_pending_flag()
    Services-->>Server: Set or clear _pending if type still matches
    Server-->>Client: Registration response
Loading

Sequence diagram for pending type approval and service visibility

sequenceDiagram
    participant Admin
    participant API
    participant Types as service_types
    participant Services as services
    participant Reader

    Admin->>API: PUT /services/types/approval
    API->>Types: find_one_and_update()
    API->>Services: update_many()
    Services-->>API: Clear _pending flags
    Reader->>Services: visible_services()
    Services-->>Reader: Query _pending != true
    Reader->>Services: PROJECTION
    Services-->>Reader: Services without _pending
Loading

Flow diagram for unused service type limit enforcement

flowchart TD
    Request[Add or change to a new service type] --> Existing{service_type_exists}
    Existing -->|Yes| Registered[Return registered-type conflict]
    Existing -->|No| Admin{Admin or unlimited}
    Admin -->|Yes| Store[Store service type or service]
    Admin -->|No| Count[_count_unused_types]
    Count --> Limit{Limit reached}
    Limit -->|Yes| Conflict[Return UnusedTypesLimit conflict]
    Limit -->|No| Store
Loading

File-Level Changes

Change Details Files
Replace dynamically generated pending-service visibility filters with a bounded, indexed internal flag and reconcile that flag across the service lifecycle.
  • Added sparse _pending storage and excluded it from API projections.
  • Set or clear flags during registration, type changes, approvals, and startup reconciliation with concurrency-aware checks.
  • Updated service reads, approvals, and pending-update authorization to query the flag.
  • Added indexes for pending services and pending service types.
cloud_registry/app.py
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_types.py
tests/test_service_types.py
Enforce a configurable per-user limit on service types that have no service.
  • Added max_unused_service_types, defaulting to 10, with null for unlimited and 0 for non-admin prohibition.
  • Counted unused types in indexed batches, including approved types, and enforced the limit for explicit type creation and new types introduced through service registration or updates.
  • Returned conflict responses with remediation guidance and preserved race-safe duplicate handling.
  • Added a created_by index to support counting.
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service_types.py
cloud_registry/service_models/custom_config.py
tests/test_service_types.py
Validate services before creating pending types and improve validation error paths.
  • Extracted reusable service validation so invalid registrations leave no pending type behind.
  • Applied type-qualified field names to invalid stored-string errors.
  • Updated registration error handling for unused-type limit conflicts.
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service.py
cloud_registry/ga4gh/registry/service_types.py
tests/test_service_types.py
Align API descriptions and operational documentation with the new pending-state model and unused-type limit.
  • Documented conflict behavior and configuration for all affected service and type endpoints.
  • Corrected rolling-update and startup backfill guidance.
  • Documented remaining per-account abuse considerations and recommended ingress rate limiting.
cloud_registry/api/additions.openapi.yaml
docs/api.md
docs/configuration.md
Expand regression coverage for bounded reads, consistency, concurrency, limits, validation, and indexes.
  • Added tests for large pending-type sets and hidden internal flags.
  • Covered approvals, startup reconciliation, concurrent registration/type changes, and repeated approvals.
  • Covered limit modes, batches, deletions, service changes, admins, unlimited and zero configurations, duplicate races, and index creation.
tests/test_service_types.py

Assessment against linked issues

Issue Objective Addressed Explanation
#246 Bound the cost of reads involving pending service types so it does not grow with the number of unused pending types or exceed MongoDB’s BSON document limit. ✅
#246 Enforce a configurable cap on unused service types added by non-admin users in both open and moderated modes, exempt admins, and avoid storing pending types for registrations that fail validation where possible. ✅
#246 Add the required indexes and document the startup backfill behavior, remaining abuse vector, and recommended rate limits. ✅

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

# Conflicts:
#	docs/api.md
#	tests/test_service_types.py
@uniqueg
uniqueg marked this pull request as ready for review October 26, 2026 10:13
@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 (d7fed28) to head (487c5f3).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #254   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           17        17           
  Lines         1623      1683   +60     
=========================================
+ Hits          1623      1683   +60     

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

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

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

## Individual Comments

### Comment 1
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="323" />
<code_context>
+        if is_pending(service_type):
+            return
+    services.update_many(
+        {**query, PENDING_SERVICE: True}, {"$unset": {PENDING_SERVICE: ""}}
+    )
+
</code_context>
<issue_to_address>
**Pending services become visible**

When a type is removed and re-added as pending while startup reconciliation, approval cleanup, or `_sync_flags()` is clearing service flags, `_sync_flags()` and `putServiceTypeApproval()` can clear `_pending` from services after the type is pending again, so ordinary readers see services that should remain hidden.

Make flag clearing conditional on the same approval state or version it observed, so stale cleanup cannot clear flags after a type is re-added as pending.

Also at `cloud_registry/ga4gh/registry/service_types.py:717-719`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="717-720" />
<code_context>
         {**document, PENDING: True}, {"$unset": {PENDING: ""}}
     )
+    # also if the type was approved before, to clear flags missed meanwhile
+    get_collection("services").update_many(
+        {**_services_of_type(document), PENDING_SERVICE: True},
+        {"$unset": {PENDING_SERVICE: ""}},
+    )
     if approved is None:
         if not service_type_exists(document):
</code_context>
<issue_to_address>
**Re-added pending services become visible**

When an admin removes a pending type with no services, another admin approves it during the deletion race, and a user re-adds the type and registers a service before the approval handler clears flags, `putServiceTypeApproval()` clears the service flags before checking whether the type still exists. If a user re-adds the type as pending and registers a service during that interval, the approval handler clears its flag, then returns because the type exists without approving it; the pending service is consequently visible to readers who should not see it.

Make approval and flag clearing race-safe by rechecking the type state after clearing flags and restoring pending flags for matching services if the type is pending again.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/server.py" line_range="302" />
<code_context>
             service_type, created_by=created_by, pending=service_types_pending()
         )
+        # if the type was approved (or removed and added) meanwhile
+        sync_pending_flag(service.data["id"], service_type)
     if service.verification_removed:
         logger.info(
</code_context>
<issue_to_address>
**Approved service stays hidden**

When an approved type is removed while a moderated user registers a service with it, and `_restore_type()` runs after that registration’s flag sync, the registration sync can finish before `deleteServiceType()` calls `_restore_type()`. If the removed type was approved, `_restore_type()` then clears `pending` from the type but does not clear the service’s `_pending` flag, so the approved service stays hidden and non-admin updates are rejected until reconciliation.

Synchronize matching service flags when `_restore_type()` restores a type, clearing them when the restored type is approved.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/service.py" line_range="432" />
<code_context>
     warn_invalid_urls,
     warn_url_schemes,
 )
-from cloud_registry.ga4gh.registry.service_types import add_service_types
+from cloud_registry.ga4gh.registry.service_types import (
</code_context>
<issue_to_address>
**Approved services stay hidden**

When an admin approves the type after `service.pending` is set but before the service is written, and registration stops after the write but before `sync_pending_flag()`, the service is written with the earlier `service.pending` value, so an approval that cleared flags before this write misses the service. If registration stops before `sync_pending_flag()`, the now-approved service remains hidden until a later startup reconciliation.

Ensure interrupted registrations trigger reconciliation independently of a future app startup, or make the service write and pending-state update atomic with respect to approval.
</issue_to_address>

### Comment 5
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="532" />
<code_context>
+        return
+    if not may_add_service_types():
         raise UnregisteredServiceType(service_type)
+    check_unused_types()


</code_context>
<issue_to_address>
**Service changes bypass the type limit**

When a user registers services with distinct new types while those types are in use, then deletes the services or changes them to other types, `check_service_type()` checks the limit only when a type is first added, while deleting a service or changing it away from a type can make that type unused without a corresponding check. A user can register services with many distinct types and then delete them, leaving more unused types than the configured limit.

Enforce the limit when a service deletion or type change would make a user-added type unused, or otherwise track and cap the number of types a user can cause to become unused.
</issue_to_address>

### Comment 6
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="381" />
<code_context>
         # admins see all services
         return {}
-    return {"$or": [{"$nor": [pending]}, own]}
+    return {"$or": [{PENDING_SERVICE: {"$ne": True}}, own]}
+
+
</code_context>
<issue_to_address>
**Pending reads scan all services**

When at least one service is pending, `visible_services()` filters with `_pending: {$ne: true}`, which also matches the many documents where the sparse index has no entry. MongoDB therefore cannot use that index to satisfy the non-pending branch and scans the services collection on list and lookup requests, including verification reads.

Use a query/index representation that lets MongoDB efficiently find non-pending services, including documents where the flag is absent.

Also at `cloud_registry/config.yaml:172`.
</issue_to_address>

### Comment 7
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="351-357" />
<code_context>
+    `_sync_flags()`). Queries once per distinct type of the stored services,
+    not per stored type.
+    """
+    types = get_collection("services").aggregate(
+        [{"$group": {"_id": {field: f"$type.{field}" for field in TYPE_FIELDS}}}]
+    )
+    for group in types:
+        service_type = type_document(group["_id"])
+        if service_type is not None:
+            _sync_flags(service_type, _services_of_type(service_type))


</code_context>
<issue_to_address>
**Startup reconciliation scales with all types**

When the registry has a large number of distinct service types that are in use, `sync_pending_services()` groups every distinct service type and calls `_sync_flags()` for each, including types that are already approved. Since the unused-type limit does not bound types attached to services, a large registry generates one or more database round trips per distinct type in every worker startup; workers can take too long to boot or fail to become available during a rollout.

Restrict reconciliation to types requiring flag changes and batch the lookups and updates, or otherwise bound the per-worker startup work.
</issue_to_address>

### Comment 8
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="401-411" />
<code_context>
+        Number of such types, at most `limit`.
+    """
+    count = 0
+    types = get_collection("service_types").find({CREATED_BY: user}, TYPE_PROJECTION)
+    while batch := list(islice(types, UNUSED_TYPES_BATCH)):
+        used = get_collection("services").aggregate(
+            [
+                {"$match": {"$or": [_services_of_type(item) for item in batch]}},
+                {"$group": {"_id": {field: f"$type.{field}" for field in TYPE_FIELDS}}},
+            ]
+        )
+        in_use = {_type_key(group["_id"]) for group in used}
+        count += sum(_type_key(item) not in in_use for item in batch)
+        if count >= limit:
+            return limit
+    return count
</code_context>
<issue_to_address>
**Type checks grow slower with history**

When a user accumulates many distinct types that all have services, `_count_unused_types()` runs a service aggregation for every batch and continues through all batches when every type is in use, so each later type addition or service registration does more database work and slows requests.

Bound the total type-counting work per request or replace the per-batch aggregations with a bounded query.
</issue_to_address>

### Comment 9
<location path="cloud_registry/ga4gh/registry/service_types.py" line_range="117" />
<code_context>


+# Number of types per query when counting the unused types of a user
+UNUSED_TYPES_BATCH = 100
+
+
</code_context>
<issue_to_address>
**Long types break type additions**

When a user’s batch contains enough long service-type strings to exceed MongoDB’s command BSON size limit, `_count_unused_types()` builds one aggregation command containing every type in a fixed 100-item batch. Long but valid type strings can make that command exceed MongoDB’s BSON document-size limit, so adding a type or registering a service fails with a server error despite the request and stored type being valid.

Build aggregation batches subject to an encoded BSON-size limit, rather than only a fixed number of types.

Also at `cloud_registry/ga4gh/registry/service_types.py:404`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and if a pending service’s stored flag is missing or cleared incorrectly, the new visibility filter could expose its metadata to users who lack a role on it; reverting cannot undo data already seen. The startup reconciliation and registration/approval synchronization are intended to prevent stale flags, but a defect in those paths could still cause that exposure.

Blocking findings: cloud_registry/ga4gh/registry/service_types.py:323, cloud_registry/ga4gh/registry/service_types.py:720, cloud_registry/ga4gh/registry/server.py:302, cloud_registry/ga4gh/registry/service.py:432, cloud_registry/ga4gh/registry/service_types.py:532, and 4 more


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

Comment thread cloud_registry/ga4gh/registry/server.py Resolved
Write the pending flags of a type's services, check the type again and
write again until its state is stable, so that removals and re-adds as
pending meanwhile end with the right flags. Approvals and restored
types sync flags this way, and startup only checks pending types and
the types of flagged services.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit da25c9b into dev Oct 26, 2026
17 checks passed
@uniqueg
uniqueg deleted the fix/bound-service-types branch October 26, 2026 10:40
uniqueg added a commit that referenced this pull request Oct 26, 2026
Release notes and upgrade steps for #246 (PR #254): the limit of unused
types per user, rate limits, and the new indexes and pending flags that
the app sets up on startup (#249).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.

fix: bound pending and unused service types

1 participant