Skip to content

feat(plugins): add plugin key-value store - #557

Merged
uniqueg merged 6 commits into
devfrom
feat/550-plugin-store
Oct 29, 2026
Merged

uniqueg merged 6 commits into
devfrom
feat/550-plugin-store

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Gives gateway plugins a small key-value store, ctx.store, across requests, processes and replicas (first part of #545).

  • API: get(key, default=None), set(key, value, *, ttl=None), delete(key), and an atomic increment(key, by=1, *, ttl=None, limit=None) that returns the new value, or None without incrementing if it would exceed limit (or go below -(2^53 - 1)). Counters get their TTL when created (fixed window, e.g. per day). key_for(*parts) derives pseudonymous keys (SHA-256 of namespace and parts) from e.g. user identifiers.
  • Backend: one shared plugin_store collection in the first database of db.dbs, documents {_id: "<ns>\x1f<key>", ns, key, value | n, expires_at}, a TTL index on expires_at and an index on ns. Increments are conditional single-document updates decided by the server ($inc within the bounds; else insert or replace of an absent or expired entry; retried on races, at most 5 times). Reads filter out expired entries, as MongoDB's TTL monitor runs about once a minute. Works with mongomock too (apps' tests).
  • Indexes: create_app() creates them; if that fails (e.g. database not up yet), the app logs a warning and starts, and writes create them first, so no entry is written without the TTL index.
  • Without database, or for plugins whose store the operator turned off, each process keeps the entries in memory (same semantics). ctx.store.mode is shared, local or off. A warning is logged if plugins of one distribution disagree on the switch.
  • Namespace per distribution (PEP 503 name; built-in plugins: foca); plugins can't choose it.
  • Config: plugins.defaults.store (enabled, max_entry_size 4 KiB, max_ttl 30 days, at most 10 years, which entries without TTL get) with per-plugin overrides in plugins.available.<id>.store. No namespace size limit yet (feat(plugins): limit store namespace size #552).
  • Calls are bounded by the hook's deadline (pymongo.timeout); database errors and timeouts raise foca.plugins.StoreError (a PluginError), which fails the alternative like any other error. Argument errors raise ValueError.
  • Testing: the harness's hooks get a memory store; PluginHarness.store gives tests the same entries.
  • Docs: plugin guide (new "Plugin store" section), configuration (store settings, collection, indexes), API reference.

Design decisions (from the design note, decided by the maintainer): one shared collection; off switch falls back to memory; namespace per distribution; no namespace size limit in v1. The listing of stored data and the storage mode follows in #551.

Note: StoreError lives in foca/plugins/store.py, not foca/plugins/errors.py as the design note sketched: errors.py holds the client-facing gateway errors (problem details), while StoreError is a plugin error.

Closes #550

Verification

  • coverage run -m pytest with a local MongoDB 7.0 on port 12345: 3217 passed (after the Sourcery fixes), 2 skipped (one of them pre-existing; the other is the thread test on mongomock, which isn't thread-safe), coverage 100%. The store tests run on the memory backend, mongomock and a real MongoDB (TTL expiry with an injected clock, atomic increments from 10 threads against a limit, document layout, timeouts, datetime_conversion=DATETIME_MS clients).
  • ruff check, ruff format --check, mypy: clean.
  • pre-commit run --all-files (incl. semgrep and ast-grep): passed.
  • mkdocs build --strict: passed.
  • CI: all checks passed on 3ec62aa, after the Sourcery fixes and a merge of dev (CI passed; tests on Python 3.11 to 3.15 with MongoDB 7.0 and 8.0, lowest dependencies, integration, chart, image scans, Codecov patch and project, Read the Docs).

Declined review findings

  • PluginHost.store_settings stays public (quality review suggested making it private): the plugin listing of feat(plugins): list plugin storage #551 uses it to show the storage mode.
  • The thread test skips mongomock in its body rather than via a fixture mark (low): one line, and the fixture's params stay uniform for all other tests.
  • PluginHarness.store stays a property next to the class docstring; it is listed under Attributes now (low, cosmetic).
  • Sourcery: unbounded number of distinct keys per namespace. Declined for this PR as decided for v1; the namespace limit is feat(plugins): limit store namespace size #552. Entries expire after max_ttl at the latest, and values and keys are capped in size.

Sourcery's other eight findings are fixed in 430736d: size check before the I-JSON checks, no keys in counter errors, index setup bounded by 10 s, primary reads, lock wait bounded by the deadline, falsy backends kept, and two test gaps.

Reviews: two rounds of adversarial and quality review; all high/medium findings fixed (limit bypass with datetime_conversion client options, increments failing under mongomock, startup failure without index rights, public backend protocol returning a private type, duplicated counter rules), as well as the cheap lows (bounded max_ttl, lower counter bound, millisecond TTLs, namespace split warning, entries without valid expiry, docs example).

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 28, 2026 19:55
Give plugin hooks `ctx.store`, a small key-value store across requests:
get, set (with TTL), delete and an atomic increment with an optional
limit (fixed window: the TTL is set when the counter is created).

- One shared `plugin_store` collection in the first database of
  `db.dbs` (TTL index on `expires_at`, index on `ns`, created by
  `create_app()`); without database, a per-process memory backend.
- Namespace per distribution (PEP 503 name; built-ins: `foca`).
- `plugins.defaults.store` (`enabled`, `max_entry_size`, `max_ttl`) with
  per-plugin overrides in `plugins.available.<id>.store`; a plugin whose
  store is off gets the memory backend.
- Calls are bounded by the hook deadline; database errors and timeouts
  raise `StoreError`, which fails the alternative.
- `PluginHarness.store` for plugin tests.

Closes #550

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe `ctx.store` in the plugin guide (API, limits, namespaces,
modes, errors, personal data, testing), the `store` settings and the
`plugin_store` collection in the configuration docs, and add
`foca.plugins.store` to the API reference.

Refs #550

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Increment with plain conditional updates decided by the server
  (`$inc` with bounds, then insert or replace of absent or expired
  entries, retried on races) instead of an aggregation pipeline whose
  result was re-derived in Python: results no longer depend on the
  client's datetime options, and mongomock runs it (apps' tests).
- Pin time zone aware datetimes on the store collection.
- Counters stay within -(2^53 - 1) as well; TTLs are at least 1 ms and
  expiries are stored in milliseconds; `max_ttl` is finite, at most 10
  years.
- Start apps with a warning if the indexes can't be created; writes
  create them first, so no entry is written without the TTL index.
- Warn if plugins of one distribution disagree on the off switch.
- `StoreEntry` is public (backend protocol); simpler `_guard` and
  integer checks; comments on the counter rules.
- Docs: complete example, counters via `get()`, index and off-switch
  behaviour, mongomock.

Refs #550

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Increments now replace entries whose `expires_at` is missing or no
date, which all other calls already treat as absent; before, they
failed with "busy" forever. Also share the counter bounds in one
helper, re-wrap a docstring, clarify tests and list the remaining
public names of `foca.plugins.store` in the API reference.

Refs #550

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

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Adds a configurable plugin-scoped key-value store exposed as ctx.store, with local memory and shared MongoDB backends, TTL-indexed persistence, atomic bounded counters, distribution namespaces, deadline-aware errors, harness support, startup integration, documentation, and comprehensive tests.

Sequence diagram for a shared plugin store request

sequenceDiagram
    participant Hook as Plugin hook
    participant Store as ctx.store
    participant Mongo as MongoStoreBackend
    participant DB as MongoDB plugin_store

    Hook->>Store: increment(key, by, ttl, limit)
    Store->>Mongo: increment(namespace, key, by, limit)
    Mongo->>DB: Conditional atomic update
    alt increment within bounds
        DB-->>Mongo: New counter value
        Mongo-->>Store: New counter value
        Store-->>Hook: New counter value
    else limit exceeded or lower bound reached
        DB-->>Mongo: No update
        Mongo-->>Store: None
        Store-->>Hook: None
    end
Loading

Entity relationship diagram for plugin store documents

erDiagram
    PLUGIN_STORE {
        string _id PK
        string ns INDEX
        string key
        string value
        integer n
        datetime expires_at TTL
    }

    PLUGIN_STORE }o--|| NAMESPACE : belongs_to
Loading

File-Level Changes

Change Details Files
Introduces the plugin store API, validation, expiration, pseudonymous key derivation, counter semantics, and store error handling.
  • Adds get/set/delete/increment/key_for with JSON size limits, TTL capping, fixed-window counters, atomic bounds, and defensive copying.
  • Defines shared store settings, modes, namespaces, and public exports.
  • Exposes stores through plugin contexts and test harnesses, including configurable deadlines and backends.
foca/plugins/store.py
foca/plugins/context.py
foca/plugins/__init__.py
foca/plugins/engine.py
foca/plugins/testing.py
Implements process-local and MongoDB-backed persistence with concurrency-safe increments and expiry management.
  • Adds a thread-safe memory backend with lazy expiry cleanup.
  • Adds the plugin_store MongoDB collection layout, TTL and namespace indexes, expiry filtering, timeout translation, and retry-bounded atomic increments.
  • Creates indexes during application startup when possible and lazily before writes when startup setup fails.
foca/plugins/store.py
foca/foca.py
Integrates store configuration and per-plugin storage behavior into plugin loading.
  • Adds default and per-plugin enabled, max_entry_size, and max_ttl configuration with validation and inheritance.
  • Selects the first configured database for shared storage, otherwise local memory; supports per-plugin off mode and warns when a distribution's plugins disagree.
  • Derives immutable namespaces from built-in identity or normalized distribution names.
foca/plugins/config.py
foca/plugins/engine.py
foca/foca.py
Documents the plugin store contract, operations, configuration, persistence model, privacy considerations, and testing support.
  • Adds usage examples and API semantics for values, counters, TTLs, namespaces, errors, and key pseudonymization.
  • Documents configuration models, collection/index requirements, storage modes, and harness access.
  • Publishes store classes and constants in the reference documentation.
docs/configuration/plugins.md
docs/plugins.md
docs/reference.md
Adds broad automated coverage for store semantics, integrations, backend behavior, configuration, and application startup.
  • Tests memory, mongomock, and real MongoDB behavior including expiry, atomic contention, limits, malformed entries, datetime options, timeouts, and index creation.
  • Tests harness/context integration, namespaces, configuration overrides, disabled stores, database selection, and startup failure handling.
tests/plugins/test_plugin_store.py

Assessment against linked issues

Issue Objective Addressed Explanation
#550 Expose ctx.store with get, set, delete, atomic increment, validated keys and I-JSON values, fixed-window TTL behavior, and calls bounded by the hook deadline with store failures surfaced as StoreError. ✅
#550 Implement the shared MongoDB backend and per-process in-memory fallback, including distribution-based namespaces, expiration handling, configurable per-plugin storage settings, and an in-memory testing store. ✅
#550 Document the plugin store and its configuration, including guidance for pseudonymizing principals used in keys. ✅

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

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #557    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           55        56     +1     
  Lines         6667      7008   +341     
==========================================
+ Hits          6667      7008   +341     
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 28, 2026 23:29

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

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

## Individual Comments

### Comment 1
<location path="foca/plugins/store.py" line_range="258" />
<code_context>
+            entry: Entry.
+            now: Current time.
+        """
+        self._entries[(ns, key)] = entry
+        self._writes += 1
+        if self._writes % self._SWEEP_INTERVAL == 0:
</code_context>
<issue_to_address>
**Distinct keys exhaust storage**

When a workload writes many distinct keys before their TTLs expire, `MemoryStoreBackend._write` and `MongoStoreBackend.set` accept new keys without an aggregate limit, so retained entries grow until process memory or database storage is exhausted and the gateway or database can fail.

Enforce an aggregate entry or byte quota for writes to both backends.

Also at `foca/plugins/store.py:492-499`.
</issue_to_address>

### Comment 2
<location path="foca/plugins/store.py" line_range="805" />
<code_context>
+        """
+        _check_key(key)
+        try:
+            dumped = json.dumps(
+                value, separators=(",", ":"), ensure_ascii=False, allow_nan=False
+            )
</code_context>
<issue_to_address>
**Oversized values exhaust resources**

When a plugin passes a very large value to `set()`, `Store.set` serializes and parses the entire value before checking `max_entry_size`, creating large temporary strings and objects; the work can exhaust memory or keep the hook worker occupied past its deadline before the value is rejected.

Enforce the size limit during serialization, before building or parsing the full value.
</issue_to_address>

### Comment 3
<location path="foca/plugins/store.py" line_range="205" />
<code_context>
+    Returns:
+        Error.
+    """
+    return StoreError(f"Key {key!r} holds a value that is no counter")
+
+
</code_context>
<issue_to_address>
**Personal keys enter logs**

When a caller can make a plugin increment a key containing personal data, and that key already holds a non-counter value, `_counter_conflict` embeds the raw key in `StoreError`; `PluginHost._call` logs the exception message through `describe_error`, which does not redact keys, so the operator’s logs disclose the key.

Omit the key from the conflict error, or redact/pseudonymize it before logging.
</issue_to_address>

### Comment 4
<location path="foca/foca.py" line_range="215" />
<code_context>
+            try:
+                # the indexes of the plugins' store; writes to the store
+                # create them too, so the app may start without them
+                host.setup_store()
+            except PyMongoError as exc:
+                logger.warning(
</code_context>
<issue_to_address>
**Database stall blocks app startup**

When mongoDB accepts the connection but stops responding to the index command, `create_app()` calls `host.setup_store()`, which calls `MongoStoreBackend.setup()` and waits for `create_index()` without a timeout; the app therefore remains stuck starting instead of logging the warning and continuing.

Bound startup index creation with a finite timeout so `create_app()` can reach its existing warning-and-continue path.

Also at `foca/plugins/store.py:428`.
</issue_to_address>

### Comment 5
<location path="foca/plugins/store.py" line_range="409" />
<code_context>
+        """
+        # time zone aware UTC times whatever the client's options (e.g.,
+        # `datetime_conversion` in `MONGO_URI`), as results depend on them
+        self.collection: Collection[dict[str, Any]] = collection.with_options(
+            codec_options=CodecOptions(
+                tz_aware=True,
</code_context>
<issue_to_address>
**Stale reads fail counter increments**

When the MongoDB URI selects secondary reads and a secondary has not caught up with a store write, `MongoStoreBackend.get` and the increment recovery `find_one` inherit the secondary read preference, so they can return stale entries; a saturated counter then exhausts its retries and raises `StoreError` instead of returning `None`.

Use primary reads for store lookups and increment recovery reads.

Also at `foca/plugins/store.py:458`, `foca/plugins/store.py:579`.
</issue_to_address>

### Comment 6
<location path="foca/plugins/store.py" line_range="352" />
<code_context>
+            Whether an entry that had not expired was deleted.
+        """
+        with self._lock:
+            entry = self._live(ns, key, now)
+            if entry is None:
+                return False
</code_context>
<issue_to_address>
**Expired calls still change counters**

When a memory-backend operation waits for a contended lock long enough for the hook deadline to pass, `Store._timeout()` runs before `MemoryStoreBackend.increment()` acquires its lock, and the memory backend does not bound lock acquisition or recheck the deadline. If the lock remains contended past the deadline, an abandoned hook can still increment its counter after timing out.

Bound lock acquisition by the remaining deadline and recheck it before performing the operation.
</issue_to_address>

### Comment 7
<location path="foca/plugins/engine.py" line_range="453" />
<code_context>
         self.plugins: dict[str, LoadedPlugin] = (
             dict(plugins) if plugins is not None else load_plugins(conf, api=api)
         )
+        self._store_backend: StoreBackend = store_backend or MemoryStoreBackend()
+        self._stores = _store_settings(self.plugins, conf, self._store_backend)
         self._executor = _Executor(conf.defaults.workers)
</code_context>
<issue_to_address>
**Supplied backend is replaced**

When a caller supplies a `StoreBackend` whose truth value is false or whose length is zero, `PluginHost.__init__` replaces the supplied backend with `MemoryStoreBackend`, so plugins write to process-local storage instead of the caller's backend and lose its sharing or persistence behavior.

Choose the default backend only when `store_backend is None`.
</issue_to_address>

### Comment 8
<location path="tests/plugins/test_plugin_store.py" line_range="518" />
<code_context>
+        """`get` trusts the query's filter; `delete` checks the deleted expiry."""
+        collection = MagicMock()
+        collection.with_options.return_value = collection
+        collection.find_one.return_value = {"_id": "x", "value": "1"}
+        collection.find_one_and_delete.return_value = {"_id": "x"}
+        store = make_store(MongoStoreBackend(collection), Clock())
</code_context>
<issue_to_address>
**Expiry filter regression goes undetected**

When `MongoStoreBackend.get` stops filtering out expired entries in its query, `test_unchecked_documents` still passes: the `MagicMock` returns the document regardless of the query, and the `store.get("k") == 1` assertion checks only its decoded value. Removing the expiry predicate therefore goes undetected.

Assert that the `find_one` query includes the expiry predicate, or use a collection fake that applies the query filter.
</issue_to_address>

### Comment 9
<location path="tests/plugins/test_plugin_store.py" line_range="622" />
<code_context>
+    def test_harness(self) -> None:
+        """Hooks get a store; the harness shares its entries with tests."""
+        harness = PluginHarness(CountingPlugin)
+        harness.run_request(make_inbound({}))
+        assert harness.executions[0].annotations == {
+            "count": 1,
</code_context>
<issue_to_address>
**Cross-host sharing goes untested**

When hosts report `mode == "shared"` but their backends do not share entries, `TestEngine.test_shared` creates one harness and makes one request, so its `shared` mode and initial count assertions pass even if another host cannot see that host’s entries. `TestFromConfig.test_host` likewise checks only the mode before closing each host, not whether their entries are shared.

Have one host write an entry and a second host using the same shared backend read or increment it, including a check of the `from_config` wiring.

Also at `tests/plugins/test_plugin_store.py:750`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 9 findings to address first, and the store persists plugin values and counters in MongoDB, and its TTL index deletes expired entries; if expiry or namespace isolation is wrong, state can be lost or read across plugin distributions. Reverting removes the feature but cannot restore deleted entries or undo data already exposed.

Blocking findings: foca/plugins/store.py:258, foca/plugins/store.py:805, foca/plugins/store.py:205, foca/foca.py:215, foca/plugins/store.py:409, and 4 more


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

Comment thread foca/plugins/store.py Resolved
Comment thread foca/plugins/store.py Resolved
Comment thread foca/plugins/store.py Resolved
Comment thread foca/foca.py Resolved
Comment thread foca/plugins/store.py Resolved
Comment thread foca/plugins/store.py Resolved
Comment thread foca/plugins/engine.py Resolved
Comment thread tests/plugins/test_plugin_store.py Resolved
Comment thread tests/plugins/test_plugin_store.py Resolved
uniqueg and others added 2 commits October 29, 2026 01:12
- Check the size of values before the slower I-JSON checks.
- Leave keys, which may be personal data, out of counter errors.
- Bound the index setup by 10 s, so that startup doesn't stall.
- Read entries from the primary, whatever the client's options.
- Wait for the memory backend's lock at most until the deadline.
- Keep falsy backends passed to `PluginHost`.
- Test the expiry filter of reads and sharing across hosts.

Refs #550

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 6aed732 into dev Oct 29, 2026
32 checks passed
@uniqueg
uniqueg deleted the feat/550-plugin-store branch October 29, 2026 00:29
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 plugin key-value store

1 participant