Handle errors¶
Almost every exception the library raises on purpose derives from
zanzibar.ZanzibarError, and every one of them can be imported from the top level
(from zanzibar import ...), which is their one public home. Every one also keeps a
builtin base class (ValueError, KeyError or RuntimeError), so existing
except ValueError: code keeps working. A few
deliberate errors are not ZanzibarErrors at all; they are listed under
What except ZanzibarError does not catch.
This page groups the exceptions into four kinds by what you should do about them, and names the ones you are most likely to meet. The exceptions reference lists every class, with when it is raised, its base classes and its attributes.
Catch everything the library refuses¶
The examples on this page use this store:
from pathlib import Path
from sqlmodel import SQLModel, Session, create_engine
from zanzibar import Store, ZanzibarError
SCHEMA = """
model
schema 1.1
type user
type doc
relations
define viewer: [user]
"""
for leftover in ("errors.db", "empty.db"): # start from empty files each run
Path(leftover).unlink(missing_ok=True)
engine = create_engine("sqlite:///errors.db")
SQLModel.metadata.create_all(engine)
store = Store(Session(engine), "my-app", schema=SCHEMA)
except ZanzibarError catches every refusal, limit and freshness error. A refused write
changes nothing, and the store stays usable afterwards:
try:
store.add_tuple("user:alice", "editor", "doc:1") # doc declares no "editor"
except ZanzibarError as error:
print(type(error).__name__) # -> 'AdmissionRejected'
store.add_tuple("user:alice", "viewer", "doc:1")
print(store.check("user:alice", "viewer", "doc:1")) # -> True
Some exceptions derive from others, so when you catch several, put the more specific one
first. For example, zanzibar.ClosureFanoutExceeded is also an
zanzibar.AdmissionRejected, and zanzibar.IndexStalled is also a
zanzibar.LookupNotFresh and a zanzibar.StaleRead. The
hierarchy shows them all.
Bad input: fix the request, do not retry¶
These mean the request itself is wrong. Retrying it gives the same answer. In a web service, they usually become a 400-style response, or a bug in the code that built the request.
zanzibar.AdmissionRejected: a write was refused, for example because the tuple names a relation the schema does not declare, would create a cycle, or removes a tuple that is not stored.zanzibar.UndeclaredTypeOrRelation: a read named a type or relation the schema does not declare, often a typo.zanzibar.MalformedTupleString: a"type:name"or"type:name#relation"argument does not have that shape.
from zanzibar import AdmissionRejected, MalformedTupleString
try:
store.add_tuple("alice", "viewer", "doc:1") # missing the "user:" part
except MalformedTupleString:
print("malformed") # -> 'malformed'
try:
store.remove_tuple("user:bob", "viewer", "doc:1") # bob was never added
except AdmissionRejected as error:
print(str(error).startswith("non-existent tuple cannot be removed")) # -> True
A read is checked the same way for types and relations: a check, lookup,
lookup_reverse or expand that names a type or relation the schema does not declare
raises zanzibar.UndeclaredTypeOrRelation, a ValueError, so a typo in a relation
name is reported rather than read as “denied”. Names are not checked: a check about an
object no tuple mentions answers False.
from zanzibar import UndeclaredTypeOrRelation
try:
store.check("user:alice", "veiwer", "doc:1") # a typo for "viewer"
caught = None
except UndeclaredTypeOrRelation as error:
caught = type(error).__name__
print(caught) # -> 'UndeclaredTypeOrRelation'
print(store.check("user:alice", "viewer", "doc:999")) # -> False
What a read checks lists exactly what a read refuses.
Resource limits: change the write, or the limit¶
zanzibar.ClosureFanoutExceeded and zanzibar.PathCountExceeded are
AdmissionRejecteds for a valid write that is too large for the graph index. On a
synchronous store the write is refused completely: it is in neither backend. Retrying the
same write does not help; split it, or raise the limit. See
Cap write fan-out.
While such a row, written by a sync=False instance, waits in the log, every write
through a sync=True instance of the same store fails with the same exception, about
that row rather than yours. The message says so, names the row, and says how to unblock
the store; see
A pending row can block every synchronous write.
Schema problems: fix the schema¶
These are raised when a schema is parsed or a store is opened. They are setup errors, not something to handle per request.
zanzibar.SchemaError: the schema text is refused. The message says what is wrong and, for a shape the library does not accept, what to write instead. See Rewrite a refused schema shape.zanzibar.CyclicDerivedDependency: a relation that usesandorbut notdepends on itself. It is aValueErrorbut not aSchemaError, soexcept SchemaErrordoes not catch it. The same is true ofzanzibar.UnsupportedByGraphIndex, raised when a wildcard feature reaches a relation that usesandorbut not.zanzibar.SchemaMismatch: you opened an existing store with a different schema from the one it was created with. Schemas cannot be changed; see Change a schema.
from zanzibar import SchemaError, SchemaMismatch, parse_openfga_schema
try:
parse_openfga_schema("type user\ntype doc\n relations\n define viewer: [usr]\n")
except SchemaError as error:
print(str(error)) # -> "doc#viewer: restriction [usr] names an undeclared type 'usr'; declare it (type usr) or fix the spelling"
try:
Store(Session(engine), "my-app", schema=SCHEMA.replace("[user]", "[user, doc#viewer]"))
except SchemaMismatch:
print("schemas are write-once") # -> 'schemas are write-once'
A relation that uses but not and recurses through the side it keeps (here
group#member) is refused with CyclicDerivedDependency, which an
except SchemaError lets through. Catch it by name, or catch ZanzibarError:
from zanzibar import CyclicDerivedDependency
GROUPS = """
model
schema 1.1
type user
type group
relations
define banned: [user]
define member: [user, group#member] but not banned
"""
try:
parse_openfga_schema(GROUPS)
except (SchemaError, CyclicDerivedDependency) as error:
refusal = error
print(type(refusal).__name__) # -> 'CyclicDerivedDependency'
print(isinstance(refusal, SchemaError)) # -> False
print(isinstance(refusal, ZanzibarError)) # -> True
To fix the schema, see
Recursion through and or but not.
The rest of this kind (zanzibar.ShapeNoLongerAccepted,
zanzibar.PersistedSchemaRefused, zanzibar.DoublyBridgedShapeError) are
in the schema errors reference.
Setup and configuration: fix the deployment¶
These come from how the database, the tables or the store were set up. Fix the configuration; retrying does not help.
zanzibar.TablesNotCreated: thezanzibar_*tables are missing. RunSQLModel.metadata.create_all(engine)after importing the library. Itsmissingattribute lists the missing tables.zanzibar.TablesOutdated: thezanzibar_*tables in a SQLite file were created by a 0.0.x release, which made them in an older layout. Create the tables in a new database file and write the tuples again.zanzibar.StoreNotFound:Store(session, store_id)without a schema names a store that does not exist in this database. Create it once by passingschema=, or check that the session points at the right database.
The others of this kind are zanzibar.UnsafeIsolationLevel (see
Run on PostgreSQL), zanzibar.WriteLockUnsafe, and
zanzibar.UnloggedTuplesPresent / zanzibar.UnloggedWriteRefused (see
Bulk-load or adopt an existing store); the
reference describes each. A few more come
only from driving the backends or the offline index tools yourself; they are listed in
Use the backends directly.
from zanzibar import StoreNotFound, TablesNotCreated
try:
Store(Session(engine), "no-such-store")
except StoreNotFound as error:
print(error.store_id) # -> 'no-such-store'
empty = create_engine("sqlite:///empty.db") # tables never created
try:
Store(Session(empty), "my-app", schema=SCHEMA)
except TablesNotCreated as error:
print("zanzibar_relation_tuple" in error.missing) # -> True
Freshness: refresh and retry¶
These mean a read could not be answered as fresh as you asked. Nothing is wrong with the data, and the same request usually succeeds after a refresh or once the index catches up. See Use async mode and freshness tokens.
zanzibar.StaleRead: acheckorexpandwithat_least=tokennames a write this session cannot see yet. Callzanzibar.Store.refresh()and retry once. If the retry fails the same way, the token is wrong, and retrying further will not help.zanzibar.LookupNotFresh: alookuporlookup_reversewithat_least=while the index is behind that write. Runcatch_up(), or wait for your worker to, and retry. For a single decision,check(..., at_least=token)answers anyway.zanzibar.IndexStalled: alookuporlookup_reversewithout a token while the index is stalled. See Recover a stalled index.
zanzibar.WatermarkGap (refresh and retry) and zanzibar.StaleLookupIds
(run the lookup again; see Find who can access what) belong here too;
see the freshness reference.
from zanzibar import StaleRead
token = store.add_tuple("user:bob", "viewer", "doc:1")
try:
store.check("user:bob", "viewer", "doc:1", at_least=token + 1000) # not issued yet
except StaleRead as error:
print("was not issued yet" in str(error)) # -> True
print(store.check("user:bob", "viewer", "doc:1", at_least=token)) # -> True
A token from another store¶
zanzibar.ForeignToken, a StaleRead, means the token was returned by a write to
a different store. Every tokened read refuses it (check, lookup, lookup_reverse,
expand), whatever its value, and the message starts with that cause and names both
stores. Do not retry: nothing about this store can make the token valid. Pass a token
from one of this store’s own writes. If a handler of yours retries on StaleRead, catch
ForeignToken before it. A lookup with a token from another store raises ForeignToken,
not LookupNotFresh.
from zanzibar import ForeignToken
other = Store(Session(engine), "other-app", schema=SCHEMA)
foreign = other.add_tuple("user:carol", "viewer", "doc:9")
try:
store.check("user:bob", "viewer", "doc:1", at_least=foreign)
except ForeignToken as error:
print((error.issued_by, error.store_id)) # -> ('other-app', 'my-app')
What except ZanzibarError does not catch¶
zanzibar.InvariantViolation, anAssertionError. It means the stored index is corrupt, not that a request was refused, so it is kept out ofZanzibarErroron purpose. Let it reach your error reporting. When it comes from the check that runs after a commit, the write it reports on is already stored; see When a check fails.zanzibar.UnprovenExtensionWarning, a warning, not an exception. It is emitted for a schema that uses a wildcard feature beyond OpenFGA’s; see the section below.A misspelt
ZANZIBAR_PARANOIAorZANZIBAR_MAX_CLOSURE_FANOUT, or an invalidparanoia=argument, raises a plainValueErrorwhen the store opens.Errors from the database driver pass through unchanged. On SQLite, a write that competes with another writer can fail with
sqlite3.OperationalError: database is locked(wrapped by SQLAlchemy); the store has rolled back, and the write can be retried.A
Storerefuses aSessionthat has unsaved changes of yours (objects added but not committed) with a plainValueError, because it commits and rolls back the session itself. Give eachStorea session of its own.An
at_least=that is not anint(a string, a float,True) raises a plainTypeError, and a negative one a plainValueError. Pass the token exactly as a write returned it.Any other
ValueErrorthat is not aZanzibarError, escaping from a write, is a bug in the library or in how it is being called, not a refusal. Report it.
Silence the wildcard-extension warning, or make it an error¶
A schema that uses a wildcard feature beyond OpenFGA’s (for example [group:*#member])
emits zanzibar.UnprovenExtensionWarning when a store opens. It is a
UserWarning, so you control it with the standard warnings module, by its class.
Wildcard extensions beyond OpenFGA explains when
each choice makes sense.
To silence it where you have chosen the extension on purpose, filter it around the code that opens the store, and say in a comment which extension you rely on:
import warnings
import zanzibar
EXT_SCHEMA = """
model
schema 1.1
type user
type group
relations
define member: [user]
type doc
relations
define viewer: [user, group:*#member]
"""
ext_engine = create_engine("sqlite://")
SQLModel.metadata.create_all(ext_engine)
with warnings.catch_warnings(record=True) as seen:
warnings.simplefilter("always")
# We rely on [group:*#member] ("every member of any group") on purpose.
warnings.filterwarnings("ignore", category=zanzibar.UnprovenExtensionWarning)
ext_store = Store(Session(ext_engine), "ext-quiet", schema=EXT_SCHEMA)
print(len(seen)) # -> 0
To make it an error, for example in your test suite, turn the warning into an exception. Opening a store with such a schema then raises it:
with warnings.catch_warnings():
warnings.simplefilter("error", zanzibar.UnprovenExtensionWarning)
try:
Store(Session(ext_engine), "ext-strict", schema=EXT_SCHEMA)
escalated = False
except zanzibar.UnprovenExtensionWarning:
escalated = True
print(escalated) # -> True
In a pytest suite the same effect comes from the filterwarnings setting, for example
error::zanzibar.UnprovenExtensionWarning.