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

SchemaError

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).

ShapeNoLongerAccepted

a schema you pass uses a shape an older release accepted and this one refuses. instead holds the rewrite. See Rewrite a refused schema shape.

PersistedSchemaRefused

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.

CyclicDerivedDependency

a relation that uses and / but not depends on itself through a from step or a [type#relation] restriction. Raised by parse_openfga_schema() and by Store; a standalone SetEngine accepts the schema. Not a SchemaError.

SchemaMismatch

a store is opened with a schema other than the one it was created with.

UnsupportedByGraphIndex

the graph index cannot represent a schema construct: a wildcard feature (a [T:*#p] restriction, a star tupleset or an object_wildcard_shapes entry) that reaches a relation using and / but not (for example [group:*#member] where member is [user] but not banned), or and / but not when the rule set is compiled with enable_boolean=False. Raised by parse_openfga_schema and Store; a standalone SetEngine accepts these schemas. A ValueError, not a SchemaError.

DoublyBridgedShapeError

a shape is both a wildcard-userset shape and an object-wildcard shape. Both backends refuse it.

MalformedTupleString

a "type:name" / "type:name#relation" argument cannot be split into its parts, such as "alice", "user:a:b" or "group:g#b:c". Raised on reads and writes alike.

UndeclaredTypeOrRelation

a read (check, lookup, lookup_reverse, expand, or the set engine’s filter_result) names a type, a relation or a subject relation the schema does not declare, such as check("user:alice", "vewer", "doc:1"). An unknown object or subject name is not refused. Raised since 0.1.3.

AdmissionRejected

a write is refused: an undeclared type or relation, a subject the type restriction does not admit, an identifier outside A-Za-z0-9_./@+=- or longer than 256 characters, a cycle (a group inside itself, a folder that is its own ancestor), or removing a tuple that is not stored. The store is unchanged. A read naming an undeclared type or relation raises UndeclaredTypeOrRelation instead.

IndexResourceLimit

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.

ClosureFanoutExceeded

a synchronous write would add more rows to the index than the fan-out cap allows. Nothing is written. See Cap write fan-out.

PathCountExceeded

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 sync=False the write is accepted into the log; catch_up() then raises this and the index stalls (see IndexStalled). While that row waits, writes through a sync=True instance raise it too; see A pending row can block every synchronous write.

MissingDeltaProcessor

the index’s apply step is driven by hand without a delta processor, on a schema with and / but not.

IndexExists

build_index() or Store.adopt targets an index that already exists.

StoreNotFound

Store(session, store_id) without schema= names a store id that has no stored schema in this database.

StaleLookupIds

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.

StaleRead

a read carrying an at_least token cannot be satisfied. Call refresh() and retry once; if that fails the same way, the token is wrong.

ForeignToken

a tokened read (check, lookup, lookup_reverse, expand) was passed a token that a write to another store returned. Not retryable: pass a token from this store’s own writes.

LookupNotFresh

a lookup / lookup_reverse carrying an at_least token while the index is behind the token. Run catch_up() and retry.

IndexStalled

an untokened lookup / lookup_reverse while the index has recorded that it cannot advance. See Recover a stalled index.

WatermarkGap

advancing the index would skip committed log rows (a concurrent commit not yet visible). Nothing was committed. Retryable: refresh() and retry.

UnsafeIsolationLevel

a PostgreSQL session is not at READ COMMITTED. Raised when the store opens.

WriteLockUnsafe

a SQLite connection is in autocommit mode, so the per-store write lock would not hold. Raised when the store opens.

CascadeNotRun

a commit after a direct graph-index write on a schema with and / but not, when no run_cascade ran after the write. The transaction stays open: roll back, or run the cascade and commit again. A Store never raises it. See Use the backends directly.

UnloggedWriteRefused

a standalone set engine writes to a store id that a Store owns.

UnloggedTuplesPresent

a Store opens over tuples a standalone set engine wrote. Use Store.adopt.

TablesNotCreated

a Store opens on a database without the zanzibar_* tables. Run SQLModel.metadata.create_all(engine) after importing the library. See Database tables.

TablesOutdated

a Store opens a SQLite file whose zanzibar_node table an older release created. 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.

InvariantViolation

a runtime check finds the stored index corrupt. When the check before the commit fails, the commit does not happen. At the full and fixpoint levels a second check runs after the commit; when that one fails the write is already stored, the message says so, and the store stays usable. See Configuration.

UnprovenExtensionWarning

(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: Exception

The root of every exception the library raises on purpose. except zanzibar.ZanzibarError catches every refusal, limit and freshness error the library defines. zanzibar.InvariantViolation and zanzibar.UnprovenExtensionWarning are deliberately outside it.

Schema errors

exception zanzibar.SchemaError

Bases: zanzibar.ZanzibarError, ValueError

The 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 ValueError but not SchemaError, because the text parsed and the graph index refused it: UnsupportedByGraphIndex, its subclass DoublyBridgedShapeError, and CyclicDerivedDependency. Catch ValueError (or ZanzibarError) to cover all of them.

exception zanzibar.ShapeNoLongerAccepted

Bases: zanzibar.SchemaError

A schema you pass uses a shape that an earlier release accepted and this one refuses: a schema line naming a version other than 1.1, extra words on a header line, but not sharing a level with another operator without parentheses, a type restriction naming an undeclared type, or an object_wildcard_shapes entry naming no declared relation. The message ends with the rewrite.

instead: str

The rewrite that keeps the meaning, in words you can act on.

accepted_through: str

The last release that accepted the shape.

refused_since: str

The first release that refuses it.

exception zanzibar.PersistedSchemaRefused

Bases: zanzibar.ZanzibarError, ValueError

A 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.Store with or without schema=, zanzibar.setengine.SetEngine, or zanzibar.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.

store_id: str
refusal: zanzibar.ShapeNoLongerAccepted

The parser’s refusal; also the exception’s __cause__.

instead: str

The rewrite, as in refusal.instead.

exception zanzibar.CyclicDerivedDependency

Bases: zanzibar.ZanzibarError, ValueError

A relation that uses and / but not depends on itself, through a from step or a [type#relation] restriction. The graph index cannot evaluate that recursion, so zanzibar.parse_openfga_schema() and Store refuse the schema. A standalone zanzibar.setengine.SetEngine accepts it. The message suggests a rewrite.

Not a subclass of SchemaError. Recursion that the parser itself refuses is a SchemaError: a relation referring to itself through relation names alone, and recursion through the part a but not subtracts.

exception zanzibar.SchemaMismatch

Bases: zanzibar.ZanzibarError, ValueError

An explicit schema, or set of object-wildcard shapes, disagrees with the one the store was created with. Stored schemas never change. Raised by zanzibar.Store and by zanzibar.setengine.SetEngine opened on a store id that has a stored schema. The same schema reformatted, with comments, or with its type blocks, define lines or restriction lists reordered is not a mismatch; swapped operands of or, and or but not are.

exception zanzibar.UnsupportedByGraphIndex

Bases: zanzibar.ZanzibarError, ValueError

The graph index cannot represent a schema construct: a wildcard feature (a [T:*#p] restriction, a star tupleset or an object_wildcard_shapes entry) that reaches a relation using and / but not, or and / but not when the rule set is compiled with enable_boolean=False. Raised by zanzibar.parse_openfga_schema() and zanzibar.Store. The message names the relation. The set engine handles every shape this refuses except DoublyBridgedShapeError. A ValueError since 0.1.0 (before, it had no builtin base), so an except ValueError around schema loading catches it. It is not a SchemaError: the text parsed, and the graph compile refused it.

exception zanzibar.DoublyBridgedShapeError

Bases: zanzibar.UnsupportedByGraphIndex

A 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, ValueError

A "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, ValueError

A read named a type, a relation or a subject relation the schema does not declare. Store raises it from check, lookup, lookup_reverse and expand, and the set engine from the same methods and filter_result, before anything is read. The message is the one a write with the same mistake gets, such as type 'doc' declares no relation 'vewer'; did you mean 'viewer'?. Names are not checked: an unknown object or subject name, and the wildcard names user:* and folder:*, are not refused. When the subject looks like a lookup result key (type, name, predicate) passed where check takes (subject_predicate, subject_type, subject_name), the message ends with the corrected call. Attributes: method, role ('subject', 'object' or 'filter'), type_name and relation.

exception zanzibar.AdmissionRejected

Bases: zanzibar.ZanzibarError, ValueError

A 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.AdmissionRejected

The 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 ClosureFanoutExceeded and PathCountExceeded.

exception zanzibar.ClosureFanoutExceeded

Bases: zanzibar.IndexResourceLimit

A synchronous write would add more rows to the graph index’s closure than the ZANZIBAR_MAX_CLOSURE_FANOUT cap allows (default 100,000; 0 disables 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 under but not a ban is capped like any other write. Rows already in the log are never refused: Store.catch_up and build_index() apply them with a logged warning. See Configuration.

exception zanzibar.PathCountExceeded

Bases: zanzibar.IndexResourceLimit

A 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_up raises it and the index stalls (see IndexStalled). While that row waits in the log, writes through a sync=True instance raise it too, about the waiting row; the message names that row and the recovery (a sync=False removal, then zanzibar.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 form ADD user:alice viewer doc:1. ClosureFanoutExceeded carries it in the same case.

Freshness and the index

exception zanzibar.StaleRead

Bases: zanzibar.ZanzibarError, RuntimeError

A read carrying an at_least token could not be satisfied: the index is behind the token and the write is not visible in this session’s read snapshot. Call refresh() 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 subclass ForeignToken instead, which no retry fixes.

exception zanzibar.LookupNotFresh

Bases: zanzibar.StaleRead

A lookup / lookup_reverse carrying an at_least token could not be served, because the index is behind the token. check falls back to the set engine in this case; the lookups do not, because the two backends’ results use different node ids. Run catch_up() (any instance may) and retry. For a single yes/no answer, check(..., at_least=...) needs no catch-up. A token from another store raises ForeignToken, not this.

exception zanzibar.IndexStalled

Bases: zanzibar.LookupNotFresh

An untokened lookup / lookup_reverse was refused because the last catch_up() could not advance the index, so how far behind it is no longer bounded. check falls back to the set engine in this state. A stall from a transient failure (a lock timeout, a lost connection) ends at the next successful catch_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_error names the row and the failure. See Recover a stalled index.

exception zanzibar.ForeignToken

Bases: zanzibar.StaleRead

A tokened read (check, lookup, lookup_reverse, expand, and TupleSource.check) was passed an at_least token 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() and catch_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 subclasses StaleRead, so an existing except StaleRead still catches it, and it is deliberately not a LookupNotFresh. New in 0.1.0; before, such a token was accepted without error at or below this store’s cursor.

token: int

The token that was passed.

issued_by: str

The store whose write returned it.

store_id: str

The store that was read.

exception zanzibar.WatermarkGap

Bases: zanzibar.ZanzibarError, RuntimeError

Advancing 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, KeyError

result_keys / excluded_keys refused 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.

field: str

'node_ids' or 'excluded_node_ids'.

ids: list[int]

The first offending ids; empty when the whole result is stale.

exception zanzibar.MissingDeltaProcessor

Bases: zanzibar.ZanzibarError, ValueError

The 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. A Store never raises it.

exception zanzibar.IndexExists

Bases: zanzibar.ZanzibarError, ValueError

build_index() or Store.adopt was pointed at an index store id that already has a cursor or graph state. Use a new index store id, or rebuild_index() to rebuild in place.

index_store_id: str
detail: str

What was found.

Opening a store

exception zanzibar.StoreNotFound

Bases: zanzibar.ZanzibarError, KeyError

The 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=...).

store_id: str
exception zanzibar.TablesNotCreated

Bases: zanzibar.ZanzibarError, RuntimeError

The database has none, or only some, of the zanzibar_* tables. Raised by Store in place of the database driver’s own error. Run SQLModel.metadata.create_all(engine) after importing the library. See Database tables.

missing: list[str]

The absent table names.

exception zanzibar.TablesOutdated

Bases: zanzibar.ZanzibarError, RuntimeError

A SQLite file’s zanzibar_node table was created by a 0.0.x release, without AUTOINCREMENT. 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.

table: str

'zanzibar_node'.

exception zanzibar.UnsafeIsolationLevel

Bases: zanzibar.ZanzibarError, RuntimeError

A 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, RuntimeError

The 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, RuntimeError

A commit was refused because a direct write to the graph index, on a schema with and / but not relations, ran no DeltaProcessor.run_cascade in the same transaction after it, so committing would leave the derived relations stale. Raised by the commit; the transaction is still open. store_ids names the stores that owe a cascade. The check shows a cascade was called, not that its watermark was right. A Store runs the cascade itself and never raises it.

exception zanzibar.UnloggedTuplesPresent

Bases: zanzibar.ZanzibarError, RuntimeError

A Store refused to open over a store id that already has tuples with no matching tuple-log rows, written by a standalone set engine before any Store claimed the id. The index, which is built from the log, would not see them. Open such a store with Store.adopt.

exception zanzibar.UnloggedWriteRefused

Bases: zanzibar.ZanzibarError, RuntimeError

A direct add_tuple / remove_tuple on a standalone SetEngine was refused because a Store owns that store id. Such a write would bypass the tuple log, so the index and every other instance would never see it. Write through the Store.

Outside the tree

exception zanzibar.InvariantViolation

Bases: AssertionError

A stored-state invariant does not hold: the index is corrupt. Raised by the runtime checks that the paranoia setting turns on (see Configuration). It is deliberately not a ZanzibarError, so a handler for refusals never swallows it; catch it explicitly if you catch it at all.

exception zanzibar.UnprovenExtensionWarning

Bases: UserWarning

A 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 per Store open (or zanzibar.parse_openfga_schema() / SetEngine call). Silence it with warnings.filterwarnings('ignore', category=zanzibar.UnprovenExtensionWarning).