Skip to content

feat(plugins): add default failover router - #504

Merged
uniqueg merged 113 commits into
devfrom
feat/failover-router
Oct 25, 2026
Merged

uniqueg merged 113 commits into
devfrom
feat/failover-router

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds foca.routing.ordered (foca.plugins.routing.OrderedRouter), the default route step of gateways and the least surprising one. It keeps the order of the backend list, and shuffles the backends of each service registry among themselves (random.SystemRandom), with no round-robin state. This is the sixth PR of the v0.18.0 plugin stack (#485).

  • Params:
    • labels: keep only candidates that have them.
    • seed: for tests only, refused unless the admin setting allow_seed is on.
    • The order used per registry group is recorded in the provenance.
  • Built-ins:
    • BUILTIN_PLUGINS is the only source of built-in plugins; there is no entry point in FOCA's metadata.
    • Built-ins (the reserved foca.* prefix) are available without a plugins.available entry. Such an entry may set only enabled, roles, client_selectable and config.
    • Other distributions that claim a built-in ID are refused.
  • Default pipeline: the router is the default pipeline, and the default client_pipelines.append step for pipelines without a route step. if_missing_phase looks only at the client's or preset's own steps.
  • Param checks: Plugin.check_params() lets plugins refuse params when pipelines are resolved, by raising the new InvalidParams (400). Other exceptions count as plugin errors.
  • Docs: routing (the algorithm, how forward failures are classified, and a breaking-change note for proTES), and where pinning must go.

Closes #491

Verification

Run locally on 85f85d0 (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.
  • mkdocs build --strict: pass.
  • pre-commit: pass.

The MongoDB tests and semgrep did not run locally (CI runs them). CI on 85f85d0: 27 checks pass, and 2 are skipped as intended.

Review: two rounds of adversarial and quality review.

  • Round 1 (272a796):
    • built-ins had two sources (an entry point and the code), so the order of entry points mattered;
    • every exception from check_params was reported as invalid params;
    • tests for seeds and snapshots were missing;
    • the docs didn't say that router labels don't bind client pipelines.
  • Round 2:
    • a route step in client_pipelines.prepend dropped the appended router (85f724d);
    • the docs didn't say where pinning that must always hold goes (b0376b8).

All are fixed.

Sourcery: 4 findings, all fixed in a9c8dac:

  • only InvalidParams from check_params gives 400; validation errors, SystemExit and other errors are plugin errors;
  • foreign distributions can't claim disabled built-ins;
  • test_no_groups now checks configured backends in exact order.

CI on a9c8dac: 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]>
`foca.routing.ordered` (`foca.plugins.routing.OrderedRouter`) is the
least surprising route step: it keeps the order of the backend list and
shuffles the backends of each service registry among themselves
(`random.SystemRandom`), with no round-robin state. Optional params:
`labels` (keep only candidates with them) and `seed` (tests only,
refused unless the admin setting `allow_seed` is on).

- FOCA registers it as an entry point; built-ins (`foca.*`, a reserved
  prefix) are available without a `plugins.available` entry, which may
  only set `enabled`, `roles`, `client_selectable` and `config`; other
  distributions must not provide them, and they load from their object
  reference if FOCA's metadata lacks the entry point
- it is the default pipeline, and the default `client_pipelines.append`
  step for pipelines without a route step (`on_failure: skip`)
- `Plugin.check_params()` lets plugins refuse params when pipelines are
  resolved
- `run.route(candidates, snapshots=...)` records the registry read
  times in the provenance

Refs #491

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]>
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
uniqueg and others added 23 commits October 25, 2026 06:37
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]>
The appended router's if_missing_phase also counted the admin's
prepend steps, so a route plugin in prepend dropped
foca.routing.ordered from every client and preset pipeline. Only the
client's or preset's own steps count now.

Refs #491

Co-Authored-By: Claude Opus 5.5 <[email protected]>
client_pipelines.prepend frames client and preset pipelines only,
not plugins.pipeline, so pinning that must always hold belongs in
both. The router's module docstring now says that BUILTIN_PLUGINS is
its only source, not an entry point.

Refs #491

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]>
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]>
- 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]>
@sourcery-ai

sourcery-ai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implements foca.routing.ordered as FOCA's built-in default route step, with ordered failover, per-registry randomization, label and test-seed parameters, and provenance recording. The PR also establishes built-in plugin discovery and namespace rules, adds lifecycle-time parameter validation with correct error handling, applies the router across default and client pipelines, and documents the resulting routing and pipeline semantics.

Sequence diagram for ordered backend failover

sequenceDiagram
    participant PipelineRun
    participant OrderedRouter
    participant Backend

    PipelineRun->>OrderedRouter: on_route(candidates, ctx)
    OrderedRouter->>OrderedRouter: filter candidates by labels
    OrderedRouter->>OrderedRouter: shuffle discovered backends per registry group
    OrderedRouter-->>PipelineRun: ordered candidates
    PipelineRun->>Backend: forward request to next candidate
    alt backend certainly did not accept request
        PipelineRun->>Backend: forward request to next candidate
    else unknown outcome
        PipelineRun-->>PipelineRun: stop failover
    end
Loading

Flow diagram for default and client routing pipelines

flowchart LR
    Config[PluginsConfig] --> Default[Default pipeline]
    Config --> Client[Client or preset pipeline]
    Default --> Router[foca.routing.ordered]
    Client --> Frame[client_pipelines framing]
    Frame --> Missing{Route phase missing?}
    Missing -->|Yes| Router
    Missing -->|No| Existing[Existing route step]
    Router --> Resolve[Resolve plugin parameters]
    Existing --> Resolve
Loading

File-Level Changes

Change Details Files
Adds the built-in ordered failover router and makes it the default gateway routing behavior.
  • Introduces OrderedRouter with label filtering, per-registry SystemRandom shuffling, deterministic test seeds, and execution annotations.
  • Adds routing configuration models and registers the router through the built-in plugin map.
  • Defaults the main pipeline to the router and appends it to client and preset pipelines when no route phase is present.
  • Records registry snapshots and routing results in request provenance.
foca/plugins/routing.py
foca/plugins/config.py
foca/plugins/engine.py
foca/plugins/loader.py
foca/plugins/__init__.py
tests/plugins/test_plugin_routing.py
tests/plugins/test_plugin_basics.py
tests/plugins/test_plugin_engine.py
tests/plugins/test_plugin_loader.py
tests/plugins/test_plugin_provenance.py
tests/plugins/test_plugin_runtime.py
tests/plugins/test_plugin_selection.py
Hardens plugin parameter validation and built-in plugin resolution.
  • Adds Plugin.check_params() and distinguishes expected InvalidParams failures from unexpected plugin errors.
  • Reserves the foca.* namespace, makes BUILTIN_PLUGINS the sole built-in source, and rejects foreign providers and pins.
  • Allows built-ins to be configured without allowlist entries while preserving enablement, role, client-selection, and config controls.
foca/plugins/base.py
foca/plugins/engine.py
foca/plugins/config.py
foca/plugins/loader.py
tests/plugins/test_plugin_routing.py
tests/plugins/test_plugin_basics.py
Documents default routing semantics, pipeline framing rules, provenance, and plugin configuration constraints.
  • Explains ordered failover classification, registry shuffling, labels, test-only seeds, and snapshot provenance.
  • Clarifies how pipeline, preset, prepend, and append steps interact and where always-enforced routing or pinning belongs.
  • Adds API reference entries and plugin parameter-validation guidance.
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md

Assessment against linked issues

Issue Objective Addressed Explanation
#491 Add the built-in ordered failover router, with label filtering, optional admin-gated seeding, and built-in plugin loading without requiring an allowlist entry. ✅
#491 Make the router the default route step for gateway and appended client pipelines, and document the routing and failover behavior. ✅
#491 Record per-registry-group routing provenance, including the entry ID, snapshot time, backend count, and shuffled order. ❌ The router records only aggregate annotations such as the number of shuffled groups. Snapshot times and candidate lists are recorded separately in route provenance, but the PR does not record each registry group's backend count and shuffled order alongside its entry ID and snapshot time.

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 (9121442) to head (a9c8dac).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #504   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           50        51    +1     
  Lines         5778      5870   +92     
=========================================
+ Hits          5778      5870   +92     
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 October 25, 2026 21:09

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

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

## Individual Comments

### Comment 1
<location path="foca/plugins/engine.py" line_range="390" />
<code_context>
                         f"Invalid params of plugin {alternative.plugin!r} in step"
                         f" {step.id!r}: {exc}"
                     ) from exc
+                except Exception as exc:
+                    logger.exception(
+                        "Plugin %s failed to check params", alternative.plugin
</code_context>
<issue_to_address>
**SystemExit bypasses plugin error handling**

When a plugin’s `check_params()` raises `SystemExit` while a pipeline is resolved, `resolve_steps()` catches only `Exception` from `check_params()`, so `SystemExit` bypasses the `PluginError` handling and can terminate the request worker or process while resolving a pipeline.

Handle `SystemExit` from `check_params()` in the same plugin-error path as other plugin failures.

Also at `foca/plugins/engine.py:392`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/loader.py" line_range="304-305" />
<code_context>
                 continue
-            entry_point = _find(plugin_id, candidates)
+            entry_point = (
+                _find_builtin(plugin_id, candidates)
+                if plugin_id in BUILTIN_PLUGINS
+                else _find(plugin_id, candidates)
+            )
</code_context>
<issue_to_address>
**Disabled built-in conflicts go unchecked**

When the built-in is disabled in `plugins.available` and another distribution registers the same identifier, `find_entry_points()` skips disabled plugins before it reaches `_find_builtin()`, so a foreign distribution that claims a reserved built-in ID is not refused when that built-in is disabled. The installation can therefore pass startup despite violating the stated built-in ID ownership rule.

Check for conflicting built-in entry points independently of whether the built-in plugin is enabled.
</issue_to_address>

### Comment 3
<location path="foca/plugins/engine.py" line_range="384" />
<code_context>
                 try:
                     params = loaded.cls.Params.model_validate(alternative.params)
-                except ValidationError as exc:
+                    loaded.instance.check_params(params)
+                except (ValidationError, InvalidParams) as exc:
                     raise ValueError(
</code_context>
<issue_to_address>
**Plugin bug becomes client 400**

When a plugin's `check_params()` raises Pydantic's `ValidationError`, `resolve_steps()` catches `ValidationError` from either parameter validation or `check_params()` and wraps it as `ValueError`; `resolve()` then reports it as an invalid client selection instead of a plugin failure, so the caller receives a misleading 400.

Handle parameter-model validation separately from `check_params()`, and classify only `InvalidParams` from the latter as invalid parameters.
</issue_to_address>

### Comment 4
<location path="tests/plugins/test_plugin_routing.py" line_range="90-91" />
<code_context>
+
+def test_no_groups() -> None:
+    """Configured backends only are not shuffled."""
+    ids, run = route({"labels": {"region": "us"}, "seed": None})
+    assert sorted(ids) == ["r0", "r2"]
+    ids, run = route({"labels": {"nothing": "x"}})
+    assert ids == []
</code_context>
<issue_to_address>
**No-group case is not exercised**

When the router shuffles candidates when the input has no discovered registry groups, `test_no_groups` (`tests/plugins/test_plugin_routing.py:90-94`) filters to `r0` and `r2`, which are discovered candidates in group `reg`, then sorts their IDs; its other case routes no candidates. A router that shuffles candidates when there are no registry groups therefore passes without exercising that behavior.

Route at least two configured candidates with no registry group and assert their exact order.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/plugins/engine.py:390, foca/plugins/engine.py:384, tests/plugins/test_plugin_routing.py:91


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

Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/loader.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread tests/plugins/test_plugin_routing.py Resolved
- Only InvalidParams from check_params means invalid params (400);
  validation errors, SystemExit and other errors of the hook are
  plugin errors.
- Other distributions must not claim built-ins, even disabled ones.
- test_no_groups routes configured backends only, in exact order.

Refs #491

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 3e6e1b2 into dev Oct 25, 2026
30 checks passed
@uniqueg
uniqueg deleted the feat/failover-router branch October 25, 2026 21:27
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 default failover router

1 participant