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_reversereturn (also viaStore).node_ids: ids ofzanzibar.graphindex.Noderows in this store.Store.result_keys(result)turns them into(type, name, predicate)keys,predicatebeing the relation or"..."for a bare subject. Intermediate usersets (group:eng#member) are included. Fromlookup_reverse, a userset in the result means the userset ITSELF is an allowed subject; it is not a claim about each member (underbut not banneda banned member stays refused), so askcheckabout a member instead of expanding the userset.markers: wildcard grants as(type, predicate, variant). Variant"any"is subject-side: fromlookup_reverse,("user", "...", "any")means every user (a[user:*]tuple). Variant"all"is object-side and appears only withobject_wildcard_shapes(an extension): fromlookup,("doc", "reader", "all")means reader of every doc (adoc:*tuple). An"all"marker fromlookup_reverse, or an"any"marker fromlookup, 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 makesdoc:1#viewera viewer ofdoc:1on an empty store, and the index never creates a node to say so.Store.result_keys/excluded_keysfold them in, so read a result through those.
A subject that a marker already covers may also appear in
node_ids; the set engine’sSetLookupResultleaves 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:
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
ReachabilityIndexidx, for the schema whosezanzibar.schema.RuleSet.schema_infoisschema_info. It handles wildcard subjects and objects, and relations that useand/but not(which aDeltaProcessormaintains). It never commits: the caller commits the session.- idx: ReachabilityIndex¶
The underlying index.
idx.store_idis 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 throughRuleSet.applyfirst.
- 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 raisesAdmissionRejected.
- 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:Storedoes, before it reaches the index, and raisesUndeclaredTypeOrRelationfor an undeclared type or relation incheck,lookup,lookup_reverseandexpand, as the set engine does.lookup,lookup_reverseandfilter_resulthere 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 inexcluded_node_ids.
- filter_result(res, entity_type=None, predicate=None) zanzibar.LookupResult¶
A copy of a
lookup()orlookup_reverse()result that keeps only the entries (node ids, markers, excluded ids and implicit keys) whose(type, predicate)matches every filter given. With both filtersNoneit returnsresitself. Use it before the next write: an id whose node is gone raisesStaleLookupIds.
- 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 anand/but notrelation’s stored state refers to, and a node of a shape that the schema’s rewrites store copies of.
- class zanzibar.graphindex.ReachabilityIndex(session, store_id, *, max_closure_fanout=None)¶
The stored transitive closure for one store id, read and written through
session. AWildcardIndexwraps one; its remaining methods are the closure’s low-level node and edge operations, whichWildcardIndexcalls and which are not documented here.max_closure_fanoutcaps how many closure rows one edge addition may create (ClosureFanoutExceededabove it).Nonereads theZANZIBAR_MAX_CLOSURE_FANOUTenvironment variable, and falls back to 100,000 when it is unset or empty.0disables the cap. A negative value, or an environment value that is not an integer, raisesValueError. The value is fixed when the index is constructed. See Configuration.- fanout_cap_suspended()¶
A context manager. Inside it, edge additions in the current thread that exceed
max_closure_fanoutare 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 asprocwhen you drive the apply step yourself; aStorebuilds and runs its own, so most programs never touch it. A pure-union schema (noand/but not) needs none.- Parameters:
widx (WildcardIndex)
compiled (CompiledBooleans)
- run_cascade(txn_start_watermark) None¶
Bring every
and/but notrelation up to date with the edge writes made in this transaction.txn_start_watermarkisoutbox_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 neitherrun_cascadenorbackfillran after that write, the commit raiseszanzibar.CascadeNotRun; that check shows a cascade was called, not that it was called with the right watermark.
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.
- 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 isoutbox_watermark()read after the last commit. Rows abovebefore_watermarkare never touched. The newest row is always kept, so outbox ids keep increasing andoutbox_watermark()returns the same value after a prune. A negativebefore_watermarkraisesValueError. 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_storetable: one per graph index store id. Columns:id,description,created_at.
- class zanzibar.graphindex.Node¶
A row of the
zanzibar_nodetable: 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_edgetable: 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.