Skip to content

feat(plugins): add typed backend lists - #501

Merged
uniqueg merged 88 commits into
devfrom
feat/backend-lists
Oct 25, 2026
Merged

uniqueg merged 88 commits into
devfrom
feat/backend-lists

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds typed backend lists for gateways: one ordered list, used by the default router and shared by all gateways. It replaces proTES's two places for backends, whose set() merge loses the order. This is the fifth PR of the v0.18.0 plugin stack (#485).

  • Entries (foca.plugins.backends):
    • ga4gh-tes: URL, url_schemes, id, auth, labels, location.
    • ga4gh-service-registry: URL, refresh_interval, timeout, version and environment filters, auth for discovered backends, separate private-address switches for the registry and for discovered backends, and max_stale.
    • IDs are unique, and URLs are normalized and refused if they contain user info.
  • Discovery: only verified services are used. Services are filtered by type, version and environment, and fetched with the guarded HTTP client (feat(utils): add a guarded HTTP client #490).
  • Registry cache:
    • One cache per entry and process.
    • A rate-limited retry, and a fork-safe lock.
    • The last good list is used for at most max_stale seconds. Without a usable list, threads wait for the read in progress.
  • expand():
    • Entries become candidates in order.
    • The gateway's own public URL, and everything below it, is left out (same host, effective port and path, any scheme; default ports count as the same).
    • Candidates are de-duplicated by ID at the first position, and configured settings win over discovered ones.
    • Discovered backends whose ID a configured entry already uses for another URL are skipped.
  • Lookups: entry_for() gives the typed entry behind a candidate, find(url) looks a backend up, with a rate-limited refresh, and expand(snapshots=...) records the registry reads used, for provenance.
  • Apps: GatewayApp(backends=...) names the app's backend list config, create_app() validates it, and get_backend_list() builds the list. Registry entries need server.public_url.
  • Docs: backend list configuration, with proTES's mapping from its old keys.

Closes #493

Verification

Run locally on 7ff884a (with dev merged):

  • ruff check and ruff format --check: pass.
  • mypy: pass.
  • pytest without MongoDB: pass, with 100% coverage of foca/plugins and foca/utils/http.py. The tests use no network access (a local registry and mocked HTTP).
  • mkdocs build --strict: pass.
  • pre-commit: pass.

The MongoDB tests and semgrep did not run locally (CI runs them). CI on 61c2444: 27 checks pass, and 2 are skipped as intended. The first run failed on an exact comparison of two monotonic floats in test_cache (29.999...), which 61c2444 compares approximately.

Review: two rounds of adversarial and quality review.

  • Round 1 (21cdcae, 005b44a):
    • malformed /verifications items failed the read and kept revoked backends forever;
    • stale lists weren't bounded (max_stale added);
    • registries at private addresses couldn't be read in tests;
    • server.public_url wasn't required;
    • the own-URL check depended on the scheme;
    • the module was too big (now a package, with the same imports).
  • Round 2:
    • threads got an empty or stale list while the first read, or the first read after an idle gap, was running (32e22bc);
    • discovered backends could take a configured entry's ID (f9c0a4f).

All are fixed.

Sourcery: 7 findings, all fixed in 4e81662:

  • the verified API version must equal the offered one;
  • read times count from the end of the I/O;
  • threads wait if the cache expires during a read;
  • the own-URL check compares effective ports;
  • expand(snapshots=...) gives the reads that candidates come from;
  • registry timeouts are finite;
  • backend entries must be ordered.

CI on 4e81662: 28 checks pass, and 2 are skipped as intended.

Declined review findings

  • Commit hygiene (merge commits from the stack): declined, because the PR is squash-merged.

🤖 Generated with Claude Code

uniqueg and others added 30 commits October 25, 2026 00:24
Add `foca.plugins`, a framework-neutral engine for gateway plugins:

- plain request model (`InboundRequest`, `Backend`, `OutboundRequest`,
  `BackendResponse`, `Principal`, case-insensitive `Headers`) and an
  explicit `Context` per hook call; no Flask, Werkzeug or Connexion
  types, so plugins run unchanged after the move to Connexion 3
- `Plugin` base with `on_request`, `on_route`, `on_forward` and
  `on_response` hooks, `NotApplicable`, `Rejected` and `PluginError`
- allowlisted loading of entry points (group `foca.plugins`) with
  distribution and version pins, `RECORD` digests, `enabled: false`
  kill switch and a startup error with a migration hint for legacy
  `middlewares` keys
- steps with ordered alternatives, copy-and-commit per alternative,
  failure semantics, timeouts via a bounded thread pool, forwarding
  attempts with "not accepted" / "outcome unknown" outcomes, a total
  `forward_timeout`, `Via` headers, loop detection (508) and no routing
  to the gateway's own public URL
- `foca.plugins.adapter`, the only module using Connexion 2 / Flask
- config section `plugins`, docs pages, and an ast-grep rule that keeps
  framework imports out of `foca/plugins` except the adapter

Co-Authored-By: Claude Opus 5.5 <[email protected]>
What proTES needs to adopt the engine:

- `Foca(gateway=GatewayApp(api, validate, sanitize,
  validate_outbound))` declares a gateway app; `create_app()` loads its
  plugins once to fail fast, and `foca.plugins.runtime.get_host()`
  gives controllers and Celery tasks the host of their process,
  created on first use after forks (no Flask app context needed)
- legacy `middlewares` keys are refused before the app's strict
  `custom` model is validated
- errors of the app's `sanitize` (e.g. 413) stop the request
  unchanged; `validate` failures stay invalid output
- `validate_outbound` per attempt (reason `invalid_outbound`)
- `NotAccepted`/`OutcomeUnknown` exceptions with reason codes for the
  app's client, and `Attempt.report()`
- adapter: `request_id()` from a safe `X-Request-ID` or a new one;
  `Principal.groups` are the mapped roles of access control
- string short form of steps (`- <plugin id>`)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let clients choose the pipeline and the backends of a request in two
reserved tags, under the configurable prefix `plugins.tags.prefix`
(default `gateway.`):

- `gateway.pipeline`: a preset name (`plugins.presets`) or a pipeline
  as JSON, validated and authorized before any plugin runs (limits,
  roles, `client_selectable`, uniform "plugin not available" errors)
  and framed by `client_pipelines.prepend`/`append` (`if_missing_phase`
  for a default route step)
- `gateway.backends`: `{"type": "order" | "allow" | "forbid",
  "backends": [...]}`, applied to the routed candidates; items that are
  no candidates are discarded and recorded
- any other client tag under the prefix is refused with 400

Presets and frames are resolved on startup; presets that need a
disabled plugin are unavailable. Gateway errors move to
`foca.plugins.errors`. `foca.utils.urls` imports Flask only in
`get_public_url()`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`run.provenance()` describes a pipeline run as plain JSON data for the
app to store with its resource:

- prospective: pipeline source, preset, the client's tag by reference,
  the resolved pipeline and its `sha256:` hash of the RFC 8785
  canonical JSON (own implementation, tested with the RFC's vectors)
- retrospective: hook calls with build keys, outcomes, timings,
  sanitized errors, annotations and changes as hashes and JSON Pointers
  without values (`plugins.provenance.detail: paths`); route candidates,
  the client's backend selection, attempts and the final reason
- engine: FOCA, plugin API and app versions (`GatewayApp(name,
  version)`)

`ProvenanceStore` takes collections of the app: plugin builds (with an
optional image digest from `FOCA_IMAGE_DIGEST`) and default or preset
pipelines are stored once by hash; client pipelines stay inline.
Failed runs are stored only with `plugins.provenance.record_failed`
(default off), with documented TTL index specs.

Hook records keep changes instead of the data before and after. The
engine's usage example now catches `OutcomeUnknown` before its base
class.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.utils.http` sends requests to URLs from users and registries
without becoming an SSRF vector, on requests/urllib3 only:

- `GuardedClient` checks the peer address of each new connection after
  connecting and before sending (so DNS rebinding cannot reach internal
  hosts), never follows redirects, ignores proxies and `.netrc` of the
  environment, allows `https` only and always verifies TLS, bounds
  requests by a deadline (connect timeout capped at 10 s) and response
  bodies by size, and returns a plain `HttpResponse`
- errors carry reason codes and tell requests that certainly did not
  reach the server (`RequestNotSent`) from those that may have
  (`RequestMaybeSent`), for gateway outcomes
- `is_public_address()`, `check_public_host()` and `fetch_json()`, moved
  from proTES

Plugins get a client bound to their deadline as `ctx.http`, configured
by `plugins.defaults.http`. The framework-import rule covers the client.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.backends` gives gateway apps one ordered list of typed
backend entries, under a key of their own (proTES:
`custom.tes.backends`), replacing configured lists plus one registry:

- `ga4gh-tes` entries (`url`, `url_schemes` default `["https"]`, `id`,
  `auth`, `basic` env var names, `labels`, `location`) and
  `ga4gh-service-registry` entries (`https` only, refresh interval,
  timeout, version prefixes, environments, `auth` and labels for the
  discovered backends, `allow_private_addresses`); unique ids,
  normalized URLs without user info
- registry discovery moved from proTES and made generic by API type:
  verified services only, type/version/environment filters, `https`,
  public hosts, no redirects, no token; cache per entry and process
  with last-good fallback, retries after 30 s at most, fork-safe locks
- `BackendList.expand()`: candidates in entry order, de-duplicated by
  URL at the first position with configured settings winning, the
  gateway's own public URL and everything below it left out
- `entry_for()`, `find(url, refresh=True)` (rate-limited registry
  re-read, for other processes), `snapshots()` and `describe()`

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes:

- outbound `Via` headers are the inbound request's with this gateway's
  entry appended (RFC 9110, section 7.6.3), whatever plugins or the
  app's builder set, so that loops through several gateways are
  detected (A -> B -> A)
- each call gets its own deep copy of the step's parameters, and the
  caller's claims as a read-only deep copy, so that a hook cannot
  change them for later calls, requests or provenance
- hooks raising `SystemExit` and other `BaseException`s fail like
  others; `KeyboardInterrupt` and `GeneratorExit` propagate

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.security.access_control.get_current_claims()` returns a copy of
the claims of the current request's token, next to
`get_current_subject()` and `get_current_groups()`; the plugin adapter
uses it instead of a private helper.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps that configure `plugins` without `Foca(gateway=...)` get a startup
warning, as the section is validated but not used. The docs say that
there is no runtime API for operators, summarize the steps for gateway
app authors, and note that plugins are instantiated once more per
process after the startup check.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.engine` keeps the host, runs and attempts; the rest moves
along its seams, with the public imports from `foca.plugins` and
`foca.plugins.engine` unchanged:

- `errors`: gateway errors with problem details
- `outcomes`: `NotAccepted`, `OutcomeUnknown`, `sanitize_error()` and
  the engine's internal errors
- `records`: resolved pipelines, hook call and attempt records
- `executor`: the bounded thread pool of hook calls
- `checks`: outbound requests, `Via` names and hook output checks

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of the plugin engine:

- Claims of the caller are a FrozenMapping, which plugins can keep in
  their state: unlike MappingProxyType, it can be deep-copied and
  pickled. The engine copies state and candidates inside the guarded
  block, so a failing copy fails that alternative only, not the request.
- The engine sets Via before the app's outbound check; inbound Via
  headers longer than 1024 characters are refused (400, InvalidVia).
  Docs say that the inbound Via is passed through verbatim.
- The default gateway_id is the host and port of the public URL,
  without user information, and only if it matches the gateway_id
  pattern.
- setup() of plugins may run more than once per process (docstring and
  author docs); tests import internals from their new modules.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	foca/plugins/__init__.py
#	foca/plugins/engine.py
# Conflicts:
#	foca/plugins/engine.py
#	tests/plugins/test_plugin_engine.py
CodeQL flagged reflected XSS in a view that only exists for its URL
rule. Return a constant instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Principal.token is set only if a token was validated (claims).
- Repeated header fields of inbound requests are combined (e.g., Via).
- Problem responses keep the custom title of a plugin's rejection;
  problem_response() takes a request-specific title.
- Annotations reject NaN and infinite numbers.
- Plugins loaded before a load or pipeline error are closed.
- Gateway names bracket IPv6 addresses (pattern GATEWAY_ID_PATTERN),
  and the outbound Via header, with this gateway's entry, stays within
  1024 characters.
- One gateway app per process: configure() refuses other settings
  while a host is in use; reset() closes it; the host is closed at
  exit.
- Docs: app callbacks run outside plugin deadlines and must be fast;
  rejections in the response phase count as errors.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	foca/plugins/config.py
#	foca/plugins/engine.py
Guard against names in foca.plugins.__all__ that do not resolve (e.g.,
a missing import), as noticed by proTES.

Refs #486

Co-Authored-By: Claude Opus 5.5 <[email protected]>
uniqueg and others added 22 commits October 25, 2026 05:16
Address the second review round of provenance:

- Response hooks must keep the client's Headers (as forward hooks do),
  and describing changes never raises (error: internal), so that a
  hook cannot fail a request that a backend accepted.
- Changed paths are collected up to the cap only, pointers longer
  than 512 characters are recorded as their parent, and the paths of
  a run take at most 64 KiB (then truncated: true), so that records
  stay far below the BSON limit.
- Annotations must be I-JSON (exact integers, valid Unicode).
- save() also catches errors while building the record, with a
  minimal fallback record.
- Client address headers (Forwarded, X-Forwarded-For, X-Real-IP) are
  left out of hashes; docs say to put low-entropy headers in
  secret_headers and to declare secret params as SecretStr, which is
  redacted (tested).
- Tests: TTL index on mongomock from FAILURE_INDEXES, app_info of
  create_host().

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the Sourcery review of PR #499:

- Records keep only the type of errors of plugins and other code, as
  their messages may hold secrets; logs get the message
  (describe_error). FOCA's gateway errors, rejections and its own
  timeout and invalid-output texts keep their message.
- Set-Cookie of responses is left out of hashes; hashes of changes
  are keyed (HMAC-SHA256, random key per process), content hashes of
  pipelines and builds stay plain RFC 8785 SHA-256.
- Backend URLs in records lose user info, query and fragment.
- A budget that runs out during the last attempt gives
  forward_timeout, not no_backend.
- Pipelines that are no I-JSON are recorded without resolved.
- Records are cut to 1 MiB of JSON (changed paths, then annotations,
  then the resolved pipeline; truncated: true).
- If storing builds fails, the record keeps their documents inline.
- save_failure() is idempotent: _id is the request ID, else the
  run's random run_id, written with replace_one(upsert=True).
- The pointer length cap applies to array items too.
- Docs: map keys in changed paths, MongoDB client timeouts.

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	tests/plugins/test_plugin_engine.py
Compare the URL fields of the record exactly instead of testing for
URL substrings in its JSON text (CodeQL: incomplete URL substring
sanitization).

Refs #488

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dev has the squash of #499 (provenance), whose tree equals
feat/plugin-provenance, already merged here; conflicts in
foca/plugins/context.py and tests/plugins/test_plugin_engine.py are
resolved to this branch's tree.
One GuardedClient shared its end, timer and sockets across requests,
so concurrent requests (e.g., of a plugin that fans out) overwrote
each other's deadlines: one request finishing cancelled another's
timer, and its own timer then shut the other's sockets down.

Each request now gets its own guard, found by its connections per
thread (urllib3 connects, sends and reads in the request's thread);
pooled connections that a request reuses are tracked in its guard,
and the guard finishes before the connection goes back to the pool,
so a late timer cannot stop a socket that another request uses. No
lock serializes requests. Tests: two concurrent requests with
overlapping deadlines, a deadline on a reused connection.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A json body that is no JSON (NaN, a set, other objects) gave an
InvalidJSONError classified as connection_lost, or a raw TypeError,
although nothing was sent; a header with a line break gave
invalid_url. Both now raise InvalidRequest (a RequestNotSent, reason
invalid_request or invalid_header) before sending, so all errors stay
HttpErrors. The dead InvalidHeader branch of _classify is gone.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connections checked all resolved addresses but connected only to the
first, losing urllib3's fallback across A/AAAA records. They now try
the checked addresses in order within one connect budget; the peer of
the one that connects is checked as before.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
While one thread read a registry, the others got the cached backends,
which are none before the first read and after an idle gap longer
than max_stale, so requests found no discovered backends although a
read was about to deliver them. Threads now wait for the read unless
a good read within max_stale is cached; with one, they keep getting
it while the refresh runs. Tests use two real threads.

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A discovered backend's id is its URL, which can equal a configured
entry's custom id for another URL; candidates then had two backends
with one id, and the client's backend selection could pick the wrong
one. expand() now skips such discovered backends (logged at debug
level).

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Python 3.14 parses unbalanced deep arrays without RecursionError, so
the ValueError branch of HttpResponse.json was not covered in CI. The
test now also forces the RecursionError.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Error messages name URLs without user info, query and fragment, with
  control characters escaped (_redact).
- Guards track connections, not sockets: a connection belongs to the
  request that uses it, so a late timer of an earlier request no
  longer stops it, and one that such a timer stopped is closed before
  reuse. Timers shut down the current socket of a connection, so TLS
  sockets that wrap the new one are stopped too.
- Sessions keep no cookies, and are created once under a lock.
- Docs: cookies, redacted messages, and why network-specific NAT64
  prefixes are not checked.

Refs #490

Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeQL flags host substring checks in tests; compare the whole
message instead (with an escape character, since urlsplit drops
line breaks itself).

Refs #490

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

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds typed, ordered backend lists for gateway apps, integrating validated configured entries with verified service-registry discovery while providing secure filtering, bounded process-local caching, concurrency and fork safety, runtime integration, documentation, and extensive tests.

Sequence diagram for backend list expansion and registry discovery

sequenceDiagram
    participant Gateway as Gateway request
    participant BackendList
    participant RegistryCache
    participant Registry
    participant HTTP as Guarded HTTP client

    Gateway->>BackendList: expand()
    BackendList->>RegistryCache: urls(refresh)
    alt Cache usable and not due
        RegistryCache-->>BackendList: cached URLs in registry order
    else Registry read required
        RegistryCache->>Registry: GET /verifications
        Registry-->>RegistryCache: verified services
        RegistryCache->>Registry: GET /services
        Registry-->>RegistryCache: service records
        RegistryCache->>HTTP: fetch_json()
        HTTP-->>RegistryCache: guarded responses
        RegistryCache-->>BackendList: filtered discovered URLs
    end
    BackendList-->>Gateway: ordered, de-duplicated candidates
Loading

Flow diagram for backend candidate filtering

flowchart LR
    E["Typed backend entries"] --> X["expand() in entry order"]
    X --> V["Configured entries and verified registry services"]
    V --> O["Exclude gateway public URL and descendants"]
    O --> D["De-duplicate URLs; configured settings win"]
    D --> I["Skip discovered IDs taken by another configured URL"]
    I --> C["Backend candidates"]
Loading

File-Level Changes

Change Details Files
Introduces typed, validated backend-list configuration models with normalized URLs, authentication settings, metadata, registry options, and unique entry identifiers.
  • Adds service and service-registry entry models with discriminated validation.
  • Normalizes and validates URLs, schemes, credentials, registry freshness limits, and duplicate IDs.
  • Exposes backend configuration types and registry APIs through the plugin package.
foca/plugins/backends/__init__.py
foca/plugins/backends/config.py
Implements ordered candidate expansion and lookup across configured and registry-discovered backends.
  • Preserves entry and discovery order while de-duplicating URLs and preferring configured settings.
  • Excludes the gateway's own public URL subtree and prevents discovered IDs from conflicting with configured entries.
  • Adds candidate-to-entry mapping, URL lookup, snapshots, and credential-free descriptions.
foca/plugins/backends/lists.py
Adds verified service-registry discovery with resilient, process-shared caching and concurrency controls.
  • Filters services by verification, API type, version, environment, URL consistency, and address policy.
  • Uses guarded HTTP reads without registry credentials or redirects, with retry limiting and bounded stale data.
  • Coordinates concurrent reads, supports fork-safe locks, preserves unresolved hosts for one read, and provides cache reset/access helpers.
foca/plugins/backends/registry.py
Integrates backend lists into gateway application configuration and startup validation.
  • Adds the GatewayApp backend configuration callback and runtime get_backend_list() construction.
  • Validates backend lists during create_app() and requires server.public_url when registries are configured.
foca/plugins/runtime.py
foca/foca.py
Documents backend-list configuration, proTES migration semantics, runtime behavior, and public APIs.
  • Describes typed entry schemas, ordering, discovery trust rules, caching, lookups, and metadata APIs.
  • Adds backend-list and runtime symbols to the generated reference documentation.
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md
Adds comprehensive tests for configuration, expansion, discovery filtering, cache behavior, concurrency, fork safety, and runtime integration.
  • Covers malformed and revoked verification data, private-address controls, stale limits, retries, and local guarded HTTP reads.
  • Verifies ordered de-duplication, own-gateway exclusion, ID conflicts, lookup behavior, and application validation.
tests/plugins/test_plugin_backends.py
tests/plugins/test_plugin_runtime.py

Assessment against linked issues

Issue Objective Addressed Explanation
#493 Provide validated, ordered typed backend-list configuration for gateways, integrate it with GatewayApp and runtime, and document app configuration. ✅
#493 Implement shared service-registry discovery with verification and API filters, guarded HTTP and address trust rules, and per-entry caching with bounded stale data and refresh behavior. ✅
#493 Expand entries in order while excluding the gateway’s own URL and de-duplicating candidates by Backend.id, preserving configured-entry precedence and supporting entry_for and URL lookup. ❌ The expansion code de-duplicates by backend.url (seen: set[str] and if backend.url in seen), not by Backend.id as required. Distinct candidates sharing an ID but having different URLs can therefore both be returned, while candidates sharing a URL but having distinct IDs are collapsed.

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (fb4029d) to head (4e81662).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #501    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           46        50     +4     
  Lines         5430      5778   +348     
==========================================
+ Hits          5430      5778   +348     
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.

The retry interval is the difference of two monotonic floats, which
is not exact (29.999... in CI).

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 25, 2026 20:36

@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="foca/plugins/backends/registry.py" line_range="183" />
<code_context>
+        if (
+            not isinstance(url, str)
+            or url != verified_url
+            or not _is_api(verified_type, api)
+        ):
+            selection.rejected.append(
</code_context>
<issue_to_address>
**Unverified API versions reach routing**

When the service record lists an accepted API version but its matching verification record lists a different version, `select_services()` accepts the service version against `entry.versions`, but `_is_api()` checks the verification only by group and artifact. The service becomes a candidate even though its API version was not verified.

Compare the verified type’s version with the service type’s version before admitting the service.

Also at `foca/plugins/backends/registry.py:184`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/backends/registry.py" line_range="333" />
<code_context>
+            Whether the next read is due, or a read is requested and the last
+            one is at least `MIN_REFRESH_INTERVAL` seconds ago.
+        """
+        now = time.monotonic()
+        return now >= self._next_read or (
+            refresh and now - self._last_read >= MIN_REFRESH_INTERVAL
</code_context>
<issue_to_address>
**Slow reads expire immediately**

When a registry read takes at least the configured refresh interval, max-stale period, or retry interval, `_refresh()` uses a monotonic time captured before network I/O for `_next_read` and `_read_good`. A slow successful read is immediately due or stale, and a slow failure consumes its retry delay before it is returned.

Set the read-success and next-read timestamps using a monotonic time sampled after the registry I/O completes.

Also at `foca/plugins/backends/registry.py:367-381`.
</issue_to_address>

### Comment 3
<location path="foca/plugins/backends/registry.py" line_range="283-284" />
<code_context>
+        if usable and not self._due(refresh):
+            return self._current()
+        # without usable backends, wait for a read that runs meanwhile
+        if not self._lock.acquire(blocking=not usable):
+            return self._current()
+        try:
+            if self._due(refresh):
</code_context>
<issue_to_address>
**Expired cache returns no backends**

When a cached list is still usable when a caller checks it, but expires while another thread holds the lock refreshing the registry, `urls()` decides to acquire the lock non-blockingly from its initial `usable` value. If another thread is refreshing and the cached list crosses `max_stale` before `_current()` runs, this branch returns an empty list instead of waiting for the in-progress read, so a request temporarily sees no candidates despite a refresh that can provide them.

After failing the non-blocking acquisition, recheck whether the cache is still usable and wait for the lock if it has expired.
</issue_to_address>

### Comment 4
<location path="foca/plugins/backends/lists.py" line_range="30-31" />
<code_context>
+        Host with port (if any), and path without trailing slash.
+    """
+    rest = url.split("://", 1)[-1]
+    host, _, path = rest.partition("/")
+    return host, f"/{path}".rstrip("/")
+
+
</code_context>
<issue_to_address>
**Gateway URL matching loses port identity**

When the gateway and backend use different schemes with default ports, or the same port is implicit in one URL and explicit in the other, `_location()` drops the scheme after scheme-specific normalization removes default ports, then compares authority text. It can treat ports 443 and 80 as the same endpoint or fail to match two URLs that use port 443, causing a valid backend to be excluded or a gateway URL to pass `_is_own()`.

Compare the parsed host, effective numeric port, and path when determining whether two URLs identify the same location.

Also at `foca/plugins/backends/lists.py:92-94`.
</issue_to_address>

### Comment 5
<location path="foca/plugins/backends/registry.py" line_range="379-382" />
<code_context>
+                entry.url,
+                ", ".join(selection.urls.values()) or "none",
+            )
+        self._urls = selection.urls
+        self._read = True
+        self._read_good = now
+        self.read_at = (
+            datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z")
+        )
</code_context>
<issue_to_address>
**Provenance uses a different registry snapshot**

When a registry refresh overlaps candidate expansion and snapshot collection, or completes between `expand()` and `snapshots()`, the candidate URLs and `read_at` can come from different cache reads: `_refresh()` publishes `_urls` before `read_at`, and `snapshots()` can read a later timestamp after `expand()` returns. Callers record inaccurate provenance for the candidates they routed.

Capture the candidate URLs and their `read_at` together as one snapshot and use that same snapshot for expansion and provenance.

Also at `foca/plugins/backends/lists.py:159`.
</issue_to_address>

### Comment 6
<location path="foca/plugins/backends/config.py" line_range="219" />
<code_context>
+    id: str = Field(default="", min_length=1)
+    refresh_interval: PositiveInt = 300
+    max_stale: PositiveInt = 3600
+    timeout: PositiveFloat = 10
+    versions: list[Annotated[str, Field(min_length=1)]] = Field(
+        default=["1.0", "1.1"], min_length=1
</code_context>
<issue_to_address>
**Infinite timeouts break discovery**

When the configuration supplies an infinite timeout, `PositiveFloat` accepts positive infinity, so an infinite registry timeout passes configuration validation. `fetch_json` then reaches the guarded client's timer and socket timeout with infinity, causing runtime errors and leaving the registry with no discovered candidates.

Reject non-finite timeout values during `RegistryEntry` validation.
</issue_to_address>

### Comment 7
<location path="foca/plugins/runtime.py" line_range="41-42" />
<code_context>
 from foca.plugins.engine import PluginHost
 from foca.plugins.model import OutboundRequest

+BackendEntries = (
+    Iterable[ServiceEntry | RegistryEntry | Mapping[str, Any]] | BackendListConfig
+)
+"""Entries of a backend list, as models or mappings."""
</code_context>
<issue_to_address>
**Unordered inputs scramble routing**

When a caller supplies a set or another unordered iterable as the backend entries, `BackendEntries` and `BackendList.__init__` accept any `Iterable`, including sets. When a caller supplies an unordered collection, its iteration order determines candidate order, so routing can choose different backends across runs despite the API promising an ordered list.

Accept an ordered type such as `Sequence` for backend entries, or explicitly reject unordered collections.

Also at `foca/plugins/backends/lists.py:48-49`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and a bad discovery or backend-selection decision could send gateway requests and configured credentials to an unintended service; a credential disclosed this way cannot be recovered by reverting the change. The exposure is bounded to services and traffic handled by the configured gateway, rather than inherently unbounded.

Blocking findings: foca/plugins/backends/registry.py:183, foca/plugins/backends/registry.py:333, foca/plugins/backends/registry.py:284, foca/plugins/backends/lists.py:31, foca/plugins/backends/registry.py:382, and 2 more


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

Comment thread foca/plugins/backends/registry.py Resolved
Comment thread foca/plugins/backends/registry.py Resolved
Comment thread foca/plugins/backends/registry.py Resolved
Comment thread foca/plugins/backends/lists.py Resolved
Comment thread foca/plugins/backends/registry.py Resolved
Comment thread foca/plugins/backends/config.py Resolved
Comment thread foca/plugins/runtime.py Resolved
- Services whose verified API version differs from the offered one
  are not used.
- Next reads and staleness count from the end of a registry read.
- Threads wait for a running read if the cache expires meanwhile.
- The own-URL check compares effective ports; default ports of http
  and https still count as the same.
- expand(snapshots=...) records the read that the candidates of each
  registry come from; URLs and read time are published together.
- Registry timeouts are finite; backend entries must be ordered.

Refs #493

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 9121442 into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/backend-lists branch October 25, 2026 20:56
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(plugins): add typed backend lists

1 participant