Skip to content

fix(plugins): bind gateway settings to their app - #525

Merged
uniqueg merged 4 commits into
devfrom
fix/gateway-app-binding
Oct 26, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/gateway-app-binding

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes finding 2 (medium) of the FOCA v0.18.0 pre-release review: a later Foca(...) without gateway= (e.g., the module-level Foca(...) in proTES's Celery worker module, which Connexion imports while the gateway app is created) silently cleared the gateway settings of the process, so create_app() or the first gateway request failed with a misleading "No gateway app configured" error.

Design (gateway settings bound to their app's configuration, fails safe):

  • Foca(...) without gateway= no longer touches the runtime.
  • The first Foca(gateway=...) binds its GatewayApp and its Config to the process, as one tuple. Every later Foca(gateway=...) must pass equal settings, whether or not a host exists (before, this depended on import order); only runtime.reset() clears them.
  • create_host(), plugin_classes() and get_backend_list() use the bound configuration instead of get_config() "latest" (which may be a worker module's).
  • create_app() serves only the app whose configuration is bound, checked before anything else, and fails otherwise (e.g., on a retry after a failed startup, or in tests without reset()). Nothing ever rebinds a configuration. Comparing configurations was not an option: create_app() changes them (e.g., db).
  • docs/plugins.md: every Foca(gateway=...) in a gateway process, also in a Celery worker module, must pass the same GatewayApp (define it once and import it, since new lambdas compare unequal); create the gateway app's Foca(...) before importing modules that create others.

proTES flow: app.py's Foca(gateway=G) binds; the worker module's Foca(...) (plain, or with gateway=G), imported during create_app(), changes nothing; a Celery worker process that imports only the worker module binds the worker's own configuration.

Closes #517

Verification

  • Regression tests first (failed before the fix): gateway Foca then plain Foca (also with the plain app created last, so "latest" points to it), other GatewayApp settings before any host exists (other API, new lambda), create_app() of another app with the same settings, forget() keeping the binding, errors after reset().
  • coverage run -m pytest with MongoDB 7.0: 2924 passed, 1 skipped; coverage report: 100%.
  • ruff check, ruff format --check, mypy: clean.
  • CI: all checks passed for d693330 (gate CI passed, tests on Python 3.11-3.15 with MongoDB, lowest deps, integration, codecov).

Reviews

adversarial-reviewer and quality-reviewer (round 1), adversarial-reviewer (round 2, no findings). Sourcery found 5 problems in the round-2 design (rebinding the configuration in create_app()), fixed in d693330 by dropping the rebind and publishing the binding atomically.

Declined review findings

  • Mark as breaking (!) and ship a reset fixture for consumers: foca/plugins/runtime.py is not in v0.17.0; the API is unreleased, so nothing breaks.
  • Docstring duplication across Foca, the module docstring, configure() and the docs: shortened the Foca docstring to point to configure(); the rest is user documentation.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Bind gateway settings and their configuration atomically to the first gateway app in a process and prevent unrelated FOCA instances from changing which app is served.

Bug Fixes:

  • Bind gateway settings to the first gateway app's configuration so later plain FOCA instances cannot clear or replace the active gateway runtime.
  • Ensure gateway hosts, plugins, backends, and app serving consistently use the bound gateway configuration instead of the most recently created FOCA app.

Enhancements:

  • Require all gateway FOCA instances in a process to use equal settings and reject serving a different app configuration until the runtime is reset.
  • Preserve gateway settings across fork cleanup while resetting hosts, and make runtime reset fully clear the binding.
  • Document gateway configuration and import-order requirements for gateway and worker processes.

Documentation:

  • Update plugin documentation to describe shared gateway settings, bound configurations, app-serving restrictions, and runtime reset behavior.

Tests:

  • Add regression coverage for plain FOCA instances, conflicting gateway settings, failed app startup retries, fork cleanup, and runtime reset behavior.

uniqueg and others added 2 commits October 26, 2026 17:54
Foca(...) without gateway= cleared the gateway settings of the process
until its host was created, e.g., when a Celery worker module with a
plain Foca(...) was imported during create_app(). Hosts and backend
lists also used the configuration of the FOCA app created last.

The first Foca(gateway=...) now binds its settings and configuration
to the process; later ones must pass the same settings, whether or not
a host exists, and Foca(...) without gateway= leaves them alone. Only
reset() clears them.

Closes #517

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Foca(gateway=...) with equal settings but another configuration was
accepted, and its configuration was ignored: create_app() checked the
plugins of the first app, and hosts and backend lists used them.
create_app() now binds the configuration of the app it creates, and
fails while the host of another configuration is in use (comparing
configurations is no option: create_app() changes them, e.g., db).

Also use _bound() in get_backend_list() and test forget() and the
errors after reset().

Refs #517

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v0.18.0 milestone Oct 26, 2026
@uniqueg uniqueg added priority: medium Medium priority type: bug Something isn't working labels Oct 26, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR makes gateway runtime state process-safe by binding a GatewayApp to its originating Config, ignoring plain Foca instances, and sourcing plugin and backend setup from that bound pair. create_app() explicitly rebinds its own configuration when safe, reset clears the binding, documentation explains the required shared GatewayApp usage, and focused tests cover import-order, rebinding, fork, and failure scenarios.

Sequence diagram for gateway configuration binding

sequenceDiagram
    participant GatewayApp
    participant FocaGateway
    participant Runtime
    participant FocaWorker
    participant Host

    GatewayApp->>FocaGateway: Foca(gateway=GatewayApp)
    FocaGateway->>Runtime: configure(GatewayApp, Config)
    Runtime-->>FocaGateway: Bind app and config
    FocaWorker->>FocaWorker: Foca() without gateway
    FocaWorker-->>Runtime: Leave binding unchanged
    GatewayApp->>FocaGateway: create_app()
    FocaGateway->>Runtime: configure(GatewayApp, AppConfig, rebind=True)
    Runtime-->>FocaGateway: Rebind when host is unused
    FocaGateway->>Runtime: create_host()
    Runtime->>Host: Build from bound Config
    Host-->>Runtime: PluginHost
Loading

State diagram for gateway runtime binding

stateDiagram-v2
    [*] --> Unbound
    Unbound --> Bound: configure(GatewayApp, Config)
    Bound --> Bound: Foca() without gateway
    Bound --> Bound: configure(same GatewayApp, Config)
    Bound --> Bound: configure(same GatewayApp, new Config, rebind=True) / host unused
    Bound --> Error: configure(other GatewayApp)
    Bound --> Error: rebind=True / host in use
    Bound --> HostActive: create_host()
    HostActive --> Bound: reset()
    Bound --> Unbound: reset()
    Error --> Bound: reset()
Loading

File-Level Changes

Change Details Files
Bind gateway settings together with the configuration they belong to, while leaving runtime state unchanged for plain FOCA instances.
  • Store the first gateway app and its Config in process runtime state.
  • Require later gateway instances to use equal GatewayApp settings.
  • Allow only create_app() to rebind the configuration when no host from another configuration is active.
  • Clear both settings and configuration on reset, while preserving them across fork-related host cleanup.
foca/plugins/runtime.py
foca/foca.py
Build plugin hosts, plugin class lists, and backend lists from the bound gateway configuration rather than the most recently created FOCA app.
  • Add a shared bound-state guard for missing gateway configuration.
  • Remove dependency on get_config() for runtime plugin and backend construction.
  • Keep gateway-specific validation and fail-safe errors when configuration or host ownership is invalid.
foca/plugins/runtime.py
Document the process-wide gateway binding contract and the requirement to reuse the same GatewayApp across gateway and worker modules.
  • Explain that plain Foca(...) does not alter gateway settings.
  • Document reuse of the same GatewayApp, including callable equality behavior.
  • Describe configuration binding, create_app() rebinding, reset(), and cross-configuration host failures.
docs/plugins.md
foca/foca.py
foca/plugins/runtime.py
Add regression coverage for gateway configuration isolation, rebinding, reset behavior, and fork semantics.
  • Verify plain apps cannot overwrite gateway settings or plugin/backend discovery.
  • Verify unequal gateway settings fail before host creation and reset permits a new gateway.
  • Verify create_app() validates and binds its own configuration, while active hosts block unsafe rebinding.
  • Verify forget() preserves settings and reset() makes runtime access fail safely.
tests/plugins/test_plugin_runtime.py

Assessment against linked issues

Issue Objective Addressed Explanation
#517 Keep gateway settings bound when a later Foca instance is created without gateway settings, and reject different gateway settings consistently until runtime.reset(). ✅
#517 Build plugin hosts and backend lists from the gateway app's bound configuration rather than whichever Foca configuration was created most recently. ✅
#517 Document the process-wide gateway configuration rules and add regression coverage for the reported scenarios. ✅

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

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #525   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           55        55           
  Lines         6611      6616    +5     
=========================================
+ Hits          6611      6616    +5     
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 26, 2026 18:52

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

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

## Individual Comments

### Comment 1
<location path="foca/foca.py" line_range="206" />
<code_context>
         # each process creates its own host on first use (after forks), so
         # plugins are instantiated (`setup()`) once more there
         if self.gateway is not None:
+            runtime.configure(self.gateway, self.conf, rebind=True)
             runtime.create_host().close()
             if self.gateway.backends is not None:
</code_context>
<issue_to_address>
**Earlier apps use later configuration**

When app A has returned without creating a host, then app B with the same gateway settings but a different configuration is created before A handles its first request, `configure()` allows the process-wide binding to change while `_runtime.host` is `None`, and A’s later `runtime.get_host()` uses B’s config, so A’s requests expose the wrong plugins or backends.

Keep the runtime configuration app-scoped, or reject rebinding once an app has been returned.

Also at `foca/plugins/runtime.py:138-144`.
</issue_to_address>

### Comment 2
<location path="foca/foca.py" line_range="206" />
<code_context>
         # each process creates its own host on first use (after forks), so
         # plugins are instantiated (`setup()`) once more there
         if self.gateway is not None:
+            runtime.configure(self.gateway, self.conf, rebind=True)
             runtime.create_host().close()
             if self.gateway.backends is not None:
</code_context>
<issue_to_address>
**Startup validates another app’s configuration**

When two gateway apps with equal settings but different configurations call `create_app()` concurrently, `runtime.configure()` releases its lock before `create_host()` or `get_backend_list()` reads the binding, so one startup validates the other app’s plugins or backends and can accept an invalid app or reject a valid one.

Serialize each app’s rebind together with its plugin and backend validation.

Also at `foca/plugins/runtime.py:138-144`.
</issue_to_address>

### Comment 3
<location path="foca/foca.py" line_range="206" />
<code_context>
         # each process creates its own host on first use (after forks), so
         # plugins are instantiated (`setup()`) once more there
         if self.gateway is not None:
+            runtime.configure(self.gateway, self.conf, rebind=True)
             runtime.create_host().close()
             if self.gateway.backends is not None:
</code_context>
<issue_to_address>
**Failed startup leaves config bound**

When a different app config is rebound while no persistent host exists, and startup validation raises but the process continues, `runtime.configure()` leaves the failed app’s config bound when `create_host()` or `get_backend_list()` raises, so later tasks or callers build from that config instead of the previously working one.

Restore the previous runtime binding if startup validation fails.

Also at `foca/plugins/runtime.py:138-144`.
</issue_to_address>

### Comment 4
<location path="foca/foca.py" line_range="206" />
<code_context>
         # each process creates its own host on first use (after forks), so
         # plugins are instantiated (`setup()`) once more there
         if self.gateway is not None:
+            runtime.configure(self.gateway, self.conf, rebind=True)
             runtime.create_host().close()
             if self.gateway.backends is not None:
</code_context>
<issue_to_address>
**Startup checks stale plugin capabilities**

When a later gateway app’s service-info runtime fields call `service_info_fields()` before the runtime is rebound, `check_service_info()` runs before `runtime.configure()`, so `service_info_fields()` reaches `runtime.plugin_classes()` with the previously bound config; startup can validate or expose stale capabilities, or reject a valid app.

Run the service-info check using the new app’s runtime configuration.

Also at `foca/plugins/runtime.py:251`.
</issue_to_address>

### Comment 5
<location path="foca/plugins/runtime.py" line_range="130" />
<code_context>
-        if _runtime.host is not None and app != _runtime.app:
+        if _runtime.app is None:
+            _runtime.app = app
+            _runtime.config = config
+            return
+        if app != _runtime.app:
</code_context>
<issue_to_address>
**Lookups fail during binding**

When the first gateway binding is being initialized while another thread calls a plugin or backend lookup, `configure()` publishes `_runtime.app` before `_runtime.config`, while `_bound()` reads both without the lock, so the lookup sees a partial binding and raises `RuntimeError`, interrupting startup or a request.

Publish the app and config atomically, or make `_bound()` read them under the same lock.

Also at `foca/plugins/runtime.py:177-179`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and if the wrong configuration is bound, the gateway can load the wrong plugins and build its backend list from the wrong settings, potentially sending work to an unintended external backend. Reverting restores the binding but cannot recall work already dispatched.

Blocking findings: foca/foca.py:206, foca/foca.py:206, foca/foca.py:206, foca/foca.py:206, foca/plugins/runtime.py:130


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

Comment thread foca/foca.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/plugins/runtime.py Resolved
Rebinding the configuration in create_app() let an app that was
already returned use the configuration of a later app, raced with
concurrent startups, kept a failed app's configuration bound and ran
the service info check against the previous configuration (Sourcery).

create_app() now serves only the app whose configuration the first
Foca(gateway=...) bound, checked before anything else, and fails
otherwise (reset() clears the binding, e.g., in tests). Settings and
configuration are bound together as one tuple, so readers without the
lock never see one without the other.

Refs #517

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

@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 23822c5 into dev Oct 26, 2026
30 checks passed
@uniqueg
uniqueg deleted the fix/gateway-app-binding branch October 26, 2026 19:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: medium Medium priority type: bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Plain Foca(...) clears the gateway settings

1 participant