Skip to content

fix!: service info id, precedence and headers - #96

Merged
uniqueg merged 5 commits into
devfrom
fix/service-info
Oct 20, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/service-info

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the service info bugs collected in #75.

  • Required id: ServiceRegister requires id; requests without it get a 400.
  • Precedence: the most recently written service info is served (internal _writtenAt, sorted descending, then _id). On startup, the service info from config.yaml is written only if the config changed since it was last written (sha256 of the config in the internal _configHash on the document with the configured id; carried over when service info with that id is posted). Posted service info, with the same or another id, is therefore kept on restarts unless the config changes. Documents written by earlier versions that equal the config are kept and get the hash recorded.
  • Headers: POST /service-info returns an empty 201 with only a Location header (no Content-Type). Location = {url_prefix}://{host}:{port}/ + api_path + script root + request path.
  • Error media type: error responses declare application/problem+json in the additions spec (follow-up from feat!: upgrade to FOCA 0.14.0 #65/feat!: upgrade to FOCA 0.14.0 #92).
  • README "Service info" section and config comments.

Closes #75

Breaking changes

  • id is required in posted service info.
  • custom.endpoints.service.api_path is now a path prefix in front of the API base path in public URLs (e.g., behind a reverse proxy), empty for none. It previously held the API base path itself (e.g., ga4gh/registry/v1); deployments must remove that value.

Verification

  • pytest: 84 passed (Python 3.10, offline); new tests for missing id, response headers, precedence (other id, same id plus restart, changed config), legacy documents (incl. legacy then POST), hidden internal fields, script root in Location, problem+json errors, declared Location header.
  • ruff check, ruff format --check, mypy cloud_registry tests: clean.
  • gitleaks dir .: no leaks.
  • Two rounds of adversarial and quality review; findings fixed.
  • CI: all checks pass (tests on Python 3.10 and 3.12, static analysis, Docker Compose smoke test, docs).

Open questions

None. Declined review findings:

  • Clock skew between replicas could make an older write win; database-side timestamps need update pipelines, which mongomock does not support. The assumption is documented in the code.
  • Sourcery: writes by old instances during a rolling upgrade, a POST racing with startup, retried POSTs and a sort index (replied in the threads); the unique index on id it asked for exists already.
  • _get_headers reads request.path (documented: must be called in a request context); the expected-headers literal in mock data and YAML anchors in the spec were kept for readability.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 20, 2026 07:18
- POST /service-info requires `id` (400 instead of a 500 `KeyError`)
- The most recently written service info is served, tracked in an
  internal `_writtenAt` field: posted service info is kept on restart
  unless the service info in the config changes. Before, the document
  with the highest `_id` was served, so posted service info with
  another `id` shadowed the config forever.
- `Location` is the public URL of the service info endpoint: the
  configured scheme, host and port, `api_path` as a path prefix, and
  the API path, without duplicate slashes
- The empty 201 response has no `Content-Type`
- Error responses declare `application/problem+json`, the media type
  FOCA returns, in addition to `application/json` (in
  `additions.openapi.yaml`, so the GA4GH specifications stay unchanged)

Closes #75

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Document the precedence rule in the README and config
- Test documents written before write times were tracked
- Write times with fixed microsecond precision
- Errors of POST /service-info are application/problem+json

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Startup compared the config with the stored document, so service info
posted with the configured identifier was replaced on every restart.
Store a hash of the config last written (`_configHash`), carry it over
when service info with that identifier is posted, and write the config
on startup only when its hash changes. Documents without the hash that
equal the config are kept, as before.

Include the WSGI script root in the `Location` header and fix the
`api_path` docstring.

BREAKING CHANGE: `id` is required in posted service info, and
`api_path` is now a prefix in front of the API base path in public
URLs rather than the path of the service info endpoint.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Service info stored before config hashes were added and equal to the
config was kept on startup without a hash, so service info posted with
the configured identifier afterwards was still replaced on the next
restart. Record the hash on such documents.

Also look up the hash before the stored service info, test that
internal fields are hidden, and document the new `api_path` meaning.

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

sourcery-ai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR fixes service-info registration precedence by recording write times and configuration hashes, preserves posted data across restarts unless startup configuration changes, requires service IDs, and corrects response headers and public URL construction for proxy deployments. It also updates the OpenAPI error media types and documentation, with tests covering legacy data, hidden metadata, precedence, validation, and Location behavior.

Sequence diagram for service-info registration and precedence

sequenceDiagram
    participant App
    participant RegisterServiceInfo
    participant Database

    App->>RegisterServiceInfo: set_service_info_from_config()
    RegisterServiceInfo->>RegisterServiceInfo: _get_config_hash(id)
    RegisterServiceInfo->>Database: find_one(id, _configHash)
    alt config hash unchanged
        RegisterServiceInfo-->>App: keep existing service info
    else config changed or hash missing
        RegisterServiceInfo->>RegisterServiceInfo: _get_stored_service_info(id)
        RegisterServiceInfo->>Database: find_one(id)
        RegisterServiceInfo->>Database: replace_one(id, _writtenAt, _configHash)
        RegisterServiceInfo-->>App: service info registered
    end

    App->>RegisterServiceInfo: get_service_info()
    RegisterServiceInfo->>Database: find sorted by _writtenAt desc, _id desc
    Database-->>RegisterServiceInfo: most recently written document
    RegisterServiceInfo-->>App: public service info
Loading

Sequence diagram for posting service info with Location header

sequenceDiagram
    actor Client
    participant API
    participant RegisterServiceInfo
    participant Database

    Client->>API: POST /service-info
    API->>API: RegisterServiceInfo()
    API->>RegisterServiceInfo: set_service_info_from_app_context(data)
    RegisterServiceInfo->>Database: replace_one(id, _writtenAt, preserved _configHash)
    RegisterServiceInfo->>RegisterServiceInfo: _get_headers()
    RegisterServiceInfo-->>API: Location header
    API-->>Client: 201 empty response with Location only
Loading

File-Level Changes

Change Details Files
Track service-info writes and configuration provenance to preserve the newest registration across restarts while applying changed startup configuration.
  • Require and validate the service-info identifier.
  • Store internal write timestamps and configuration hashes, exclude them from API responses, and sort by newest write.
  • Carry the configured document’s hash through posts and support legacy documents without hashes.
cloud_registry/api/additions.openapi.yaml
cloud_registry/ga4gh/registry/service_info.py
tests/ga4gh/registry/test_service_info.py
tests/test_app.py
Correct service-info response headers and public URL construction for reverse-proxy deployments.
  • Return an empty 201 response containing only Location.
  • Build Location from the configured URL prefix, proxy path prefix, script root, and request path.
  • Update service endpoint configuration semantics and coverage.
cloud_registry/ga4gh/registry/server.py
cloud_registry/ga4gh/registry/service_info.py
cloud_registry/service_models/custom_config.py
cloud_registry/config.yaml
tests/mock_data.py
tests/ga4gh/registry/test_service_info.py
tests/test_app.py
Update the API contract and documentation for required identifiers and problem-detail errors.
  • Declare id as required in the service registration schema.
  • Add application/problem+json to error response definitions.
  • Document startup precedence, persistence behavior, and the api_path migration.
cloud_registry/api/additions.openapi.yaml
README.md
cloud_registry/config.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#75 Ensure POST /service-info without an id is rejected with a client error rather than causing a 500. ✅
#75 Define and implement deterministic service-info precedence across posts and restarts, including the effect of configuration changes. ✅
#75 Return an empty 201 response without Content-Type and provide a correctly constructed absolute Location for the service-info endpoint, using the public host and API path without duplicate slashes. ❌ The PR removes Content-Type and constructs the path without duplicate slashes, including the API base path. However, the default external_host remains 0.0.0.0, so the default Location still uses the bind address rather than a usable public host.

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (85af437) to head (17ef1df).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev       #96   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            7         7           
  Lines          204       224   +20     
=========================================
+ Hits           204       224   +20     

☔ 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 20, 2026 05:35

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

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

## Individual Comments

### Comment 1
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="145-148" />
<code_context>
+            config_hash: Hash of the service info config last written to the
+                document, if any.
+        """
+        written_at = datetime.now(timezone.utc).isoformat(timespec="microseconds")
+        replacement = {**data, WRITTEN_AT: written_at}
+        if config_hash is not None:
+            replacement[CONFIG_HASH] = config_hash
         self.collection.replace_one(
             filter={"id": data["id"]},
</code_context>
<issue_to_address>
**Posted info loses its metadata**

When old and new application versions share the database during a rolling deployment and an old instance handles a POST, the old instance replaces the document without `_writtenAt` or `_configHash`. New readers treat it as legacy, and startup can overwrite the posted service info with config, so callers see stale or lost service info.

Make the rolling-deployment write path preserve the metadata, or prevent old instances from writing documents that new instances depend on.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="127" />
<code_context>
-        self._upsert_service_info(data=self._add_timestamps(data=data, stored=stored))
+        self._upsert_service_info(
+            data=self._add_timestamps(data=data, stored=stored),
+            config_hash=self._get_config_hash(id=data["id"]),
+        )
         return self._get_headers()
</code_context>
<issue_to_address>
**Posted info is overwritten by config**

When startup changes or migrates the configured document while a POST for that identifier is in progress, the POST can replace the document with a stale or missing `_configHash` after startup writes the current hash. On the next restart, `set_service_info_from_config` sees a mismatch and replaces the posted service info with config.

Update the document so a concurrent POST cannot restore a stale hash or remove the hash written by startup.

Also at `cloud_registry/ga4gh/registry/service_info.py:97-99`, `cloud_registry/ga4gh/registry/service_info.py:149`.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="150-152" />
<code_context>
+        if config_hash is not None:
+            replacement[CONFIG_HASH] = config_hash
         self.collection.replace_one(
             filter={"id": data["id"]},
-            replacement=data,
+            replacement=replacement,
             upsert=True,
         )

</code_context>
<issue_to_address>
**Concurrent writes duplicate identifiers**

When two app instances write service info with the same identifier before either insert is visible to the other, two instances upsert the same previously absent `id` concurrently; both `replace_one` calls can insert because only MongoDB’s generated `_id` is unique. The collection then contains duplicate service-info documents for one identifier, so later reads and updates can select or replace the wrong copy.

Enforce a unique database index on `id` and handle duplicate-key upsert races by updating the existing document.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="64" />
<code_context>
-                self.collection.find({}, {"_id": False})
-                .sort([("_id", -1)])
+                self.collection.find({}, PROJECTION)
+                .sort([(WRITTEN_AT, -1), ("_id", -1)])
                 .limit(1)
                 .next()
</code_context>
<issue_to_address>
**Reads fail as the collection grows**

When many distinct service-info IDs have accumulated, `get_service_info` sorts by `_writtenAt` without a matching index, so MongoDB scans and sorts an increasingly large collection and can exceed its sort resources. `/service-info` requests then fail.

Create an index that supports the sort used by `get_service_info`.
</issue_to_address>

### Comment 5
<location path="cloud_registry/ga4gh/registry/service_info.py" line_range="145-146" />
<code_context>
+            config_hash: Hash of the service info config last written to the
+                document, if any.
+        """
+        written_at = datetime.now(timezone.utc).isoformat(timespec="microseconds")
+        replacement = {**data, WRITTEN_AT: written_at}
+        if config_hash is not None:
+            replacement[CONFIG_HASH] = config_hash
</code_context>
<issue_to_address>
**Retry resurrects stale info**

When a client retries a POST whose successful response was lost, after another service-info ID has been posted, the retried POST replaces its service-info document and assigns it a fresh `_writtenAt`. If another ID was posted after the original request, the retry makes the older payload appear newest, so GET serves stale info.

Make retries identifiable and deduplicate them, or reject stale writes using a version or conditional update.
</issue_to_address>

### Comment 6
<location path="cloud_registry/ga4gh/registry/server.py" line_range="133" />
<code_context>
     service_info = RegisterServiceInfo()
     headers = service_info.set_service_info_from_app_context(data=_get_request_object())
-    return None, 201, headers
+    response = Response(status=201, headers=headers)
+    # The body is empty, so it has no media type (Flask sets a default one)
+    del response.headers["Content-Type"]
</code_context>
<issue_to_address>
**Location is missing from API spec**

When a consumer relies on the published OpenAPI contract to discover response headers, openAPI consumers see a 201 response with no declared headers, so generated clients and contract-based tooling cannot discover the `Location` header that `postServiceInfo` returns.

Declare the `Location` response header in the `/service-info` 201 response.
</issue_to_address>

### Comment 7
<location path="tests/test_app.py" line_range="275" />
<code_context>
+    spec = client.get(f"{BASE}/openapi.json").json
+    declared = spec["paths"]["/services/{serviceId}"]["get"]["responses"]["404"]
+    name = declared["$ref"].rsplit("/", 1)[-1]
+    assert response.mimetype in spec["components"]["responses"][name]["content"]
+
+
</code_context>
<issue_to_address>
**Error media type regression passes**

When an error response regresses to `application/json`, when `/services/unknown` returns `application/json`, `test_error_media_type` at line 275 still passes because the additions spec declares that media type too, so the test does not catch the required `application/problem+json` response.

Assert that the response mimetype is exactly `application/problem+json`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and if the write-time ordering or config-hash check is wrong, the service can keep serving stale or unintended service info from MongoDB across restarts. That value outlives a revert, but can be replaced by posting corrected info or changing the config.

Blocking findings: cloud_registry/ga4gh/registry/service_info.py:148, cloud_registry/ga4gh/registry/service_info.py:127, cloud_registry/ga4gh/registry/service_info.py:152, cloud_registry/ga4gh/registry/service_info.py:64, cloud_registry/ga4gh/registry/service_info.py:146, and 1 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
Comment thread tests/test_app.py Resolved
Declare the `Location` header of `POST /service-info` responses in the
specification, and assert that error responses are problem details.

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.

Bug: service-info POST, precedence and headers

1 participant