optimize

package
v0.270.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 6, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package optimize analyses authorization models and proposes equivalence-preserving rewrites.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidModel = errors.New("invalid authorization model")

ErrInvalidModel is wrapped by NewModel when validation fails.

View Source
var ErrNoWeightedGraph = errors.New("weighted graph cannot be built")

ErrNoWeightedGraph is wrapped by Weights when OpenFGA's weighted graph cannot be built for the model (for example an AND or BUT NOT on a tuple cycle, or a tupleset type that lacks the relation).

Functions

func Dependents

func Dependents(m *Model, targets []string) map[string]bool

Dependents returns every relation ("type#rel") of m that can reach one of targets in the relation dependency graph, targets included.

func JSONWeights added in v0.270.0

func JSONWeights(in map[string]int) map[string]int

JSONWeights returns a fresh map with graph.Infinite replaced by -1; the input aliases the weighted graph's internal maps and must not be mutated.

func NoWeightedGraphReason

func NoWeightedGraphReason(err error) (string, bool)

NoWeightedGraphReason returns the builder's own message when err wraps ErrNoWeightedGraph, so the CLI and the TUI explain the failure identically.

func Unexercised

func Unexercised(m *Model, applied []Finding, skipped []string) []string

Unexercised returns the sorted, de-duplicated "type#relation" of every applied finding whose relation depends on a restriction the benchmark skipped (or is itself the skipped relation). skipped holds bench.Source notices of the form "type#relation: reason". Dependents are computed on the rewritten model (rw.After), since that is the model benchmarked.

func UnexercisedByChecks

func UnexercisedByChecks(m *Model, applied []Finding, checks []string) []string

UnexercisedByChecks returns the sorted, de-duplicated "type#relation" of every applied finding that no check reaches. A check on type#relation reaches a rewritten relation X when it is X itself or depends on X (is in Dependents(m, [X])). checks holds the checked "type#relation" keys, and m is the rewritten model, since that is the model benchmarked.

func UnifiedDiff

func UnifiedDiff(file, before, after string) string

UnifiedDiff diffs before/after line by line, labelled with the model file. go-udiff's own renderer emits a wrong +start on every hunk after the first, so the headers are recomputed here from the hunk lines.

func Weights

func Weights(m *Model) (map[string]map[string]int, error)

Weights returns, per "type#relation", the upstream weight of each user type. graph.Infinite is preserved.

Types

type Finding

type Finding struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Relation string `json:"relation"`
	Before   string `json:"before"`
	After    string `json:"after"`
	Reason   string `json:"reason"`
	Proof    string `json:"proof"`
	Tier     Tier   `json:"tier"`
	// Key is the serialized FindingKey, set by Analyze so JSON consumers can
	// correlate findings.
	Key string `` /* 142-byte string literal not displayed */
	// Weights maps user type to weight; Analyze substitutes -1 for
	// graph.Infinite here and the command renders -1 as "inf".
	Weights map[string]int `json:"weights" jsonschema_description:"Weight per user type; -1 means unbounded (infinite) weight."`
	// contains filtered or unexported fields
}

Finding is a single optimizer observation or rewrite.

type FindingKey

type FindingKey struct {
	Type, Relation, ID, Proof string
	N                         int
}

FindingKey identifies one applied finding by content. N only separates findings that are identical in every other field: it counts the earlier ones in the run.

func Keys

func Keys(applied []Finding) []FindingKey

Keys returns the key of each applied finding, in order.

func (FindingKey) String

func (k FindingKey) String() string

String renders the key as Type#Relation:ID:Proof, with #N appended when N > 0.

type GatedFinding

type GatedFinding struct {
	Finding
	Gate string `json:"gate" jsonschema_description:"Why the rewrite was not applied."`
}

GatedFinding is a safe rewrite that was derived but not applied because a safety gate rejected it.

type Lattice

type Lattice struct {
	// contains filtered or unexported fields
}

Lattice is a set of proven (A ⊆ B) pairs. Reflexivity is implicit.

Contract: A ⊆ B is recorded only when it holds for every subject of every kind, including userset subjects (obj#rel), on OpenFGA v1.22.1. See docs/superpowers/specs/2026-11-03-optimizer-soundness-design.md.

func BuildLattice

func BuildLattice(m *Model) *Lattice

BuildLattice computes the least fixpoint of the derivation rules: union member, alias, transitivity and TTU, starting from the empty set.

An alias `define r: s` proves only s ⊆ r, never r ⊆ s: the self-defining rule makes Check(obj#r, r, obj) true, while Check(obj#r, s, obj) is not.

func (*Lattice) Equivalent

func (l *Lattice) Equivalent(a, b Term) bool

Equivalent reports whether a ⊆ b and b ⊆ a.

func (*Lattice) Subset

func (l *Lattice) Subset(a, b Term) bool

Subset reports whether a ⊆ b is proven.

type Model

type Model struct{ Proto *openfgav1.AuthorizationModel }

Model wraps the proto with lookups the rewrite rules need.

func NewModel

func NewModel(p *openfgav1.AuthorizationModel) (*Model, error)

NewModel validates p and wraps it.

func (*Model) Clone

func (m *Model) Clone() *Model

Clone returns a deep copy.

func (*Model) DSL

func (m *Model) DSL() (string, error)

DSL renders the model as DSL.

func (*Model) DirectTypes

func (m *Model) DirectTypes(typ, rel string) []*openfgav1.RelationReference

DirectTypes returns the directly related user types of typ#rel.

func (*Model) Relation

func (m *Model) Relation(typ, rel string) (*openfgav1.Userset, bool)

Relation returns the rewrite of typ#rel.

type Report

type Report struct {
	// Findings lists safe findings (in Rewrite.Applied order), then caller,
	// then tuple findings; the latter two are sorted by type, relation, ID.
	Findings []Finding
	// Rewrite is nil when no safe findings were applied.
	Rewrite *RewriteResult
	// Blocked, when set, says why no safe rewrite could be applied.
	Blocked string
	// Gated lists safe rewrites that were derived but not applied, with the
	// gate reason; set even when Rewrite is nil.
	Gated []GatedFinding
}

Report is the full outcome of analysing a model.

func Analyze

func Analyze(p *openfgav1.AuthorizationModel) (*Report, error)

Analyze validates p, applies the safe rewrites and reports advisory findings computed on the rewritten model.

type RewriteResult

type RewriteResult struct {
	Applied []Finding
	Before  *Model // original, untouched
	After   *Model // rewritten and validated
	// Blocked, when set, says why no safe rewrite was applied at all.
	Blocked string
	// Gated lists the safe rewrites a safety gate rejected, with the gate
	// reason: those of the last pass that derived any findings; empty when
	// the final pass derived none.
	Gated []GatedFinding
}

RewriteResult is the outcome of applying the safe rules to a model.

func Rewrite

func Rewrite(m *Model) (*RewriteResult, error)

Rewrite applies the safe rules to fixpoint (at most 10 passes). At most one finding is applied per relation per pass, and the lattice is rebuilt from the current model each pass, so dependent drops are re-derived rather than assumed. A model with a recursive exclusion gets no rewrite at all (see recursiveExclusion), and a rewrite that changes whether OpenFGA can build the model's weighted graph is discarded. In a model with a conditioned or wildcard direct type, a rewrite that changes any relation's weight is discarded too: OpenFGA's weight-2 TTU fast path answers wrongly there. On every model, a rewrite that changes which resolver OpenFGA picks for any surviving edge (the four TypeSystem resolver predicates) is discarded.

RewriteSubset applies the same loop under the same gates but only for the findings the caller accepts.

func RewriteSubset

func RewriteSubset(m *Model, accept map[FindingKey]bool) (*RewriteResult, error)

RewriteSubset is Rewrite restricted to the findings named in accept. A nil or empty map accepts nothing. Every gate of Rewrite still applies, so an accepted finding is skipped if it would be unsafe in this combination.

type Term

type Term struct {
	Type     string
	Computed string // relation name
	TTU      *struct{ Tupleset, Computed string }
	// Direct is a canonical key: "<owning relation>:" followed by the sorted
	// directly related types ("type", "type#rel", "type:*"), each suffixed
	// " with <cond>" when conditioned.
	//
	// SOUNDNESS: a direct term denotes the tuples stored under ITS OWN
	// relation, so the owning relation is part of its identity. doc#a: [user]
	// and doc#b: [user] are DIFFERENT terms.
	Direct string
}

Term is a userset term scoped to a type. Exactly one of Computed/TTU/Direct is set.

func TermOf

func TermOf(typ, rel string, us *openfgav1.Userset, md *openfgav1.RelationMetadata) (Term, bool)

TermOf converts the rewrite us of typ#rel into a Term; md is the metadata of typ#rel. It returns false for union/intersection/difference (and any other composite rewrite).

type Tier

type Tier string

Tier classifies how a finding may be acted on.

const (
	// TierSafe findings are equivalence-preserving rewrites.
	TierSafe Tier = "safe"
	// TierCaller findings require a change in how callers use the model.
	TierCaller Tier = "caller"
	// TierTuple findings require a change in stored tuples.
	TierTuple Tier = "tuple"
)

Directories

Path Synopsis
Package bench synthesizes tuples and checks from an authorization model and benchmarks the checks against a before and an after model on a counting embedded OpenFGA server.
Package bench synthesizes tuples and checks from an authorization model and benchmarks the checks against a before and an after model on a counting embedded OpenFGA server.
Package benchfmt renders a bench.Result as the human-readable benchmark report shared by the CLI and the playground.
Package benchfmt renders a bench.Result as the human-readable benchmark report shared by the CLI and the playground.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL