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:
- 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. - 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.
events_for_requestMUST 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.- Reads MUST return entries in
seqorder, andscanMUST stream rather than materialize — verification walks the whole log. - 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.
append
async
¶
Insert entry, atomically failing if its seq is taken.
Raises:
| Type | Description |
|---|---|
~LedgerConflict
|
|
events_for_request
async
¶
All events for one request, in seq order. Must be indexed.
scan ¶
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
¶
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
¶
Most recent published checkpoint, or None.
approvo.stores.base.ProjectionStore ¶
Bases: Protocol
Denormalized read model. Rebuildable; never authoritative.
Implementation requirements:
upsertMUST NOT move a view backwards. Apply only when the incominglast_seqis 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.querySHOULD use keyset pagination, not offsets, and encode whatever it needs in the opaquenext_cursorstring.- Filters in :class:
~approvo.models.RequestQuerycombine 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.
approvo.stores.base.IdempotencyStore ¶
Bases: Protocol
Reserve-then-complete coordination for retried mutations.
Implementation requirements:
reserveMUST be atomic, returningwon=Trueto exactly one concurrent caller — an insert-if-absent, conditional put, or equivalent.- 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. - 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.
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
¶
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.