Repository navigation
fix(plugins): fix plugin store review findings - #568
Conversation
- 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]>
Reviewer's GuideThe 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 setupsequenceDiagram
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
Flow diagram for lowered plugin-store max_ttlflowchart 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
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Summary
Fixes the low findings of the 0.19.0 pre-release review of the plugin store (#557, #560) before the release.
db.dbs. The policy database thatregister_access_controladds when the app has no database of that name (e.g., nodbsection) is skipped, so the store stays in memory (local), as documented. The new propertyAccessControlConfig.added_databasetells the engine which database was added. An app database that also holds the policies (e.g., proTES) still holds the store.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 storedexpires_atof each namespace's entries to now + the currentmax_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.max_ttland one worker without a database. Apps log a warning once at startup if plugins that declaredata_storedkeep it in memory. FOCA can't see Gunicorn's worker count, so the warning names workers and replicas instead of detecting them.setup_store()logs its own errors for each phase and no longer raises.OperationFailures (codes 13, 18, 85, 86) are logged at error level with the server message.info.versionis 1.1.0, since there are new required fields. The docs say that plugins usingctx.storeordata_storedrequirefoca>=0.19.subject is None). Theget(key, default)wording for storednullis 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 themongodbtests against a private MongoDB 7.0.34 on localhost:12345.ruff check,ruff format --check,mypy,ast-grep scan,semgrep scan --config .semgrep --errorandmkdocs build --strict: all clean.test_access_control_databaseandtest_skipped_databasesfailed before the fix.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 intest_storage_schema.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_expiryto theStoreBackendprotocol 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