Skip to content

Stores

The three storage protocols you implement against your datastore; see Storage for why there are three and how to validate an implementation.

Protocols

approvo.stores.base.EventStore

Bases: Protocol

Append-only, hash-chained event log. The source of truth.

Implementation requirements:

  1. Appends MUST be atomic on (log_id, seq). Use a unique constraint, unique index, or conditional write — whatever your datastore offers natively. Do not emulate it with a read followed by a write; that races, and the race silently forks the chain. When the sequence number is already taken, raise :class:~approvo.errors.LedgerConflict; the service catches it and retries against the new head.
  2. Entries MUST NOT be mutable. Deny UPDATE and DELETE to the application's credentials. approvo detects tampering either way, but detection is a worse outcome than prevention.
  3. events_for_request MUST be indexed on (log_id, request_id, seq). It is on the hot path of every status read; a scan here makes approvo O(ledger) per request and it will not scale.
  4. Reads MUST return entries in seq order, and scan MUST stream rather than materialize — verification walks the whole log.
  5. Writes SHOULD be durable before returning. With an asynchronously-replicated store, a rolled-back append leaves a gap that verification will correctly report as tampering.

head async

head() -> LedgerEntry | None

Highest-seq entry, or None for an empty log.

append async

append(entry: LedgerEntry) -> None

Insert entry, atomically failing if its seq is taken.

Raises:

Type Description
~LedgerConflict

entry.seq already exists.

events_for_request async

events_for_request(request_id: str) -> list[LedgerEntry]

All events for one request, in seq order. Must be indexed.

scan

scan(start: int = 0, limit: int | None = None) -> AsyncIterator[LedgerEntry]

Stream entries from start in seq order.

Note this returns an async iterator directly rather than being an async def — implement it with async def + yield.

leaf_hashes async

leaf_hashes(up_to: int | None = None) -> list[str]

entry_hash values in seq order, for Merkle computation.

up_to is exclusive: pass a checkpoint's tree_size to get exactly the leaves that checkpoint committed to.

latest_checkpoint async

latest_checkpoint() -> Checkpoint | None

Most recent published checkpoint, or None.

approvo.stores.base.ProjectionStore

Bases: Protocol

Denormalized read model. Rebuildable; never authoritative.

Implementation requirements:

  1. upsert MUST NOT move a view backwards. Apply only when the incoming last_seq is greater than or equal to the stored one, so out-of-order or replayed projections cannot resurrect stale state. A conditional update is the usual mechanism.
  2. query SHOULD use keyset pagination, not offsets, and encode whatever it needs in the opaque next_cursor string.
  3. Filters in :class:~approvo.models.RequestQuery combine with AND. Unsupported filters SHOULD raise rather than be ignored — silently returning unfiltered rows to an approvals UI is a security problem, not a cosmetic one.

clear async

clear() -> None

Drop all views for this log. Called before a full rebuild.

approvo.stores.base.IdempotencyStore

Bases: Protocol

Reserve-then-complete coordination for retried mutations.

Implementation requirements:

  1. reserve MUST be atomic, returning won=True to exactly one concurrent caller — an insert-if-absent, conditional put, or equivalent.
  2. A key reused with a different fingerprint MUST raise :class:~approvo.errors.IdempotencyConflict. That is a caller bug (the same key meaning two different things), not a retry.
  3. Rows MAY be expired on a TTL. Choose a window comfortably longer than your clients' retry budget; expiring early turns a replay into a duplicate append attempt, which the ledger will accept as a genuine second decision.

reserve async

reserve(key: str, fingerprint: str) -> Reservation

Atomically claim key for this caller.

complete async

complete(key: str, response: dict) -> None

Record the winner's result so later retries can replay it.

release async

release(key: str) -> None

Drop a reservation whose work failed, so a retry can proceed.

approvo.stores.base.Reservation dataclass

Result of :meth:IdempotencyStore.reserve.

won is True for the single caller that acquired the slot and must do the work. Everyone else gets won=False plus, once the winner has called :meth:IdempotencyStore.complete, the stored response.

approvo.stores.base.NullProjectionStore

No-op projections, for callers that only ever read by id.

Perfectly reasonable: projections exist to power list screens. If your BFF only ever fetches one request at a time, skip them entirely and save yourself a table.

Conformance suite

approvo.testing

Conformance suite for store implementations.

approvo ships no database adapters, so this module is how you find out whether yours is correct. Every MUST in :mod:approvo.stores.base has a test here. If these pass against your store, approvo's tamper-evidence and idempotency guarantees hold on your datastore.

Subclass the suite and supply a fixture yielding a fresh, empty store::

import pytest
from approvo.testing import EventStoreConformance

class TestMyEventStore(EventStoreConformance):
    @pytest.fixture
    async def event_store(self):
        store = MyEventStore(pool, log_id="test")
        await store.truncate()          # your own reset helper
        yield store

Then just run pytest. The suites are EventStoreConformance, ProjectionStoreConformance, IdempotencyStoreConformance, and KeyProviderConformance (for KMS/HSM signing back ends).

Requires pytest and pytest-asyncio (pip install 'approvo[dev]'). Tests are explicitly marked @pytest.mark.asyncio, so they work whether or not your project sets asyncio_mode = "auto".

The concurrency tests here exercise real parallelism only if your store talks to a real datastore over a pool. They will pass trivially against a single-connection or in-process store — that is expected, and it is why you should run this against the thing you actually deploy.

EventStoreConformance

Subclass and provide an event_store fixture yielding an empty store.

test_concurrent_appends_yield_exactly_one_winner async

test_concurrent_appends_yield_exactly_one_winner(event_store)

The core anti-fork guarantee: N writers, same seq, one survivor.

ProjectionStoreConformance

Subclass and provide a projection_store fixture yielding an empty store.

IdempotencyStoreConformance

Subclass and provide an idempotency_store fixture yielding an empty store.