Exceptions¶
Every exception the library raises on purpose is importable from the top-level package,
zanzibar, and every one but zanzibar.InvariantViolation derives from
zanzibar.ZanzibarError. Every subclass also has a builtin base
(ValueError, KeyError or RuntimeError), so a handler that
catches the builtin keeps working.
Import exceptions from zanzibar; that is their one public home. No subpackage
(zanzibar.schema, zanzibar.store, zanzibar.setengine, zanzibar.graphindex) lists
an exception in its __all__. An older from zanzibar.store import StaleRead still
imports the same class, but it is not part of the API and may stop working in a later
release.
For how to choose what to catch in an application, see Handle errors.
Hierarchy¶
Builtin bases are in brackets. A class inherits every base of its parents.
Exception
├── ZanzibarError
│ ├── SchemaError [ValueError]
│ │ └── ShapeNoLongerAccepted
│ ├── PersistedSchemaRefused [ValueError]
│ ├── CyclicDerivedDependency [ValueError]
│ ├── SchemaMismatch [ValueError]
│ ├── UnsupportedByGraphIndex [ValueError]
│ │ └── DoublyBridgedShapeError
│ ├── MalformedTupleString [ValueError]
│ ├── UndeclaredTypeOrRelation [ValueError]
│ ├── AdmissionRejected [ValueError]
│ │ └── IndexResourceLimit
│ │ ├── ClosureFanoutExceeded
│ │ └── PathCountExceeded
│ ├── MissingDeltaProcessor [ValueError]
│ ├── IndexExists [ValueError]
│ ├── StoreNotFound [KeyError]
│ ├── StaleLookupIds [KeyError]
│ ├── StaleRead [RuntimeError]
│ │ ├── LookupNotFresh
│ │ │ └── IndexStalled
│ │ └── ForeignToken
│ ├── WatermarkGap [RuntimeError]
│ ├── UnsafeIsolationLevel [RuntimeError]
│ ├── WriteLockUnsafe [RuntimeError]
│ ├── CascadeNotRun [RuntimeError]
│ ├── UnloggedWriteRefused [RuntimeError]
│ ├── UnloggedTuplesPresent [RuntimeError]
│ ├── TablesNotCreated [RuntimeError]
│ └── TablesOutdated [RuntimeError]
└── AssertionError
└── InvariantViolation (not a ZanzibarError)
UserWarning
└── UnprovenExtensionWarning (a warning, not an error)
zanzibar.InvariantViolation is outside the tree on purpose. It means the stored
index is corrupt, not that a call was refused, so except ZanzibarError never swallows it.
It is raised by the runtime checks that the paranoia setting turns on (see
Configuration).
import zanzibar
print(issubclass(zanzibar.ClosureFanoutExceeded, zanzibar.AdmissionRejected)) # -> True
print(issubclass(zanzibar.AdmissionRejected, ValueError)) # -> True
print(issubclass(zanzibar.IndexStalled, zanzibar.StaleRead)) # -> True
print(issubclass(zanzibar.ForeignToken, zanzibar.StaleRead)) # -> True
print(issubclass(zanzibar.ForeignToken, zanzibar.LookupNotFresh)) # -> False
print(issubclass(zanzibar.UnsupportedByGraphIndex, ValueError)) # -> True
print(issubclass(zanzibar.StoreNotFound, KeyError)) # -> True
print(issubclass(zanzibar.CyclicDerivedDependency, zanzibar.SchemaError)) # -> False
print(issubclass(zanzibar.CyclicDerivedDependency, ValueError)) # -> True
print(issubclass(zanzibar.InvariantViolation, zanzibar.ZanzibarError)) # -> False
print(issubclass(zanzibar.InvariantViolation, AssertionError)) # -> True
print(issubclass(zanzibar.UnprovenExtensionWarning, UserWarning)) # -> True
When each is raised¶
exception |
raised when |
|---|---|
the parser refuses a schema text (DSL or OpenFGA JSON): a syntax error, a dangling or cyclic relation reference, or a refused shape. For a refused shape, the message says what to write instead (Refused schema shapes, Rewrite a refused schema shape). |
|
a schema you pass uses a shape an older release accepted and this one refuses. |
|
a store’s stored schema uses such a shape, so the store cannot be opened, whichever call opens it. See Upgrade from 0.0.x to 0.1. |
|
a relation that uses |
|
a store is opened with a schema other than the one it was created with. |
|
the graph index cannot represent a schema construct: a wildcard feature (a |
|
a shape is both a wildcard-userset shape and an object-wildcard shape. Both backends refuse it. |
|
a |
|
a read ( |
|
a write is refused: an undeclared type or relation, a subject the type restriction does not admit, an identifier outside |
|
never raised itself: the common base of the two refusals below, which depend on how large the index’s closure has grown rather than on the tuple and the schema. Catch it to handle both. |
|
a synchronous write would add more rows to the index than the fan-out cap allows. Nothing is written. See Cap write fan-out. |
|
a write would push a stored path count past the 32-bit integer limit (about 2.1 billion; not configurable). On a synchronous write the write is refused and nothing is written. With |
|
the index’s apply step is driven by hand without a delta processor, on a schema with |
|
|
|
|
|
ids from a lookup result are translated after they may have been reused (after a write, a rebuild, or on another instance). Run the lookup again. |
|
a read carrying an |
|
a tokened read ( |
|
a |
|
an untokened |
|
advancing the index would skip committed log rows (a concurrent commit not yet visible). Nothing was committed. Retryable: |
|
a PostgreSQL session is not at |
|
a SQLite connection is in autocommit mode, so the per-store write lock would not hold. Raised when the store opens. |
|
a commit after a direct graph-index write on a schema with |
|
a standalone set engine writes to a store id that a |
|
a |
|
a |
|
a |
|
a runtime check finds the stored index corrupt. When the check before the commit fails, the commit does not happen. At the |
|
(a warning) a schema uses a wildcard extension beyond OpenFGA. |
Some argument errors are plain builtins and not part of this tree: for example, a bad
paranoia value is a ValueError, a compiled rule set passed as schema= is a
TypeError, and a Session with pending changes passed to a
Store is a ValueError.
from sqlmodel import SQLModel, Session, create_engine
import zanzibar
import zanzibar.store # registers the zanzibar_* tables before create_all
SCHEMA = """
model
schema 1.1
type user
type doc
relations
define viewer: [user]
"""
engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
store = zanzibar.Store(session, "exceptions-demo", schema=SCHEMA)
try:
store.add_tuple("user:alice", "vewer", "doc:1")
except zanzibar.AdmissionRejected as exc:
caught = type(exc).__name__
print(caught) # -> 'AdmissionRejected'
try:
store.add_tuple("user alice", "viewer", "doc:1")
except ValueError as exc: # the builtin base still catches it
caught = type(exc).__name__
print(caught) # -> 'MalformedTupleString'
with Session(engine) as session:
try:
zanzibar.Store(session, "no-such-store")
except zanzibar.StoreNotFound as exc:
missing_id = exc.store_id
print(missing_id) # -> 'no-such-store'
The root¶
- exception zanzibar.ZanzibarError¶
Bases:
ExceptionThe root of every exception the library raises on purpose.
except zanzibar.ZanzibarErrorcatches every refusal, limit and freshness error the library defines.zanzibar.InvariantViolationandzanzibar.UnprovenExtensionWarningare deliberately outside it.
Schema errors¶
- exception zanzibar.SchemaError¶
Bases:
zanzibar.ZanzibarError,ValueErrorThe parser refused a schema text (DSL or OpenFGA JSON): a syntax error, a dangling or cyclic relation reference, or a refused shape. The message says what is wrong and, for a refused shape, what to write instead. Three schema refusals are
ValueErrorbut notSchemaError, because the text parsed and the graph index refused it:UnsupportedByGraphIndex, its subclassDoublyBridgedShapeError, andCyclicDerivedDependency. CatchValueError(orZanzibarError) to cover all of them.
- exception zanzibar.ShapeNoLongerAccepted¶
Bases:
zanzibar.SchemaErrorA schema you pass uses a shape that an earlier release accepted and this one refuses: a
schemaline naming a version other than1.1, extra words on a header line,but notsharing a level with another operator without parentheses, a type restriction naming an undeclared type, or anobject_wildcard_shapesentry naming no declared relation. The message ends with the rewrite.
- exception zanzibar.PersistedSchemaRefused¶
Bases:
zanzibar.ZanzibarError,ValueErrorA store’s stored schema text uses a shape this release refuses, so the store cannot be opened. Every open re-parses the stored text, so this is raised whatever opens the store:
zanzibar.Storewith or withoutschema=,zanzibar.setengine.SetEngine, orzanzibar.store.build_index(). There is no lenient mode. The message quotes the parser’s refusal and gives the rewrite. A store’s schema never changes, so applying the rewrite means creating a new store.- refusal: zanzibar.ShapeNoLongerAccepted¶
The parser’s refusal; also the exception’s
__cause__.
- exception zanzibar.CyclicDerivedDependency¶
Bases:
zanzibar.ZanzibarError,ValueErrorA relation that uses
and/but notdepends on itself, through afromstep or a[type#relation]restriction. The graph index cannot evaluate that recursion, sozanzibar.parse_openfga_schema()andStorerefuse the schema. A standalonezanzibar.setengine.SetEngineaccepts it. The message suggests a rewrite.Not a subclass of
SchemaError. Recursion that the parser itself refuses is aSchemaError: a relation referring to itself through relation names alone, and recursion through the part abut notsubtracts.
- exception zanzibar.SchemaMismatch¶
Bases:
zanzibar.ZanzibarError,ValueErrorAn explicit schema, or set of object-wildcard shapes, disagrees with the one the store was created with. Stored schemas never change. Raised by
zanzibar.Storeand byzanzibar.setengine.SetEngineopened on a store id that has a stored schema. The same schema reformatted, with comments, or with its type blocks,definelines or restriction lists reordered is not a mismatch; swapped operands ofor,andorbut notare.
- exception zanzibar.UnsupportedByGraphIndex¶
Bases:
zanzibar.ZanzibarError,ValueErrorThe graph index cannot represent a schema construct: a wildcard feature (a
[T:*#p]restriction, a star tupleset or anobject_wildcard_shapesentry) that reaches a relation usingand/but not, orand/but notwhen the rule set is compiled withenable_boolean=False. Raised byzanzibar.parse_openfga_schema()andzanzibar.Store. The message names the relation. The set engine handles every shape this refuses exceptDoublyBridgedShapeError. AValueErrorsince 0.1.0 (before, it had no builtin base), so anexcept ValueErroraround schema loading catches it. It is not aSchemaError: the text parsed, and the graph compile refused it.
- exception zanzibar.DoublyBridgedShapeError¶
Bases:
zanzibar.UnsupportedByGraphIndexA shape is both a wildcard-userset shape (a
[T:*#p]restriction) and an object-wildcard shape. A wildcard write on it would make the graph index refuse every later ordinary write of that shape, so both backends refuse the schema.
Write refusals¶
- exception zanzibar.MalformedTupleString¶
Bases:
zanzibar.ZanzibarError,ValueErrorA
"type:name"or"type:name#relation"string could not be split into its parts. The message names the expected form. A:in the relation part after#is a shape error too, so"group:g#b:c"raises it on reads and writes alike.
- exception zanzibar.UndeclaredTypeOrRelation¶
Bases:
zanzibar.ZanzibarError,ValueErrorA read named a type, a relation or a subject relation the schema does not declare.
Storeraises it fromcheck,lookup,lookup_reverseandexpand, and the set engine from the same methods andfilter_result, before anything is read. The message is the one a write with the same mistake gets, such astype 'doc' declares no relation 'vewer'; did you mean 'viewer'?. Names are not checked: an unknown object or subject name, and the wildcard namesuser:*andfolder:*, are not refused. When the subject looks like a lookup result key(type, name, predicate)passed wherechecktakes(subject_predicate, subject_type, subject_name), the message ends with the corrected call. Attributes:method,role('subject','object'or'filter'),type_nameandrelation.
- exception zanzibar.AdmissionRejected¶
Bases:
zanzibar.ZanzibarError,ValueErrorA write was correctly refused; the store is intact. The refusals are: a cycle, an identifier outside the allowed characters or length, a tuple no declared type restriction admits, an undeclared wildcard shape, and removing a tuple that is not stored. It is never a sign of corruption; that is
InvariantViolation.
- exception zanzibar.IndexResourceLimit¶
Bases:
zanzibar.AdmissionRejectedThe graph index declined to materialise an admitted write because of a limit on the size of its closure, not because of the tuple or the schema. Not raised itself: its two subclasses are
ClosureFanoutExceededandPathCountExceeded.
- exception zanzibar.ClosureFanoutExceeded¶
Bases:
zanzibar.IndexResourceLimitA synchronous write would add more rows to the graph index’s closure than the
ZANZIBAR_MAX_CLOSURE_FANOUTcap allows (default 100,000;0disables it). The refusal is atomic: the write is absent from the tuple log and from both backends. The cap bounds how long one write holds the store’s write lock; it is not an access rule, and underbut nota ban is capped like any other write. Rows already in the log are never refused:Store.catch_upandbuild_index()apply them with a logged warning. See Configuration.
- exception zanzibar.PathCountExceeded¶
Bases:
zanzibar.IndexResourceLimitA write would push a closure row’s path count past 2,147,483,647, the 32-bit integer limit, which applies on SQLite and PostgreSQL alike and is not configurable. Path counts count derivations, so a chain of K diamonds (many layers of overlapping groups) doubles them K times. A synchronous write is refused. With
sync=False,Store.catch_upraises it and the index stalls (seeIndexStalled). While that row waits in the log, writes through async=Trueinstance raise it too, about the waiting row; the message names that row and the recovery (async=Falseremoval, thenzanzibar.store.rebuild_index()); see A pending row can block every synchronous write. See Recover a stalled index.- failing_log_row: tuple[int, str]¶
Set when the index’s apply step refused a log row:
(log id, row), the row in the formADD user:alice viewer doc:1.ClosureFanoutExceededcarries it in the same case.
Freshness and the index¶
- exception zanzibar.StaleRead¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA read carrying an
at_leasttoken could not be satisfied: the index is behind the token and the write is not visible in this session’s read snapshot. Callrefresh()and retry once. If the retry fails the same way, the token is wrong: the library cannot tell a token that was never issued from one committed after this session’s snapshot began, so the message offers both. A token that another store’s write returned raises the subclassForeignTokeninstead, which no retry fixes.
- exception zanzibar.LookupNotFresh¶
Bases:
zanzibar.StaleReadA
lookup/lookup_reversecarrying anat_leasttoken could not be served, because the index is behind the token.checkfalls back to the set engine in this case; the lookups do not, because the two backends’ results use different node ids. Runcatch_up()(any instance may) and retry. For a single yes/no answer,check(..., at_least=...)needs no catch-up. A token from another store raisesForeignToken, not this.
- exception zanzibar.IndexStalled¶
Bases:
zanzibar.LookupNotFreshAn untokened
lookup/lookup_reversewas refused because the lastcatch_up()could not advance the index, so how far behind it is no longer bounded.checkfalls back to the set engine in this state. A stall from a transient failure (a lock timeout, a lost connection) ends at the next successfulcatch_up(), including one that applies nothing because the index is already at the head of the log (a stall recorded on an idle poll, where the message says “lag 0”). A row that can never be applied, a path-count overflow, needs action:Store.stall_errornames the row and the failure. See Recover a stalled index.
- exception zanzibar.ForeignToken¶
Bases:
zanzibar.StaleReadA tokened read (
check,lookup,lookup_reverse,expand, andTupleSource.check) was passed anat_leasttoken that a write to another store returned. Tokens are log ids, and log ids count up across every store in the database, so another store’s token says nothing about this one. The read refuses it whether the token is above or below this store’s own writes. The message starts with the cause and names both stores.Not retryable:
refresh()andcatch_up()cannot change which store wrote the token. How to handle it: A token from another store. Pass a token that one of this store’s own writes returned. It subclassesStaleRead, so an existingexcept StaleReadstill catches it, and it is deliberately not aLookupNotFresh. New in 0.1.0; before, such a token was accepted without error at or below this store’s cursor.
- exception zanzibar.WatermarkGap¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorAdvancing the index or the set engine would have skipped committed log rows. On PostgreSQL a log row with a lower id can become visible after one with a higher id, so a catch-up can see a gap; the advance is refused instead of skipping it. Nothing is corrupt and nothing was committed. Call
refresh()and retry.
- exception zanzibar.StaleLookupIds¶
Bases:
zanzibar.ZanzibarError,KeyErrorresult_keys/excluded_keysrefused to translate a lookup result whose ids may no longer name what they named when the lookup ran. Ids are valid only for the read snapshot the lookup used. Run the lookup again and translate the new result before the next write.
- exception zanzibar.MissingDeltaProcessor¶
Bases:
zanzibar.ZanzibarError,ValueErrorThe index’s apply step was driven by hand without a delta processor, on a schema with
and/but not. Without it the index would disagree with the set engine. AStorenever raises it.
- exception zanzibar.IndexExists¶
Bases:
zanzibar.ZanzibarError,ValueErrorbuild_index()orStore.adoptwas pointed at an index store id that already has a cursor or graph state. Use a new index store id, orrebuild_index()to rebuild in place.
Opening a store¶
- exception zanzibar.StoreNotFound¶
Bases:
zanzibar.ZanzibarError,KeyErrorThe store id has no stored schema in this database: it was never created here, or the session points at another database. A store is created by passing its schema once:
Store(session, store_id, schema=...).
- exception zanzibar.TablesNotCreated¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorThe database has none, or only some, of the
zanzibar_*tables. Raised byStorein place of the database driver’s own error. RunSQLModel.metadata.create_all(engine)after importing the library. See Database tables.
- exception zanzibar.TablesOutdated¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA SQLite file’s
zanzibar_nodetable was created by a 0.0.x release, withoutAUTOINCREMENT. The file is not migrated: create the tables in a new database file and write the tuples again. See Database tables and Upgrade from 0.0.x to 0.1.
- exception zanzibar.UnsafeIsolationLevel¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA PostgreSQL session runs at an isolation level other than
READ COMMITTED, under which a committed write can stay invisible to the store. Raised when the store opens. The message names the fix. See Supported environments.
- exception zanzibar.WriteLockUnsafe¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorThe per-store write lock cannot be taken on this session’s connection (a SQLite connection in autocommit mode), so a write’s checks would not be atomic against other writers. Raised when the store opens. The message names the fix.
- exception zanzibar.CascadeNotRun¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA commit was refused because a direct write to the graph index, on a schema with
and/but notrelations, ran noDeltaProcessor.run_cascadein the same transaction after it, so committing would leave the derived relations stale. Raised by the commit; the transaction is still open.store_idsnames the stores that owe a cascade. The check shows a cascade was called, not that its watermark was right. AStoreruns the cascade itself and never raises it.
- exception zanzibar.UnloggedTuplesPresent¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA
Storerefused to open over a store id that already has tuples with no matching tuple-log rows, written by a standalone set engine before anyStoreclaimed the id. The index, which is built from the log, would not see them. Open such a store withStore.adopt.
- exception zanzibar.UnloggedWriteRefused¶
Bases:
zanzibar.ZanzibarError,RuntimeErrorA direct
add_tuple/remove_tupleon a standaloneSetEnginewas refused because aStoreowns that store id. Such a write would bypass the tuple log, so the index and every other instance would never see it. Write through theStore.
Outside the tree¶
- exception zanzibar.InvariantViolation¶
Bases:
AssertionErrorA stored-state invariant does not hold: the index is corrupt. Raised by the runtime checks that the
paranoiasetting turns on (see Configuration). It is deliberately not aZanzibarError, so a handler for refusals never swallows it; catch it explicitly if you catch it at all.
- exception zanzibar.UnprovenExtensionWarning¶
Bases:
UserWarningA schema uses a wildcard extension beyond OpenFGA: a wildcard userset
[T:*#p], a wildcard tupleset, or object wildcards. Agreement between the two backends on these rests on tests alone. Emitted once perStoreopen (orzanzibar.parse_openfga_schema()/SetEnginecall). Silence it withwarnings.filterwarnings('ignore', category=zanzibar.UnprovenExtensionWarning).