zanzibar.graphindex

The graph index precomputes who can reach what, so a check is a few indexed lookups whatever the size of the data, and writes pay to keep that precomputation current. A zanzibar.Store owns one and keeps it in step with the tuple log; use this package directly only to drive the graph index on its own, as described in Use the backends directly.

Lookup results

LookupResult is importable from both zanzibar and zanzibar.graphindex; it is documented here under its top-level name. The marker and exclusion fields are summarised on the Python API page.

class zanzibar.LookupResult(node_ids=<factory>, markers=<factory>, excluded_node_ids=<factory>, implicit_keys=<factory>, implicit_excluded_keys=<factory>)

What lookup / lookup_reverse return (also via Store).

  • node_ids: ids of zanzibar.graphindex.Node rows in this store. Store.result_keys(result) turns them into (type, name, predicate) keys, predicate being the relation or "..." for a bare subject. Intermediate usersets (group:eng#member) are included. From lookup_reverse, a userset in the result means the userset ITSELF is an allowed subject; it is not a claim about each member (under but not banned a banned member stays refused), so ask check about a member instead of expanding the userset.

  • markers: wildcard grants as (type, predicate, variant). Variant "any" is subject-side: from lookup_reverse, ("user", "...", "any") means every user (a [user:*] tuple). Variant "all" is object-side and appears only with object_wildcard_shapes (an extension): from lookup, ("doc", "reader", "all") means reader of every doc (a doc:* tuple). An "all" marker from lookup_reverse, or an "any" marker from lookup, is a by-product of how wildcards are stored and carries no claim on its own.

  • excluded_node_ids: node ids a marker would cover but that are refused (but not). The caller subtracts them: “every user except these”. Store.excluded_keys(result) gives their keys.

  • implicit_keys / implicit_excluded_keys: the same two parts for answers that have NO node, as (type, name, predicate) keys. OpenFGA’s implicit userset self-relation makes doc:1#viewer a viewer of doc:1 on an empty store, and the index never creates a node to say so. Store.result_keys / excluded_keys fold them in, so read a result through those.

A subject that a marker already covers may also appear in node_ids; the set engine’s SetLookupResult leaves it out. Compare results by what they cover (the keys, plus every subject of a marker’s shape, minus the excluded keys), not as raw sets.

Parameters:
node_ids: set[int]

Ids of Node rows.

markers: set[tuple[str, str, str]]

Wildcard grants as (type, predicate, variant) triples.

excluded_node_ids: set[int]

Node ids a marker would cover but that are refused.

implicit_keys: set[tuple[str, str, str]]

Results that have no node, as (type, name, predicate) keys.

implicit_excluded_keys: set[tuple[str, str, str]]

Exclusions that have no node, as keys.

The index

In the method signatures below, subject_predicate is "..." (or Ellipsis) for a bare subject such as a user, or the relation of a userset subject ("member" for group:eng#member).

WildcardIndex takes a zanzibar.schema.SchemaInfo and DeltaProcessor a zanzibar.schema.CompiledBooleans. Take both from a compiled RuleSet (ruleset.schema_info, ruleset.compiled) rather than building them yourself.

class zanzibar.graphindex.WildcardIndex(idx, schema_info)

The graph index, on top of a ReachabilityIndex idx, for the schema whose zanzibar.schema.RuleSet.schema_info is schema_info. It handles wildcard subjects and objects, and relations that use and / but not (which a DeltaProcessor maintains). It never commits: the caller commits the session.

idx: ReachabilityIndex

The underlying index. idx.store_id is the store id.

add_tuple(subject_predicate, subject_type, subject_name, relation, object_type, object_name) → None

Add one edge produced by zanzibar.schema.RuleSet.apply(). Edges are counted: adding the same edge twice takes two removes to undo. This is not a raw-tuple write; deduplicate raw tuples yourself, and route each one through RuleSet.apply first.

remove_tuple(subject_predicate, subject_type, subject_name, relation, object_type, object_name) → None

Remove one count of an edge added with add_tuple(). Removing an edge whose endpoints the index has never seen raises AdmissionRejected.

check(subject_predicate, subject_type, subject_name, relation, object_type, object_name) → bool

Is the subject related to the object? A relation name the schema does not declare answers False; it does not raise. The graph index does not check reads against the schema: Store does, before it reaches the index, and raises UndeclaredTypeOrRelation for an undeclared type or relation in check, lookup, lookup_reverse and expand, as the set engine does. lookup, lookup_reverse and filter_result here answer an undeclared name with an empty result.

lookup(subject_predicate, subject_type, subject_name) → zanzibar.LookupResult

Everything the subject can reach. Wildcard objects reached become markers, never listed one by one.

lookup_reverse(relation, object_type, object_name) → zanzibar.LookupResult

Everything that can reach the object with relation. Wildcard subjects become markers, and the subjects a marker covers but that are refused are in excluded_node_ids.

filter_result(res, entity_type=None, predicate=None) → zanzibar.LookupResult

A copy of a lookup() or lookup_reverse() result that keeps only the entries (node ids, markers, excluded ids and implicit keys) whose (type, predicate) matches every filter given. With both filters None it returns res itself. Use it before the next write: an id whose node is gone raises StaleLookupIds.

remove_node(predicate, entity_type, name) → None

Remove a node and all its edges. It raises AdmissionRejected, and changes nothing, for a node that does not exist, a wildcard node (name "*"), a node that an and / but not relation’s stored state refers to, and a node of a shape that the schema’s rewrites store copies of.

backfill() → None

Create any wildcard bookkeeping missing for the nodes already stored. Idempotent.

class zanzibar.graphindex.ReachabilityIndex(session, store_id, *, max_closure_fanout=None)

The stored transitive closure for one store id, read and written through session. A WildcardIndex wraps one; its remaining methods are the closure’s low-level node and edge operations, which WildcardIndex calls and which are not documented here.

max_closure_fanout caps how many closure rows one edge addition may create (ClosureFanoutExceeded above it). None reads the ZANZIBAR_MAX_CLOSURE_FANOUT environment variable, and falls back to 100,000 when it is unset or empty. 0 disables the cap. A negative value, or an environment value that is not an integer, raises ValueError. The value is fixed when the index is constructed. See Configuration.

store_id: str
max_closure_fanout: int

The cap in force (0 when disabled).

fanout_cap_suspended()

A context manager. Inside it, edge additions in the current thread that exceed max_closure_fanout are applied with a logged warning instead of being refused. The path-count limit (PathCountExceeded) still applies. It can be nested, and restores the previous setting on exit.

class zanzibar.graphindex.DeltaProcessor(widx, compiled)

Maintains a WildcardIndex’s derived (and / but not) relations.

The graph index stores the leaf relations a write touches; every boolean relation is derived from them, and this processor keeps it current by reading the index’s outbox and re-deriving what changed. Build one per index as DeltaProcessor(widx, ruleset.compiled) and pass it as proc when you drive the apply step yourself; a Store builds and runs its own, so most programs never touch it. A pure-union schema (no and / but not) needs none.

Parameters:
run_cascade(txn_start_watermark) → None

Bring every and / but not relation up to date with the edge writes made in this transaction. txn_start_watermark is outbox_watermark() read before those writes. Call it in the same transaction, after the writes and before the commit. If the transaction wrote to the index and neither run_cascade nor backfill ran after that write, the commit raises zanzibar.CascadeNotRun; that check shows a cascade was called, not that it was called with the right watermark.

backfill(chunk_size=200) → None

Rebuild every derived relation from the edges already stored. Idempotent; use it to bootstrap a processor on an existing index, or to repair derived state.

Outbox retention

Every change in reachability writes a row to the zanzibar_delta_outbox table, which the delta processor reads. Nothing deletes those rows for you.

zanzibar.graphindex.outbox_watermark(session, store_id)

Highest outbox id for the store (0 if empty) – the keyset cursor.

Parameters:
  • session (Session)

  • store_id (str)

Return type:

int

zanzibar.graphindex.prune_outbox(session, store_id, before_watermark) → int

Delete this store’s outbox rows with an id at or below before_watermark, and return how many were deleted. Pass the lowest outbox position any reader of the outbox still needs; with one synchronous cascade per write, that is outbox_watermark() read after the last commit. Rows above before_watermark are never touched. The newest row is always kept, so outbox ids keep increasing and outbox_watermark() returns the same value after a prune. A negative before_watermark raises ValueError. The library never calls this. It does not commit: run it in its own transaction and commit.

Tables

The tables these row classes map are listed on the Database tables page.

class zanzibar.graphindex.IndexStore

A row of the zanzibar_store table: one per graph index store id. Columns: id, description, created_at.

class zanzibar.graphindex.Node

A row of the zanzibar_node table: an entity, a userset or a relation on an object. Columns: id, store_id, predicate, type, name, wildcard, implicit, reference_count.

class zanzibar.graphindex.Edge

A row of the zanzibar_edge table: one pair in the precomputed closure, with its reference counts. Columns: id, store_id, subject_id, object_id, direct_edge_count, indirect_edge_count, derived.

Exceptions

zanzibar.graphindex exports no exceptions. Import them from zanzibar; they are documented on the Exceptions page. The graph index raises, among others, AdmissionRejected, ClosureFanoutExceeded, PathCountExceeded, StaleLookupIds, WriteLockUnsafe, CascadeNotRun and InvariantViolation.