Skip to content

fix(plugins): fix plugin store review findings - #568

Merged
uniqueg merged 6 commits into
devfrom
fix/plugin-store-564
Oct 31, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/plugin-store-564

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes the low findings of the 0.19.0 pre-release review of the plugin store (#557, #560) before the release.

  • Store database: the store uses only the app's own databases of db.dbs. The policy database that register_access_control adds when the app has no database of that name (e.g., no db section) is skipped, so the store stays in memory (local), as documented. The new property AccessControlConfig.added_database tells the engine which database was added. An app database that also holds the policies (e.g., proTES) still holds the store.
  • Lowered max_ttl: I did not add a read-time cap. Capping reads would need a write time on every entry, and it would still leave the data in the database until the original expiry. Instead, PluginHost.setup_store() (at startup) cuts the stored expires_at of each namespace's entries to now + the current max_ttl (the longest of the namespace's plugins on the shared backend). Reads and the TTL index then follow the new setting, so retention is bounded too. The docs explain when this applies: at the next start that succeeds, and after a second restart for rolling updates. For turned-off stores, the docs give a cleanup recipe (db.plugin_store.deleteMany({ns: "<namespace>"})), since their entries are no longer read but stay in the database until they expire.
  • Memory store: the docs now say it is unbounded (no namespace limit in v1, per Decision 4) and recommend a short max_ttl and one worker without a database. Apps log a warning once at startup if plugins that declare data_stored keep it in memory. FOCA can't see Gunicorn's worker count, so the warning names workers and replicas instead of detecting them.
  • Setup errors: setup_store() logs its own errors for each phase and no longer raises.
    • Permanent OperationFailures (codes 13, 18, 85, 86) are logged at error level with the server message.
    • Other errors are warnings with type and code, without messages, which may name hosts.
    • Capping is bounded by one 10 s deadline and fails per namespace, so one failure doesn't skip the other namespaces.
  • Listing spec: info.version is 1.1.0, since there are new required fields. The docs say that plugins using ctx.store or data_stored require foca>=0.19.
  • Docs: the per-user budget example handles anonymous callers (subject is None). The get(key, default) wording for stored null is fixed; the behaviour is unchanged.

Not in scope: key_for() uses an unkeyed SHA-256, while the design asked for a keyed hash (HMAC). That needs a maintainer decision.

Closes #564

Verification

  • coverage run -m pytest && coverage report -m: 3238 passed, 2 skipped, 100% coverage. This was on Python 3.12, with the mongodb tests against a private MongoDB 7.0.34 on localhost:12345.
  • ruff check, ruff format --check, mypy, ast-grep scan, semgrep scan --config .semgrep --error and mkdocs build --strict: all clean.
  • Regression tests:
    • test_access_control_database and test_skipped_databases failed before the fix.
    • Other new tests: test_app_policy_database, test_cap_expiry (all backends), test_setup_caps_expiry, test_cap_errors, test_local_warning, test_create_app_setup_error_levels, test_AccessControlConfig_added_database, and the spec version check in test_storage_schema.
  • Reviews: adversarial-reviewer and quality-reviewer, two rounds. All confirmed findings are fixed. In round 1 these covered setup errors per phase with one deadline, code 18, the public accessor, tighter tests and the rolling-update docs. In round 2 they covered server messages for permanent errors only, a unit test for the accessor and the hint wording.
  • CI: all checks passed on 5dfc8d8 (run 41207685938; the MongoDB 8.0 jobs skip on affected runner kernels, as designed); re-run after merging dev.
  • Sourcery: five threads. Fixed: capping is tried without indexes too, it stops once the shared deadline has passed, and the docs on memory retention of expired entries are clarified. Answered: no read-time cap (explained above), and no warning for turned-off stores (the operator chose it; now documented). All threads resolved.
  • Not run locally: the integration and Helm jobs, image scans, test-lowest, the other Python versions and MongoDB 8.0 (CI runs them).

Declined review findings

  • Commit trailers name a different model than the session reminder (quality, low): the trailers follow the session's attribution reminder (Claude Opus 5.5).

  • Adding cap_expiry to the StoreBackend protocol breaks third-party backends (quality, low): the protocol is new in 0.19, which isn't released yet.

  • The spec version assert needs a bump with every spec change (quality, low): that is intended, as a guard.

  • Sourcery: read-time cap instead of capping at startup, and a warning for turned-off stores; see the threads.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 31, 2026 12:33
- Use only the app's own databases for the store: the policy database
  that access control adds without a `db` section is skipped, so the
  store stays in memory (`local`) then.
- Cut the expiry of each namespace's entries to the current `max_ttl`
  at startup, so that a lowered `max_ttl` applies to existing entries
  (reads and retention).
- Warn once at startup if plugins that declare `data_stored` keep it
  in memory, as no database is configured.
- Log permanent setup errors (MongoDB codes 13, 85, 86) as errors with
  their cause; others stay warnings without the message.
- Bump the listing spec to 1.1.0 (new required fields).

Refs #564

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document that the store uses the app's own first database (not the
access-control policy database), that memory stores are unbounded
(short `max_ttl`, one worker), when a lowered `max_ttl` applies, how to
remove entries of turned-off stores, `get()` defaults with stored
`null`, the anonymous case of the per-user budget example, and that
plugins using the store require `foca>=0.19`.

Refs #564

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

- Log the setup errors in the host, per phase: index errors as before,
  capping errors per namespace, so that one failure no longer skips the
  other namespaces and messages say what failed.
- Bound capping by one 10 s deadline for all namespaces.
- Treat AuthenticationFailed (18) as permanent too; give code and
  server message also in warnings of server errors.
- Read the policy database that access control added through a public
  property, `AccessControlConfig.added_database`.
- Document when a lowered max_ttl applies (rolling updates, failures).
- Tighten the tests.

Refs #564

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log the server message of store setup errors only for the permanent
error codes, as messages of other errors (e.g., of shards) may name
hosts; keep the code in all warnings. Make the code set private, name
credentials in the hint, and test `added_database` and transient
capping errors directly.

Refs #564

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

sourcery-ai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR hardens plugin-store initialization by correctly identifying app-owned databases, migrating existing entry expiries when TTL settings are lowered, and making setup failures observable but non-fatal. It also adds local-memory warnings, updates plugin-store and compatibility documentation, bumps the listing specification to 1.1.0, and adds regression coverage across backends and startup error paths.

Sequence diagram for startup plugin store setup

sequenceDiagram
    participant App as Foca.create_app
    participant Host as PluginHost.setup_store
    participant Backend as StoreBackend
    participant Logger as Logger

    App->>Host: setup_store()
    opt local store with data_stored plugins
        Host->>Logger: warning
    end
    Host->>Backend: setup()
    alt setup succeeds
        loop each namespace
            Host->>Backend: cap_expiry(namespace, expires_at, timeout)
            alt capping fails
                Host->>Logger: log setup error
            end
        end
    else setup fails
        Host->>Logger: log setup error
    end
    Host-->>App: return without raising
Loading

Flow diagram for lowered plugin-store max_ttl

flowchart TD
    Start([App startup]) --> Setup[StoreBackend.setup]
    Setup -->|success| Namespaces[Determine namespace max_ttl]
    Setup -->|failure| LogSetup[Log error or warning]
    LogSetup --> Continue([App continues startup])
    Namespaces --> Cap[cap_expiry for each namespace]
    Cap --> TTL[TTL index removes entries at the new expiry]
    Cap -->|namespace failure| LogCap[Log failure for that namespace]
    TTL --> Continue
    LogCap --> Continue
Loading

File-Level Changes

Change Details Files
Select the plugin store from app-owned databases while excluding databases injected by access-control registration.
  • Expose whether access-control added its policy database.
  • Skip injected databases when choosing the shared MongoDB backend.
  • Preserve shared storage when an app explicitly owns the policy database, otherwise use memory storage.
foca/models/config.py
foca/plugins/engine.py
foca/foca.py
docs/configuration/plugins.md
foca/plugins/store.py
tests/models/test_config.py
tests/plugins/test_plugin_store.py
Apply lowered retention limits to existing entries during startup without blocking application startup.
  • Add backend-level expiry capping for memory and MongoDB stores.
  • Compute the longest configured TTL per namespace and cap existing expiries under one ten-second startup deadline.
  • Continue processing namespaces independently when capping fails.
foca/plugins/engine.py
foca/plugins/store.py
docs/configuration/plugins.md
docs/plugins.md
tests/plugins/test_plugin_store.py
Make store startup failures non-fatal while distinguishing permanent database errors from transient or potentially sensitive failures.
  • Log index setup and expiry-capping errors internally by phase.
  • Use error severity and server messages only for permanent MongoDB error codes; use warnings without potentially host-identifying messages otherwise.
  • Remove exception handling from app creation because the host now owns setup logging.
foca/plugins/engine.py
foca/foca.py
docs/configuration/plugins.md
tests/plugins/test_plugin_store.py
Improve diagnostics and compatibility documentation for local stores and the plugin listing contract.
  • Warn once when data-retaining plugins use unbounded per-process memory storage.
  • Document worker/replica behavior, TTL migration and cleanup procedures, anonymous budgets, stored-null defaults, and the FOCA version requirement.
  • Bump the listing specification to version 1.1.0 and test the new required storage fields.
foca/plugins/engine.py
foca/plugins/api.yaml
docs/configuration/plugins.md
docs/plugins.md
foca/plugins/store.py
tests/plugins/test_plugin_api.py
tests/plugins/test_plugin_store.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (02f2592) to head (74a6a86).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #568   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7010      7068   +58     
=========================================
+ Hits          7010      7068   +58     
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 31, 2026 13:41

@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/plugins/engine.py" line_range="709" />
<code_context>
+                    else ""
+                ),
+            )
+            return
+        max_ttls: dict[str, float] = {}
+        for settings in self._stores.values():
</code_context>
<issue_to_address>
**Lowered TTL migration is skipped**

When mongoDB is writable but index creation fails, such as on a conflicting index (codes 85 or 86), while the operator has lowered `max_ttl`, `setup_store()` returns after an index-creation error without attempting `cap_expiry()` for any namespace. A permanent index conflict can leave the database writable, but existing entries then retain their old expiry despite the lowered `max_ttl`.

Attempt namespace expiry capping even when index setup fails, with the same bounded deadline and per-namespace error handling.
</issue_to_address>

### Comment 2
<location path="foca/plugins/store.py" line_range="485-503" />
<code_context>
     def setup(self) -> None:
         """Prepare the backend, e.g., create indexes, at startup."""

+    def cap_expiry(self, ns: str, expires_at: datetime, timeout: float) -> None:
+        """Cut the expiry of a namespace's entries that expire later.
+
</code_context>
<issue_to_address>
**Read-time TTL cap**

The issue asks to cap reads at the current max_ttl. This change instead shortens stored expiries at startup, so entries may still be readable beyond the new limit if capping fails or old-setting processes write during a rolling update.
</issue_to_address>

### Comment 3
<location path="foca/plugins/engine.py" line_range="725" />
<code_context>
+                self._store_backend.cap_expiry(
+                    namespace,
+                    now + timedelta(seconds=max_ttl),
+                    max(deadline - time.monotonic(), 0.001),
+                )
+            except PyMongoError as exc:
</code_context>
<issue_to_address>
**Startup exceeds deadline**

When many namespace caps remain after the shared deadline expires, `max(deadline - time.monotonic(), 0.001)` gives each remaining namespace a timeout after the deadline, so `setup_store()` continues issuing MongoDB calls and startup exceeds the stated 10-second bound.

Stop issuing `cap_expiry()` calls once the shared deadline has expired.

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

### Comment 4
<location path="foca/plugins/engine.py" line_range="681" />
<code_context>
+        local = sorted(
+            plugin_id
+            for plugin_id, settings in self._stores.items()
+            if settings.mode == "local" and self.plugins[plugin_id].cls.data_stored
+        )
+        if local:
</code_context>
<issue_to_address>
**Disabled stores go unwarned**

When a plugin declares `data_stored` and its store is disabled, `_store_settings()` assigns the plugin mode `off` but keeps its entries in a `MemoryStoreBackend`, while `setup_store()` warns only for mode `local`; operators therefore get no warning that the plugin's entries remain in process memory.

Include disabled stores backed by `MemoryStoreBackend` in the warning for plugins declaring `data_stored`.
</issue_to_address>

### Comment 5
<location path="docs/plugins.md" line_range="405" />
<code_context>
   each process has its own (`local` or `off`): counters then hold per
-  process, so budgets are only approximate. A plugin whose store is off
+  process, so budgets are only approximate, and the entries' memory is not
+  bounded by size, only by `max_ttl`. A plugin whose store is off
   doesn't see the entries of the other plugins of its distribution (the
   app logs a warning).
</code_context>
<issue_to_address>
**Expired entries remain allocated**

When expired entries are not read and fewer than 1,024 subsequent writes occur, `MemoryStoreBackend` removes expired entries only when they are read or during a sweep every 1,024 writes, so the entries remain allocated indefinitely and a short `max_ttl` does not bound actual memory retention.

Document that `max_ttl` limits logical expiry rather than retained memory, and do not present a short TTL as preventing memory growth.

Also at `foca/plugins/engine.py:689`, `docs/configuration/plugins.md:199`.
</issue_to_address>

Linked issues

#564 fix: plugin store findings before 0.19.0 · 6 of 7 met

# Requirement Status Notes
1 Use only the app's own databases for the store; use memory otherwise when access control adds the policy database. ✅ Met The engine skips the database reported by AccessControlConfig.added_database, and regression tests cover both the added policy database and an app database that also holds policies.
2 Document the unbounded memory store, recommend a short max_ttl, and warn at startup when plugins declaring stored data use it without a database. ✅ Met The docs explain memory growth and recommend a short max_ttl and one worker; setup_store warns for data_stored plugins using local storage and notes per-process counters.
3 Cap reads at the current max_ttl; document retention and cleanup for lowered max_ttl and turned-off stores. 🟡 Partly met The docs cover retention and cleanup, and startup attempts to shorten persisted expiries, but reads are not capped directly and can outlive the new max_ttl if capping fails or old-setting processes continue writing.
4 Handle anonymous callers in the per-user budget example. ✅ Met The example checks for a missing subject and raises NotApplicable before creating a per-user key.
5 Correct the docs for get(key, default) when the stored value is null. ✅ Met The docs now say the default applies only to absent or expired keys and explain that stored null returns None.
6 Bump the listing spec version and document that plugins using ctx.store or data_stored need foca>=0.19. ✅ Met The listing spec is 1.1.0, and the plugin docs state the foca>=0.19 requirement.
7 Log permanent index errors with codes 85, 86 and 13 at error level with the cause. ✅ Met Store setup logs these codes at error level with the server message; code 18 is also treated as permanent.

Sourcery assessment

Needs a human reviewer. 5 findings to address first, and at startup, entries whose expiry exceeds the namespace’s current max_ttl are rewritten to expire sooner, and MongoDB’s TTL cleanup can then delete them. If that retention limit is wrong, the affected entries are gone; reverting stops future capping but cannot restore them.

Blocking findings: foca/plugins/engine.py:709, foca/plugins/store.py:503, foca/plugins/engine.py:725, foca/plugins/engine.py:681, docs/plugins.md:405


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/store.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread docs/plugins.md Resolved
uniqueg and others added 2 commits October 31, 2026 14:54
Address Sourcery review: try capping also if the indexes could not be
created (e.g., a conflicting index leaves the database writable), stop
capping once the shared deadline has passed (logging the namespaces
left), and document that memory stores keep expired entries until
they are read or swept, also for turned-off stores.

Refs #564

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit d47edd7 into dev Oct 31, 2026
31 checks passed
@uniqueg
uniqueg deleted the fix/plugin-store-564 branch October 31, 2026 14:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: plugin store findings before 0.19.0

1 participant