zanzibar.store

The composed store. An append-only tuple log is the source of truth, a graph index is kept up to date from it, and a set engine stands beside the index to answer reads the index cannot serve yet. zanzibar.Store is the class most programs use.

Store

Store and ExpandResult are importable from both zanzibar and zanzibar.store; they are documented here under their top-level names.

class zanzibar.Store(session, store_id, *, schema=None, object_wildcard_shapes=frozenset({}), ops=SetOps('roaring'), sync=True, paranoia=None)

One permission store, end to end: validated writes into the tuple log, a graph index maintained from that log, and index-served reads.

Every write commits and returns a freshness token (an int, the write’s log id). With sync=True (the default) the write also updates the index, so this instance’s reads see it at once. With sync=False the index advances only when catch_up() runs, which the caller schedules (no worker ships). Until then an UNTOKENED check / lookup reads the index as it is and can be stale in both directions, a revoked grant still reading as allowed included. Only a check given at_least=token falls back to the set engine when the index is behind the token; a tokened lookup raises LookupNotFresh instead. sync is per instance and is not stored.

watermark() and lag() are methods, not properties, because each runs a query (lag() a COUNT).

Give the store a Session of its own: it commits on open and on every write, and rolls back on a refused write and in refresh().

The constructor opens an existing store, or creates one when schema is given. Every argument, with its type, default and meaning, is listed under “Store arguments” on the Configuration page. In brief:

  • schema is OpenFGA DSL text, or an OpenFGA JSON model as a dict or a JSON string (also wrapped as {"authorization_model": {...}}). JSON is converted to DSL before it is saved, so the saved schema is always DSL. A compiled RuleSet is not accepted. The schema is saved once; reopening with a schema that parses differently raises SchemaMismatch, while the same schema re-indented, with CRLF line endings, comments or reordered type blocks is accepted.

  • sync=True (the default) updates the graph index inside every write. With sync=False writes reach the tuple log only, and the index advances when catch_up() runs.

  • paranoia selects the runtime check level: 'off' / False / 0, 'residue', 'full' / True / 1, or 'fixpoint'. Any other value raises ValueError. An explicit argument wins over the ZANZIBAR_PARANOIA environment variable, which wins over DEFAULT_PARANOIA. A failed check raises InvariantViolation before the write’s commit, so the write is not committed; the message names the store id, the commit phase and the violated invariant. The levels and their costs are in the table of levels on the Configuration page.

Parameters:
DEFAULT_PARANOIA: str = 'off'

The check level used when neither the paranoia argument nor the ZANZIBAR_PARANOIA environment variable is set.

store_id: str

The store id this store was opened on, as passed to the constructor.

session: sqlmodel.Session

The session passed to the constructor. The store commits on it on open and on every write, and rolls it back on a refused write and in refresh(), so give the store a session of its own.

sync: bool

The sync argument: True when every write also updates the graph index, False when the index advances only in catch_up(). It belongs to this instance and is not saved with the store.

paranoia: str

The check level this store ended up with: 'off', 'residue', 'full' or 'fixpoint'.

The attributes widx, ruleset, source, proc, cursor and paranoia_guard are internal plumbing, not API: they may change without notice.

classmethod adopt(session, store_id, *, schema=None, object_wildcard_shapes=frozenset({}), bulk=True, ops=SetOps('roaring'), sync=True, paranoia=None)

Adopt an existing tuple store in one call; returns (store, report).

A store id whose RelationTuple rows were written without the tuple log (by a standalone SetEngine) cannot simply be opened as a Store: the open raises UnloggedTuplesPresent. This runs the adoption recipe instead: save the schema (when schema is given), build the graph index from the stored tuples with build_index, then open the Store. report is the BuildReport build_index returned; store is the open Store. save_schema and build_index stay public for callers that want the steps one by one.

schema takes what Store(schema=...) takes (DSL text, or an OpenFGA JSON model). Leave it out when the store already has a persisted schema; a store with neither raises StoreNotFound. A schema that differs from the persisted one raises SchemaMismatch. object_wildcard_shapes is saved with schema and is used only together with it: with schema=None the persisted shapes apply and this argument is ignored, as in Store(session, id). bulk is build_index’s; ops, sync and paranoia are the Store constructor’s.

The schema and the index commit TOGETHER. Each refusal below commits nothing: a bad paranoia (ValueError) or ops (TypeError), an id that already has an index (IndexExists; open it with Store(session, id)), writes to the store while the index is built (a RuntimeError; retry when it is quiescent), an isolation level other than READ COMMITTED (UnsafeIsolationLevel), an outdated SQLite database (TablesOutdated), missing tables (TablesNotCreated), and a stored object-wildcard tuple (doc:*) whose shape is not declared in object_wildcard_shapes (ValueError with bulk=True, AdmissionRejected with bulk=False). The argument, table and isolation checks run before anything is built. The session must be clean (no pending ORM changes).

Parameters:
Return type:

tuple[Store, BuildReport]

add_tuple(user: str, relation: str, object: str) → int
add_tuple(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str) → int

Add one tuple and commit; returns its freshness token (a log id).

Two call forms, positional or by keyword:

  • the OpenFGA form add_tuple(user, relation, object): add_tuple("user:alice", "viewer", "doc:d1"), a userset as "group:eng#member", every user as "user:*";

  • six parts add_tuple(subject_predicate, subject_type, subject_name, relation, object_type, object_name), where subject_predicate is "..." for a bare subject: add_tuple("...", "user", "alice", "viewer", "doc", "d1").

Adding a tuple that is already stored is a no-op that returns the current watermark. A refused write raises AdmissionRejected (or a subclass) and changes nothing.

remove_tuple(user: str, relation: str, object: str) → int
remove_tuple(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str) → int

Remove one stored tuple and commit; returns its freshness token (a log id). Takes the same two call forms as add_tuple. Removing a tuple that is not stored raises AdmissionRejected and changes nothing.

catch_up(batch=None)

Advance the index over the log until it reaches the head; one transaction per batch (exactly-once: applied rows + cursor commit together, so a failed batch moves nothing and a retry re-reads the same rows). Returns the number of log rows applied. This IS the async worker’s body – a daemon would just call it on a schedule.

The closure fan-out cap is SUSPENDED here: every row is already committed truth, so the cap could only stall the index behind it, never refuse the write. An over-cap row is applied with a warning instead. The cap stays in force on the sync path, where its refusal reaches the writer.

batch is None (no cap) or an int >= 1; anything else raises ValueError / TypeError before the log is read.

Parameters:

batch (int | None)

Return type:

int

property index_stalled: bool

True while the last recorded apply failure is still at the cursor, i.e. the index is not merely behind but has failed to advance. As fresh as this session’s view of the cursor row – a replica reader sees a stall recorded by another instance after its next refresh(), the same window it already accepts for every other write.

property stall_error: str | None

The recorded failure behind a live stall, for operators; None otherwise.

refresh()

Replica-reader poll: drop the current read snapshot and every read-path cache, so the next queries see the latest committed state coherently (fresh transaction + rebuilt set engine; the graph read path is uncached by design). Refused on a session with pending ORM changes, which the rollback would silently discard.

Return type:

None

lag()

Log rows the index has not yet applied (0 = fully caught up). A COUNT query – never materializes rows (ids are globally monotonic across stores, so counting, not id-subtraction, is also what makes the number meaningful). Counted against the cursor row as committed, so another instance’s catch_up() shows up without a refresh().

Return type:

int

check(user: str, relation: str, object: str, *, at_least: int | None = None) → bool
check(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str, *, at_least: int | None = None) → bool

Is the user related to the object? Same two call forms as add_tuple: check("user:alice", "viewer", "doc:d1") or check("...", "user", "alice", "viewer", "doc", "d1").

at_least (a token from a write) demands an answer that reflects the log through that write; a lagging index then falls back to the set engine.

A type, relation or subject relation the schema does not declare ("vewer", "group:eng#nosuch") raises UndeclaredTypeOrRelation before anything is read; an unknown NAME ("doc:999") is not refused and answers False. A token another store’s write returned raises ForeignToken on every tokened read (check, lookup, lookup_reverse, expand).

lookup(user: str, *, at_least: int | None = None, object_type: str | None = None, relation: str | None = None) → LookupResult
lookup(subject_predicate: str, subject_type: str, subject_name: str, *, at_least: int | None = None, object_type: str | None = None, relation: str | None = None) → LookupResult

List-objects: everything the subject can reach, served by the index.

The subject is lookup("user:alice") (or "group:eng#member") or lookup("...", "user", "alice").

object_type / relation keep only the objects of that type and/or relation (“the documents alice can view”: lookup("user:alice", object_type="doc", relation="viewer")), markers and exclusions included. A type or relation the schema does not declare is refused with UndeclaredTypeOrRelation, as in check; an unknown object NAME matches nothing.

at_least demands the index reflect the log through that token. It is ENFORCED, not fulfilled by fallback: satisfied demands are served normally, unsatisfiable ones raise LookupNotFresh (see there – and note this is the revocation surface, where quietly returning the pre-revocation enumeration is the failure that matters). Omitting the token keeps the previous behaviour exactly: an untokened, bounded-stale index read.

lookup_reverse(relation: str, object: str, *, at_least: int | None = None, subject_type: str | None = None, subject_predicate: str | None = None) → LookupResult
lookup_reverse(relation: str, object_type: str, object_name: str, *, at_least: int | None = None, subject_type: str | None = None, subject_predicate: str | None = None) → LookupResult

List-users: everything that can reach the object’s relation, as lookup_reverse("viewer", "doc:d1") or lookup_reverse("viewer", "doc", "d1"). at_least behaves exactly as in lookup – enforced, never silently downgraded.

subject_type / subject_predicate keep only the subjects of that type and/or predicate, markers and exclusions included: subject_type="user", subject_predicate="..." keeps the users ("..." is a bare subject), and subject_predicate="member" keeps member usersets. A type or relation the schema does not declare is refused with UndeclaredTypeOrRelation, as in check.

To list the USERS allowed, take the keys of type user (a granted group’s members are already listed one by one, refused ones left out) plus each user marker minus excluded_keys. A userset key such as group:eng#member means the userset itself is allowed; never expand it to its members, which would re-admit a member a but not refuses.

expand(relation: str, object: str, *, at_least: int | None = None) → ExpandResult
expand(relation: str, object_type: str, object_name: str, *, at_least: int | None = None) → ExpandResult

Zanzibar Expand: every subject that has the relation on the object, as expand("viewer", "doc:d1") or expand("viewer", "doc", "d1"). Returns an ExpandResult of (type, name, predicate) keys, wildcard markers and the keys those markers exclude (see there for how to read the three together).

Served by the set engine, never the index, so a stalled index does not affect it. The engine first reads every write this session can see (including other instances’), so an untokened call is as fresh as this session’s snapshot. at_least (a token from a write) demands the answer reflect the log through that write; if this session’s snapshot does not contain it yet, StaleRead is raised – call refresh() and retry.

result_keys(res)

Translate res.node_ids (from this store’s lookup / lookup_reverse) to (type, name, predicate) keys, predicate being the relation or "..." for a bare subject: {("doc", "d1", "viewer"), ("group", "eng", "member")}.

The key FORMAT is the one SetEngine.result_keys uses, but the key SET may differ: a subject that a marker already covers may be listed here too (the set engine leaves it out), so compare two results by what they cover – the keys, plus every subject of a marker’s shape, minus the excluded keys – never by equality of key sets. This is the CONCRETE part of the result only: res.markers (wildcard grants) and excluded_keys(res) (the subjects a marker covers but which are refused) complete it, and a marker read without its exclusions over-grants.

Read a result before the next write: ids are database row ids, which are never reused; an id whose node a later write removed raises StaleLookupIds (a KeyError).

Parameters:

res (LookupResult)

Return type:

set[tuple[str, str, str]]

excluded_keys(res)

Translate res.excluded_node_ids to (type, name, predicate) keys: the portable form of “every subject of a marker’s shape EXCEPT these”. The companion of result_keys; a caller expanding res.markers must subtract these.

Parameters:

res (LookupResult)

Return type:

set[tuple[str, str, str]]

watermark()

The newest freshness token in this store’s tuple log (0 for an empty log): the token of the latest write by any instance, as far as this session can see. Pass it as at_least to read through everything written so far.

Return type:

int

class zanzibar.ExpandResult(keys=frozenset({}), markers=frozenset({}), excluded_keys=frozenset({}))

What Store.expand returns: every subject that has the relation on the object, as portable (type, name, predicate) keys (predicate is the relation, or "..." for a bare subject such as ("user", "alice", "...")).

Three parts, read together:

  • keys – members listed one by one;

  • markers – (type, predicate) shapes granted through a wildcard: EVERY subject of that shape is a member, including ones no tuple mentions;

  • excluded_keys – subjects a marker covers that are NOT members (a but not or an and under a wildcard grant). Always subtract them from a marker.

A subject a marker covers is usually NOT repeated in keys, so keys alone is not the member list. Use key in result (covers) for one subject. Under define viewer: [user:*] but not banned with a user:* grant and user:mallory banned, keys is empty, markers is {("user", "...")} and excluded_keys is {("user", "mallory", "...")}.

A userset key such as ("group", "eng", "member") means the userset itself is a member; its own members are already included (listed in keys or covered by a marker), so never expand it again yourself, which would re-admit a member a but not refuses.

markers are (type, predicate) PAIRS, e.g. ("user", "...") or ("group", "member") for a [group:*#member] grant. LookupResult.markers (from lookup_reverse) are (type, predicate, "any") TRIPLES for the same grant, so compare across the two by the first two fields.

Parameters:
keys: frozenset[tuple[str, str, str]]

Members listed one by one, as (type, name, predicate) keys.

markers: frozenset[tuple[str, str]]

(type, predicate) shapes granted through a wildcard.

excluded_keys: frozenset[tuple[str, str, str]]

Keys a marker covers that are not members.

covers(key)

Is the (type, name, predicate) subject a member? Listed in keys, or covered by a marker of its (type, predicate) shape and not excluded.

Parameters:

key (tuple[str, str, str])

Return type:

bool

Writing through the log without a Store

TupleSource is the write half of a Store on its own: it validates each write against the schema, appends it to the tuple log and keeps an in-memory set engine current. It does not maintain a graph index.

class zanzibar.store.TupleSource(session, store_id, *, ops=SetOps('roaring'), ruleset=None)

Source-of-truth writes for one tuple store (the Zanzibar half).

TupleSource(session, store_id, *, ops=RoaringSets, ruleset=None) opens the store store_id, which must already have a saved schema (StoreNotFound otherwise). ops selects the set representation, as for Store. ruleset is a RuleSet already compiled from the store’s schema, to skip compiling it again. The session’s isolation level is checked as for a Store (UnsafeIsolationLevel).

Parameters:
  • session (Session)

  • store_id (str)

  • ops (SetOps)

property engine: zanzibar.setengine.SetEngine

The in-memory set engine, for reads. It cannot be replaced, and writing to it directly raises UnloggedWriteRefused: write through add() and remove().

watermark() → int

The newest freshness token in this store’s tuple log, as this session sees it (0 for an empty log).

catch_up_evaluator(batch=None) → int

Apply the committed log rows the set engine has not seen yet, and return how many were applied. batch caps the rows read per query (None reads them in one query). It reads what this session’s snapshot shows, so a long-lived session must rollback() first to see newer commits. After rolling back a write of your own, call refresh_evaluator() instead. A row that does not fit the engine’s state raises RuntimeError; recover with refresh_evaluator().

refresh_evaluator() → None

Rebuild the in-memory set engine from the stored tuples and reset its watermark to match. Costs time proportional to the store’s size, where catch_up_evaluator() costs time proportional to the new rows.

add(user: str, relation: str, object: str) → int
add(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str) → int

Add a raw tuple; returns the freshness token (log id).

Two call forms, as on Store.add_tuple: add("user:alice", "viewer", "doc:d1") (OpenFGA user, relation, object) or add("...", "user", "alice", "viewer", "doc", "d1") (subject_predicate, subject_type, subject_name, relation, object_type, object_name).

Idempotent on duplicates (raw tuples are a set): no state change, no log row, current watermark returned.

remove(user: str, relation: str, object: str) → int
remove(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str) → int

Remove a raw tuple; returns the freshness token (log id). Same two call forms as add. Raises AdmissionRejected (a ValueError; logs nothing) if the tuple is not present.

check(user: str, relation: str, object: str, *, at_least: int | None = None) → bool
check(subject_predicate: str, subject_type: str, subject_name: str, relation: str, object_type: str, object_name: str, *, at_least: int | None = None) → bool

Evaluate a check against the set engine, in either call form (check("user:alice", "viewer", "doc:d1") or six parts, as on Store.check). at_least (None or a non-negative int token) demands the set engine reflect the log through that token first (catch up O(delta) on demand; StaleRead if the token is not visible in this session’s snapshot – rollback/refresh and retry).

evaluator_lag()

Log rows the set engine has not yet applied (0 = fully caught up). A COUNT query – never materializes rows (ids are globally monotonic across stores, so counting, not id-subtraction, is also what makes the number meaningful).

Return type:

int

Building and rebuilding the index offline

zanzibar.store.build_index(session, source_store_id, *, index_store_id=None, bulk=True) → BuildReport

Build a fresh graph index from the store’s current tuples, in one transaction (committed on success, rolled back on failure). index_store_id defaults to source_store_id, the index a Store on that id serves. Raises IndexExists if that index already has state; use rebuild_index() to replace one in place.

bulk=True (the default) builds the index state in one in-memory pass and writes it with bulk inserts. bulk=False replays the tuples one at a time through the incremental write path. The resulting index is the same either way.

Returns a BuildReport.

zanzibar.store.rebuild_index(session, source_store_id, *, index_store_id=None, bulk=True) → BuildReport

Throw away an existing graph index and build it again, in place, from the store’s current tuples. This is the recovery for an index that zanzibar.Store.catch_up() cannot advance because a logged write is refused by the index for good (PathCountExceeded). Remove the offending tuple first (zanzibar.Store.remove_tuple() through a sync=False instance works while the index is stalled; a sync=True instance refuses every write, that removal included, with PathCountExceeded); a snapshot that still cannot be built is refused exactly as build_index() refuses it.

It runs in one transaction under the graph index’s write lock: it deletes the index’s state, runs the same build as build_index(), and moves the existing cursor row to the new position, clearing its stall marker. Other instances see the rebuilt index after their next refresh(). The delta outbox is left alone. On any failure nothing changes: the old index and its stall marker remain. Stop the store’s async worker first; a write committed during the rebuild makes it refuse with “concurrent writes”, as build_index() does. Returns a BuildReport.

class zanzibar.store.BuildReport

What build_index() returns: a named tuple (cursor, widx, ruleset), so cursor, widx, ruleset = build_index(...) works, plus one extra attribute.

cursor

The index’s cursor row, at the log position the build read up to.

widx: zanzibar.graphindex.WildcardIndex

The built graph index.

ruleset: zanzibar.schema.RuleSet

The compiled schema.

constructor: str

Which build ran: 'bulk' or 'incremental'.

The schema record and the tuple log

zanzibar.store.save_schema(session, store_id, schema_text, object_wildcard_shapes=frozenset())

Save a store’s schema (DSL text) and object-wildcard shapes, once. The schema is compiled first, so an invalid one is refused before anything is written. Saving the schema the store already has is a no-op, judged as a Store judges it on reopen (the same parsed schema and the same object_wildcard_shapes); a different one raises SchemaMismatch, naming the first difference. Returns a tuple (record, ruleset): the SchemaRecord row and the compiled RuleSet. It flushes the new row but does not commit; the caller commits the session.

zanzibar.store.open_set_engine(session, store_id, *, ops=DEFAULT_SETOPS, ruleset=None)

Open a standalone SetEngine on a store that a Store created, using the schema saved in the database, so you cannot pass a different one by mistake. This is the remedy the SchemaMismatch from SetEngine(session, store_id, schema) names. Raises StoreNotFound when no schema is saved under store_id, and PersistedSchemaRefused when this release refuses the saved schema. ruleset skips recompiling a schema you already compiled; it must be that schema’s. Public since 0.1.0.

class zanzibar.store.SchemaRecord

A row of the zanzibar_schema_record table: one per store, holding its schema as DSL text and its object-wildcard shapes. Written once, never changed. Columns: store_id, schema_text, object_wildcard_shapes, created_at. See the Database tables page.

class zanzibar.store.TupleLog

A row of the zanzibar_tuple_log table: one accepted write. A row’s id is the freshness token that write returned. Columns: id, store_id, op, subject_predicate, subject_type, subject_name, relation, object_type, object_name, created_at. See the Database tables page.

Constants

zanzibar.store.PARANOIA_ENV_VAR: str = 'ZANZIBAR_PARANOIA'

The name of the environment variable that sets the runtime-check (paranoia) level when the Store constructor’s paranoia argument is not given; an explicit argument always wins, and an empty value counts as unset. It accepts a level name, off, residue, full or fixpoint (case-insensitive), or a boolean word: 1, true, yes and on mean full; 0, false, no and off mean off. Any other value raises ValueError. The knob is described on the Configuration page.

Exceptions

zanzibar.store exports no exceptions. Import them from zanzibar; they are documented on the Exceptions page. A tokened read on a Store (check, lookup, lookup_reverse, expand with at_least=) can raise StaleRead, LookupNotFresh or ForeignToken.