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). Withsync=True(the default) the write also updates the index, so this instance’s reads see it at once. Withsync=Falsethe index advances only whencatch_up()runs, which the caller schedules (no worker ships). Until then an UNTOKENEDcheck/lookupreads the index as it is and can be stale in both directions, a revoked grant still reading as allowed included. Only acheckgivenat_least=tokenfalls back to the set engine when the index is behind the token; a tokened lookup raisesLookupNotFreshinstead.syncis per instance and is not stored.watermark()andlag()are methods, not properties, because each runs a query (lag()a COUNT).Give the store a
Sessionof its own: it commits on open and on every write, and rolls back on a refused write and inrefresh().The constructor opens an existing store, or creates one when
schemais given. Every argument, with its type, default and meaning, is listed under “Store arguments” on the Configuration page. In brief:schemais OpenFGA DSL text, or an OpenFGA JSON model as adictor 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 compiledRuleSetis not accepted. The schema is saved once; reopening with a schema that parses differently raisesSchemaMismatch, 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. Withsync=Falsewrites reach the tuple log only, and the index advances whencatch_up()runs.paranoiaselects the runtime check level:'off'/False/0,'residue','full'/True/1, or'fixpoint'. Any other value raisesValueError. An explicit argument wins over theZANZIBAR_PARANOIAenvironment variable, which wins overDEFAULT_PARANOIA. A failed check raisesInvariantViolationbefore 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
paranoiaargument nor theZANZIBAR_PARANOIAenvironment variable is set.
- 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
syncargument:Truewhen every write also updates the graph index,Falsewhen the index advances only incatch_up(). It belongs to this instance and is not saved with the store.
The attributes
widx,ruleset,source,proc,cursorandparanoia_guardare 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
RelationTuplerows were written without the tuple log (by a standaloneSetEngine) cannot simply be opened as aStore: the open raisesUnloggedTuplesPresent. This runs the adoption recipe instead: save the schema (whenschemais given), build the graph index from the stored tuples withbuild_index, then open theStore.reportis theBuildReportbuild_indexreturned;storeis the openStore.save_schemaandbuild_indexstay public for callers that want the steps one by one.schematakes whatStore(schema=...)takes (DSL text, or an OpenFGA JSON model). Leave it out when the store already has a persisted schema; a store with neither raisesStoreNotFound. A schema that differs from the persisted one raisesSchemaMismatch.object_wildcard_shapesis saved withschemaand is used only together with it: withschema=Nonethe persisted shapes apply and this argument is ignored, as inStore(session, id).bulkisbuild_index’s;ops,syncandparanoiaare theStoreconstructor’s.The schema and the index commit TOGETHER. Each refusal below commits nothing: a bad
paranoia(ValueError) orops(TypeError), an id that already has an index (IndexExists; open it withStore(session, id)), writes to the store while the index is built (aRuntimeError; 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 inobject_wildcard_shapes(ValueErrorwithbulk=True,AdmissionRejectedwithbulk=False). The argument, table and isolation checks run before anything is built. The session must be clean (no pending ORM changes).
- 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), wheresubject_predicateis"..."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 raisesAdmissionRejectedand 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.
batchisNone(no cap) or anint >= 1; anything else raisesValueError/TypeErrorbefore the log is read.
- 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 arefresh().- Return type:
- 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")orcheck("...", "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") raisesUndeclaredTypeOrRelationbefore anything is read; an unknown NAME ("doc:999") is not refused and answersFalse. A token another store’s write returned raisesForeignTokenon 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") orlookup("...", "user", "alice").object_type/relationkeep 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 withUndeclaredTypeOrRelation, as incheck; an unknown object NAME matches nothing.at_leastdemands the index reflect the log through that token. It is ENFORCED, not fulfilled by fallback: satisfied demands are served normally, unsatisfiable ones raiseLookupNotFresh(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")orlookup_reverse("viewer", "doc", "d1").at_leastbehaves exactly as inlookup– enforced, never silently downgraded.subject_type/subject_predicatekeep 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), andsubject_predicate="member"keepsmemberusersets. A type or relation the schema does not declare is refused withUndeclaredTypeOrRelation, as incheck.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 eachusermarker minusexcluded_keys. A userset key such asgroup:eng#membermeans the userset itself is allowed; never expand it to its members, which would re-admit a member abut notrefuses.
- 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")orexpand("viewer", "doc", "d1"). Returns anExpandResultof(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,StaleReadis raised – callrefresh()and retry.
- result_keys(res)¶
Translate
res.node_ids(from this store’slookup/lookup_reverse) to(type, name, predicate)keys,predicatebeing the relation or"..."for a bare subject:{("doc", "d1", "viewer"), ("group", "eng", "member")}.The key FORMAT is the one
SetEngine.result_keysuses, 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) andexcluded_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(aKeyError).
- excluded_keys(res)¶
Translate
res.excluded_node_idsto(type, name, predicate)keys: the portable form of “every subject of a marker’s shape EXCEPT these”. The companion ofresult_keys; a caller expandingres.markersmust subtract these.
- class zanzibar.ExpandResult(keys=frozenset({}), markers=frozenset({}), excluded_keys=frozenset({}))¶
What
Store.expandreturns: every subject that has the relation on the object, as portable(type, name, predicate)keys (predicateis 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 (abut notor anandunder a wildcard grant). Always subtract them from a marker.
A subject a marker covers is usually NOT repeated in
keys, sokeysalone is not the member list. Usekey in result(covers) for one subject. Underdefine viewer: [user:*] but not bannedwith auser:*grant anduser:mallorybanned,keysis empty,markersis{("user", "...")}andexcluded_keysis{("user", "mallory", "...")}.A userset key such as
("group", "eng", "member")means the userset itself is a member; its own members are already included (listed inkeysor covered by a marker), so never expand it again yourself, which would re-admit a member abut notrefuses.markersare(type, predicate)PAIRS, e.g.("user", "...")or("group", "member")for a[group:*#member]grant.LookupResult.markers(fromlookup_reverse) are(type, predicate, "any")TRIPLES for the same grant, so compare across the two by the first two fields.
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 storestore_id, which must already have a saved schema (StoreNotFoundotherwise).opsselects the set representation, as forStore.rulesetis aRuleSetalready compiled from the store’s schema, to skip compiling it again. The session’s isolation level is checked as for aStore(UnsafeIsolationLevel).- property engine: zanzibar.setengine.SetEngine¶
The in-memory set engine, for reads. It cannot be replaced, and writing to it directly raises
UnloggedWriteRefused: write throughadd()andremove().
- watermark() int¶
The newest freshness token in this store’s tuple log, as this session sees it (
0for 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.
batchcaps the rows read per query (Nonereads them in one query). It reads what this session’s snapshot shows, so a long-lived session mustrollback()first to see newer commits. After rolling back a write of your own, callrefresh_evaluator()instead. A row that does not fit the engine’s state raisesRuntimeError; recover withrefresh_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")(OpenFGAuser, relation, object) oradd("...", "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. RaisesAdmissionRejected(aValueError; 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 onStore.check).at_least(Noneor a non-negativeinttoken) demands the set engine reflect the log through that token first (catch up O(delta) on demand;StaleReadif the token is not visible in this session’s snapshot – rollback/refresh and retry).
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_iddefaults tosource_store_id, the index aStoreon that id serves. RaisesIndexExistsif that index already has state; userebuild_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=Falsereplays 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 async=Falseinstance works while the index is stalled; async=Trueinstance refuses every write, that removal included, withPathCountExceeded); a snapshot that still cannot be built is refused exactly asbuild_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 nextrefresh(). 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”, asbuild_index()does. Returns aBuildReport.
- class zanzibar.store.BuildReport¶
What
build_index()returns: a named tuple(cursor, widx, ruleset), socursor, 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.
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
Storejudges it on reopen (the same parsed schema and the sameobject_wildcard_shapes); a different one raisesSchemaMismatch, naming the first difference. Returns a tuple(record, ruleset): theSchemaRecordrow and the compiledRuleSet. 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
SetEngineon a store that aStorecreated, using the schema saved in the database, so you cannot pass a different one by mistake. This is the remedy theSchemaMismatchfromSetEngine(session, store_id, schema)names. RaisesStoreNotFoundwhen no schema is saved understore_id, andPersistedSchemaRefusedwhen this release refuses the saved schema.rulesetskips 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_recordtable: 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_logtable: one accepted write. A row’sidis 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
Storeconstructor’sparanoiaargument is not given; an explicit argument always wins, and an empty value counts as unset. It accepts a level name,off,residue,fullorfixpoint(case-insensitive), or a boolean word:1,true,yesandonmeanfull;0,false,noandoffmeanoff. Any other value raisesValueError. 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.