Repository navigation
fix: bound pending and unused service types - #254
Conversation
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]>
Reviewer's GuideThe PR bounds pending-service read filters with an indexed Sequence diagram for pending service registration and flag synchronizationsequenceDiagram
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
Sequence diagram for pending type approval and service visibilitysequenceDiagram
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
Flow diagram for unused service type limit enforcementflowchart 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
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
# Conflicts: # docs/api.md # tests/test_service_types.py
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
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]>
Summary
Bounds what pending and unused service types cost, and how many of them users can add.
Pending flag on services
_pending, sparse index). It is never served, becausePROJECTIONexcludes it.$orover 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.sync_pending_services()reconciles the flags of the pending types and of the types of flagged services.GET /approvals,visible_services()(used byGET /services,GET /services/{id}andGET /verifications) and the pending-update check all use the flag.Limit on unused types
custom.access_control.max_unused_service_types, default10;nullmeans no limit and0means only admins can add new types.POST /services/typesreturns409, and so doPOSTandPUT /serviceswith a new type. The detail says what to do.Validation before pending types are stored
type.<field>.Indexes
service_types.pending(sparse),service_types.created_by, andservices._pending(sparse).Docs
docs/configuration.md:POST /services/typesandPOST /services, linking Rate limits.docs/api.md(pending approvals, limits) and the OpenAPI descriptions ofPOST /services,PUT /services/{id}andPOST /services/typesare updated to match.Closes #246
Verification
All checks below passed locally.
pytestagainst MongoDB 7.0.34, with coveragepytestwith mongomockruff check,ruff formatmypy cloud_registry testsmkdocs build --strictpre-commit run --all-files(includes semgrep and ast-grep)The 228 Helm chart tests did not run locally because Helm isn't installed; CI runs them.
New tests:
openandmoderated, with admins exempt,null,0, changes of service types, deletions, batches and approved types.Declined review findings
moderatedonly once all instances support it.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'sresource_filter()can't run.validate()runs twice per registration (in the server and inregister_metadata()): the duplicate work is one indexed query. It keepsregister_metadata()safe to call on its own.POST /services/types: the pre-check keeps the limit from rejecting types that already exist, and the insert still handles races._count_unused_typesdoesn't use$lookup: CI also runs with mongomock, which doesn't support$lookupwith pipelines, so counting is batched instead.Declined Sourcery findings (answered in their threads):
$ne: truefilter can't use the sparse index. Listings scan all services anyway, and lookups by id use the unique index onid.CI on 90184d4 (before the Sourcery fixes): all checks passed, including
CI passed.Open questions
None.
🤖 Generated with Claude Code