Skip to content

fix: apply revocations when services can't load - #683

Merged
uniqueg merged 7 commits into
devfrom
fix/673-apply-revocations
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
fix/673-apply-revocations

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

RegistryCache reads GET /verifications, then GET /services. If the second read failed, the verifications just read were thrown away and the whole previous list stayed for up to max_stale.

Verifications now apply to the cached backends as soon as they are read, also for threads served while the services are read. A cached backend stays only if its service is still verified with the same URL and API type, of an accepted version; backends dropped this way are logged as a warning.

The rest of the cache's behaviour stays:

  • Such a read is no good read: read_at and max_stale still count from the last good one, and nothing is added.
  • If GET /verifications itself fails or isn't a list, the whole last good list stays.
  • select_services keeps its signature (it now wraps _select, so that verifications are parsed, and malformed items logged, once per read).

docs/plugins.md and the docstring of foca.plugins.backends are updated. Filters or pagination of the registry's /services are not part of this, see the note on the issue.

Closes #673

Verification

  • Tests written first: 16 of the new tests failed on the old code, then passed.
  • Locally: ruff check, ruff format --check, mypy, ast-grep scan, ast-grep test --skip-snapshot-tests, semgrep scan --config .semgrep (mise's 1.181.0, not the pinned version), mkdocs build --strict.
  • Full suite with MongoDB 7.0, Python 3.13: 3644 passed, 1 skipped, 100% coverage, before the last commit, which only changes docs and tests; after it, tests/plugins/test_plugin_backends.py: 60 passed, 100% of foca/plugins/backends, plus ruff, mypy and the docs build.
  • Against a real Cloud Registry (dev at 19a6c82, containers, real verification and DELETE of a verification, GET /services failing on FOCA's side): both backends stay while nothing is revoked, one after the revocation. Saved as check_revocation.py next to the check of fix: read serviceId in backend discovery #665 in the work folder (projects/foca-665-cr-check/; CHECK=check_revocation.py run.sh ...).
  • Not run locally: integration tests (tests/integration_*), chart tests; left to CI.
  • CI: all checks passed on 0291662 (unit tests of all Python and MongoDB versions, lowest dependencies, integration, chart, CodeQL). The push after it changes one test and merges dev.

Declined review findings

  • Revoked backends can be logged twice when both reads succeed and the URL differs (no longer verified, then Registry service not used): harmless, and they say different things.
  • keeping N backends counts the reduced list after a drop: accurate for what is kept.
  • Commit trailer "should" name another model: the reviewer's assumption; it matches the session's attribution.
  • Services with the same URL, the first one revoked, the others not, during a failure of GET /services: the backend is dropped until the next good read. Kept on purpose, as it fails closed, and a verification says nothing about the other service's environment; documented and tested.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Apply registry verifications immediately to cached backends so revoked services are not used when service discovery is unavailable.

Bug Fixes:

  • Apply newly read service verifications to cached backends even when the registry's services request fails, ensuring revoked or changed backends are no longer served.

Enhancements:

  • Preserve cache freshness and stale-read semantics while applying revocations during registry refreshes, and keep verification parsing behavior consistent across read paths.

Documentation:

  • Document how verifications affect cached backends when service discovery is unavailable, including URL, API type, version, and stale-cache behavior.

Tests:

  • Add coverage for revocations during failed and in-progress service reads, changed or malformed verifications, duplicate service URLs, re-verification, and real client failures.

uniqueg and others added 2 commits November 4, 2026 08:16
RegistryCache read GET /verifications, then GET /services, and threw
away what it had read if the second failed: the previous list stayed
for up to max_stale, including backends no longer verified.

Apply the verifications as soon as they are read, to the cached
backends: only those verified with the same URL and API type, of an
accepted version, stay. This also covers threads served while the
services are read. It isn't a good read: its time and max_stale still
count from the last one, and nothing is added. If the verifications
themselves can't be read, nothing changes.

Closes #673

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorter sentences, and what happens to services with the same URL.
Test that case, and that a revocation keeps the time of the read.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The cache now applies valid registry verifications immediately to cached backends, dropping and warning on revocations even when the subsequent services request fails, while preserving freshness semantics and the existing selection API; documentation and comprehensive regression tests cover the new behavior.

Sequence diagram for applying registry revocations during refresh

sequenceDiagram
    participant Cache as RegistryCache
    participant Registry
    participant Verifications as VerificationParser
    participant Services as ServiceSelector

    Cache->>Registry: fetch_json(/verifications)
    Registry-->>Cache: verification response
    Cache->>Verifications: _verifications(response)
    Verifications-->>Cache: verified services
    Cache->>Cache: _drop_unverified(verified)
    alt services read succeeds
        Cache->>Registry: fetch_json(/services)
        Registry-->>Cache: services response
        Cache->>Services: _select(services, verified, entry, api, previous)
        Services-->>Cache: selected backends
        Cache->>Cache: store good read
    else services read fails
        Cache->>Cache: keep only still-verified cached backends
        Cache-->>Cache: retain last good read timestamp
    end
Loading

Flow diagram for cached backend verification decisions

flowchart TD
    A[Read verifications] --> B{Verification response is a list?}
    B -- No --> C[Keep entire last good backend list]
    B -- Yes --> D[Apply verification to cached backends]
    D --> E{Same URL, API type, and accepted version?}
    E -- Yes --> F[Keep cached backend]
    E -- No --> G[Drop backend and log warning]
    D --> H{Services read succeeds?}
    H -- Yes --> I[Select and add services]
    H -- No --> J[Keep reduced cache]
    J --> K[Preserve last good read freshness and stale limits]
Loading

File-Level Changes

Change Details Files
Apply successfully read verifications to already cached backends before attempting to load services.
  • Add normalized URL/API/version matching for cached backend verification.
  • Drop revoked or changed backends immediately and warn about removals.
  • Preserve last-good timestamps, stale limits, and retry behavior when services cannot be read.
  • Ensure threads observe revocations while a services request is in progress.
foca/plugins/backends/registry.py
Refactor service selection so verification parsing is centralized while preserving the public selection interface.
  • Keep select_services unchanged externally while delegating parsed verification data to an internal selector.
  • Reuse normalized base-URL handling for both selection and cached-backend validation.
  • Continue skipping malformed verification items with one warning per read.
foca/plugins/backends/registry.py
Expand regression coverage for revocation and cache behavior across failure and concurrency scenarios.
  • Test service-read failures, malformed or changed verifications, duplicate URLs, re-verification, and reads observed by concurrent callers.
  • Add an HTTP-client failure test covering revocation when the services endpoint returns an error.
  • Verify freshness, max-stale, warning, and retry semantics remain unchanged.
tests/plugins/test_plugin_backends.py
Document verification-driven removal of cached backends when registry services are unavailable.
  • Describe URL, API type, and accepted-version checks for retained backends.
  • Document fail-closed behavior, duplicate-URL precedence, stale-read semantics, and invalid verification handling.
docs/plugins.md
foca/plugins/backends/__init__.py

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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (930ce28) to head (e58376d).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #683   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           60        60           
  Lines         7790      7807   +17     
=========================================
+ Hits          7790      7807   +17     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 November 4, 2026 07:30
CodeQL takes a bare URL in a containment check for URL sanitization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
sourcery-ai[bot]
sourcery-ai Bot previously approved these changes Nov 4, 2026

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

Sourcery assessment

Approved.

@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 1 issue

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

## Individual Comments

### Comment 1
<location path="tests/plugins/test_plugin_backends.py" line_range="710" />
<code_context>
+    cache = two_backends
+
+    def fetch(url: str, timeout: float, **options: Any) -> Any:
+        return document
+
+    monkeypatch.setattr(discovery, "fetch_json", fetch)
</code_context>
<issue_to_address>
**Malformed verifications evade the test**

When the implementation accepts an invalid verification response and then rejects the same invalid document as the services response, `test_invalid_verifications_keep_backends` uses the same `document` for every URL, so if invalid verifications are mistakenly accepted, the `/services` read also returns that invalid document and independently fails; the cache still stays unchanged. Its `len(cache.urls()) == 2` assertion also allows the wrong two URLs, so the test passes despite broken handling of invalid verifications.

Return a valid services list for `/services` while returning the parameterized document only for `/verifications`, and assert the exact cached URLs.

Also at `tests/plugins/test_plugin_backends.py:714`.
</issue_to_address>

Linked issues

#673 fix: apply revocations when services can't load · 1 of 1 met

# Requirement Status Notes
1 Apply successfully read verifications to cached backends, removing those no longer verified even when /services cannot be read. ✅ Met The cache drops backends that fail the URL, API type, or accepted-version check immediately after parsing verifications, before fetching /services.

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and if the URL or API comparison mistakenly rejects a still-valid verification, the cached backend is removed and requests may lose that backend while the services endpoint is unavailable. Reverting the code does not restore the in-memory cache entry; it is repairable by a successful services read, and otherwise bounded by the stale-cache period.

Blocking findings: tests/plugins/test_plugin_backends.py:710


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

Comment thread tests/plugins/test_plugin_backends.py Resolved
uniqueg and others added 2 commits November 4, 2026 08:40
Answer only GET /verifications with the invalid document, and compare
the exact URLs, so that accepting it can't go unnoticed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai
sourcery-ai Bot dismissed their stale review November 4, 2026 07:42

Sourcery withdrew this approval because the latest commits introduced blocking findings.

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

Sourcery assessment

Approved.

@uniqueg
uniqueg merged commit 1b94723 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/673-apply-revocations branch November 4, 2026 08:08
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: apply revocations when services can't load

2 participants