Documentation
¶
Overview ¶
Package egraphcore defines backend-neutral graph storage and matching, typed relations, incremental joins, fact actions, prepared rewrite application, schedules, extraction, candidate graph algorithms and search coordination, analysis propagation, cost and budget primitives, and fixed-point execution shared by e-graph implementations. Backends provide node and class representations, rewrite rules, legality checks, analysis semantics, costs, and code generation.
Index ¶
- Variables
- func ASTSizeCost(childCosts []float64) float64
- func CanonicalChildIDs[ID ~uint32](parent []ID, children []ID) []ID
- func ChildCosts[ID comparable](children []ID, costs map[ID]float64) ([]float64, bool)
- func CountInternalChildren[ID ~uint32](children []ID, component map[ID]bool) int
- func CyclicComponents[ID ~uint32](adj map[ID][]ID, reachable map[ID]bool) [][]ID
- func EvaluateNodeCost[Node any](model CostModel[Node], node Node, childCosts []float64, ...) float64
- func ExtractBestAdditive[ID ~uint32, Node any](root ID, nodes func(ID) []Node, canonical func(ID) ID, ...) (map[ID]AdditiveBestCostNode[Node], int, error)
- func ExtractBestAdditiveFromRoots[ID ~uint32, Node any](roots []ID, nodes func(ID) []Node, canonical func(ID) ID, ...) (map[ID]AdditiveBestCostNode[Node], int, error)
- func Find[ID ~uint32](parent []ID, id ID) ID
- func FindMemoCandidate[ID ~uint32, Node any](candidates []ID, want Node, find func(ID) ID, classNodes func(ID) []Node, ...) (ID, bool, error)
- func FindMemoCandidateIter[ID ~uint32, Node any](visitCandidates func(func(ID) bool), want Node, find func(ID) ID, ...) (ID, bool, error)
- func FindMemoCandidateIterWithBudget[ID ~uint32, Node any](visitCandidates func(func(ID) bool), want Node, find func(ID) ID, ...) (ID, bool, error)
- func LinkRoots[ID ~uint32](parent []ID, root1, root2, newRoot ID) (ID, bool)
- func MatchEClass[ID comparable, Node any](pattern *Pattern, classID ID, current map[string]ID, budget *WorkBudget, ...) ([]map[string]ID, error)
- func MatchEClassWithMatcher[ID comparable, Node, P any](pattern P, classID ID, current map[string]ID, budget *WorkBudget, ...) ([]map[string]ID, error)
- func MaterializeChoice[ID ~uint32, Node, Value any](root ID, choice map[ID]int, alternatives func(ID) []Node, ...) (Value, error)
- func MutateDiscreteChoice(genome []int, genes []DiscreteChoiceGene, mutationCount int, rng IntnSource) ([]int, error)
- func PlanJoinOrder(boundVariables []string, conditions []JoinOrderCondition, budget *WorkBudget) ([]int, error)
- func PropagateAnalysis[ID ~uint32, Node any](seeds []ID, ops AnalysisPropagation[ID, Node]) error
- func PruneEmptyAlternatives[ID ~uint32, Node any](alternatives map[ID][]Node, children func(Node) []ID) (map[ID][]Node, error)
- func RelaxBestCosts[ID ~uint32, Node any](classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, ...) (map[ID]BestCostNode[Node], int, error)
- func RelaxBestCostsWorklist[ID ~uint32, Node, Rank any](classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, ...) (map[ID]RankedBestCostNode[Node, Rank], int, error)
- func RelaxBestCostsWorklistWithBudget[ID ~uint32, Node, Rank any](classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, ...) (output map[ID]RankedBestCostNode[Node, Rank], visits int, err error)
- func RepairChoiceCycles[ID ~uint32, Node any](root ID, choice map[ID]int, alternatives func(ID) []Node, ...) (map[ID]int, error)
- func SelectedChoiceGraph[ID ~uint32, Node any](root ID, choice map[ID]int, alternatives func(ID) []Node, ...) (map[ID][]ID, map[ID]bool, error)
- func SelectedChoiceMatches[ID ~uint32, Node any, Value comparable](root ID, choice map[ID]int, alternatives func(ID) []Node, ...) bool
- func StructuralFingerprint(op, sort string, data any, children []string) string
- func ValidateMonotoneCost(cost float64, childCosts []float64) error
- func ValidateSchedule[R any](schedule *Schedule[R], validateRule ScheduleRuleValidator[R]) error
- func ValueFingerprint(value any) (string, bool)
- func WouldCreateCycle[ID comparable, Node any](owner ID, childIDs []ID, canonicalize func(ID) ID, ...) bool
- func WouldCreateCycleWithBudget[ID comparable, Node any](owner ID, childIDs []ID, canonicalize func(ID) ID, ...) (cycle bool, err error)
- func WouldCreateCycleWithVisit[ID comparable, Node any](owner ID, childIDs []ID, canonicalize func(ID) ID, ...) (bool, error)
- type AdditiveBestCostNode
- type AnalysisPropagation
- type Atom
- type BestCostNode
- type Binding
- func Join[ID ~uint32](atoms []Atom[ID], canonicalize func(ID) ID, budget *WorkBudget) (results []Binding[ID], complete bool, err error)
- func JoinBindings[ID ~uint32](left, right []Binding[ID], rightKeys []string, canonicalize func(ID) ID, ...) (results []Binding[ID], complete bool, err error)
- func JoinDeltas[ID ~uint32](atoms []Atom[ID], deltas []DeltaAtom[ID], canonicalize func(ID) ID, ...) (results []Binding[ID], complete bool, err error)
- type CandidateLattice
- func (l *CandidateLattice[T]) Accept(set *CandidateLatticeSet[T]) error
- func (l *CandidateLattice[T]) Attempts() int
- func (l *CandidateLattice[T]) LastRejection() string
- func (l *CandidateLattice[T]) LimitReached() bool
- func (l *CandidateLattice[T]) Next() (*CandidateLatticeSet[T], bool, error)
- func (l *CandidateLattice[T]) Reject(set *CandidateLatticeSet[T], reason string) error
- func (l *CandidateLattice[T]) SearchExpired() bool
- func (l *CandidateLattice[T]) SetTimeouts(searchTimeout, candidateTimeout time.Duration) error
- func (l *CandidateLattice[T]) StopReason() string
- func (l *CandidateLattice[T]) TimedOut(set *CandidateLatticeSet[T]) bool
- func (l *CandidateLattice[T]) ValidateNext(validate func(*CandidateLatticeSet[T]) error) (*CandidateLatticeSet[T], bool, error)
- type CandidateLatticeBucket
- type CandidateLatticeFinalist
- type CandidateLatticeSet
- type ChoiceFingerprint
- type ChoiceFingerprintBuild
- type ChoiceFingerprinter
- type ChoiceMaterializer
- type ChoiceSpace
- type Column
- type CongruencePlan
- func ApplyCongruencePass[ID ~uint32, Node any, Key comparable](graph Graph[ID, Node], owned []OwnedNode[ID, Node], key func(Node) Key, ...) (CongruencePlan[ID, Node], int, error)
- func PlanCongruencePass[ID comparable, Node any, Key comparable](owned []OwnedNode[ID, Node], key func(Node) Key, equal func(Node, Node) bool, ...) (CongruencePlan[ID, Node], error)
- type CongruenceReport
- type CostEvaluation
- type CostModel
- type CostVisit
- type CycleVisit
- type DeltaAtom
- type DiscreteChoiceGene
- type FactAction
- type FactActionKind
- type FactStore
- func (s *FactStore[ID]) Add(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (s *FactStore[ID]) ApplyActions(actions []ResolvedFactAction[ID], canonicalize func(ID) ID, budget *WorkBudget) (int, error)
- func (s *FactStore[ID]) ApplyActionsDetailed(actions []ResolvedFactAction[ID], canonicalize func(ID) ID, budget *WorkBudget) ([]bool, int, error)
- func (s *FactStore[ID]) CanonicalCopyWithBudget(canonicalize func(ID) ID, budget *WorkBudget) (*FactStore[ID], error)
- func (s *FactStore[ID]) Clone() *FactStore[ID]
- func (s *FactStore[ID]) CloneWithBudget(budget *WorkBudget) (*FactStore[ID], error)
- func (s *FactStore[ID]) Delete(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (s *FactStore[ID]) Get(name string) *Relation[ID]
- func (s *FactStore[ID]) MarkSubsumed(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (s *FactStore[ID]) Recanonicalize(canonicalize func(ID) ID) error
- func (s *FactStore[ID]) RecanonicalizeWithBudget(canonicalize func(ID) ID, budget *WorkBudget) error
- func (s *FactStore[ID]) Register(schema Schema) (*Relation[ID], error)
- func (s *FactStore[ID]) ReplaceFrom(other *FactStore[ID], budget *WorkBudget) error
- func (s *FactStore[ID]) TupleCount() int
- type Filter
- type FunctionMergeCallbacks
- type FunctionMergePolicy
- type Graph
- type IntnSource
- type JoinOrderCondition
- type Match
- type MatcherCallbacks
- type MeasuredCandidate
- type MeasuredSearch
- func (s *MeasuredSearch[T]) Best() (MeasuredCandidate[T], bool)
- func (s *MeasuredSearch[T]) CloseGeneration(remaining int)
- func (s *MeasuredSearch[T]) Generation() int
- func (s *MeasuredSearch[T]) MutationLimit(base int) int
- func (s *MeasuredSearch[T]) ParentFor(position int) (MeasuredCandidate[T], bool)
- func (s *MeasuredSearch[T]) Parents() bool
- func (s *MeasuredSearch[T]) Ranking() []MeasuredCandidate[T]
- func (s *MeasuredSearch[T]) Record(candidate MeasuredCandidate[T]) (bool, error)
- func (s *MeasuredSearch[T]) Resample() bool
- type MeasuredSearchConfig
- type Memory
- type MemoryScope
- type OrderedRow
- type OrderedTable
- func (t *OrderedTable[ID, Row]) Clone() *OrderedTable[ID, Row]
- func (t *OrderedTable[ID, Row]) Contains(column int, value Value[ID], key string) bool
- func (t *OrderedTable[ID, Row]) Counters() (order, fresh uint64)
- func (t *OrderedTable[ID, Row]) Delete(key string) bool
- func (t *OrderedTable[ID, Row]) Get(key string) (OrderedRow[ID, Row], bool)
- func (t *OrderedTable[ID, Row]) Len() int
- func (t *OrderedTable[ID, Row]) MarkSubsumed(key string) bool
- func (t *OrderedTable[ID, Row]) Put(key string, values []Value[ID], payload Row) (inserted bool, ok bool)
- func (t *OrderedTable[ID, Row]) PutAt(key string, values []Value[ID], payload Row, order uint64, subsumed bool) bool
- func (t *OrderedTable[ID, Row]) Range(column int, value Value[ID], visit func(string) bool) bool
- func (t *OrderedTable[ID, Row]) ReplaceFrom(other *OrderedTable[ID, Row]) bool
- func (t *OrderedTable[ID, Row]) Rows() []OrderedRow[ID, Row]
- func (t *OrderedTable[ID, Row]) SetCounters(order, fresh uint64)
- type OwnedNode
- type OwnerPair
- type Pattern
- type RankedBestCostLookup
- type RankedBestCostNode
- type RankedCostAcceptance
- type RankedCostEvaluation
- type Relation
- func (r *Relation[ID]) Add(values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (r *Relation[ID]) AddedSince(cursor RelationCursor) ([][]Value[ID], error)
- func (r *Relation[ID]) AddedSinceWithBudget(cursor RelationCursor, budget *WorkBudget) (rows [][]Value[ID], complete bool, err error)
- func (r *Relation[ID]) Clone() *Relation[ID]
- func (r *Relation[ID]) Compact(cursor RelationCursor) error
- func (r *Relation[ID]) Delete(values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (r *Relation[ID]) Len() int
- func (r *Relation[ID]) MarkSubsumed(values []Value[ID], canonicalize func(ID) ID) (bool, error)
- func (r *Relation[ID]) Query(filters []Filter[ID], canonicalize func(ID) ID, budget *WorkBudget) (rows [][]Value[ID], complete bool, err error)
- func (r *Relation[ID]) Recanonicalize(canonicalize func(ID) ID) error
- func (r *Relation[ID]) Rows() [][]Value[ID]
- func (r *Relation[ID]) Schema() Schema
- func (r *Relation[ID]) SchemaWithBudget(budget *WorkBudget) (Schema, error)
- func (r *Relation[ID]) Snapshot() RelationCursor
- type RelationCursor
- type ResolvedFactAction
- type RewriteApplicationReport
- type RootPairStatus
- type RuleMatch
- func JoinMatches[ID ~uint32](anchors []Match[ID], structuralConditions [][]Match[ID], ...) ([]RuleMatch[ID], error)
- func JoinMatchesDeltas[ID ~uint32](anchors []Match[ID], structuralConditions [][]Match[ID], atoms []Atom[ID], ...) ([]RuleMatch[ID], error)
- func JoinMatchesWithBindings[ID ~uint32](anchors []Match[ID], structuralConditions [][]Match[ID], ...) (output []RuleMatch[ID], err error)
- type SaturationLimits
- type SaturationPass
- type SaturationResult
- type SaturationStopReason
- type Schedule
- func Repeat[R any](count int, child *Schedule[R]) *Schedule[R]
- func RepeatNamed[R any](name string, count int, child *Schedule[R]) *Schedule[R]
- func Run[R any](name string, rules ...R) *Schedule[R]
- func Saturate[R any](child *Schedule[R]) *Schedule[R]
- func SaturateNamed[R any](name string, child *Schedule[R]) *Schedule[R]
- func Sequence[R any](children ...*Schedule[R]) *Schedule[R]
- func SequenceNamed[R any](name string, children ...*Schedule[R]) *Schedule[R]
- type ScheduleResult
- type ScheduleRuleValidator
- type ScheduleRun
- type ScheduleRunReport
- type Schema
- type Store
- func (s *Store[ID, Class]) AddMemoCandidate(key string, id ID)
- func (s *Store[ID, Class]) AddMemoCandidateIf(key string, id ID, same func(ID, ID) bool) bool
- func (s *Store[ID, Class]) AddMemoCandidateIfWithBudget(key string, id ID, same func(ID, ID) bool, budget *WorkBudget) (bool, error)
- func (s *Store[ID, Class]) CanonicalChildren(children []ID) []ID
- func (s *Store[ID, Class]) Class(id ID) Class
- func (s *Store[ID, Class]) ClassCount() int
- func (s *Store[ID, Class]) Clone(cloneClass func(Class) Class) *Store[ID, Class]
- func (s *Store[ID, Class]) CloneWithBudget(cloneClass func(Class, *WorkBudget) (Class, error), budget *WorkBudget) (*Store[ID, Class], error)
- func (s *Store[ID, Class]) Find(id ID) ID
- func (s *Store[ID, Class]) FindWithoutCompression(id ID, maxVisits int) (root ID, visits int, ok bool)
- func (s *Store[ID, Class]) Initialized() bool
- func (s *Store[ID, Class]) Insert(key string, newClass func(ID) Class) (ID, bool)
- func (s *Store[ID, Class]) InsertWithBudget(key string, newClass func(ID) (Class, error), budget *WorkBudget) (ID, error)
- func (s *Store[ID, Class]) Len() int
- func (s *Store[ID, Class]) LinkRoots(root1, root2, winner ID) (ID, bool)
- func (s *Store[ID, Class]) LinkRootsBySize(root1, root2 ID) (ID, bool)
- func (s *Store[ID, Class]) LookupClass(id ID) (Class, bool)
- func (s *Store[ID, Class]) MergeRoots(root1, root2, winner ID, merge func(Class, Class) Class) (ID, bool)
- func (s *Store[ID, Class]) MergeRootsBySize(root1, root2 ID, merge func(Class, Class) Class) (ID, bool)
- func (s *Store[ID, Class]) Parent(id ID) (ID, bool)
- func (s *Store[ID, Class]) RangeClasses(visit func(ID, Class) bool)
- func (s *Store[ID, Class]) ResetMemo()
- func (s *Store[ID, Class]) ResolveRoots(id1, id2 ID) (ID, ID, RootPairStatus)
- func (s *Store[ID, Class]) VisitMemoCandidates(key string, visit func(ID) bool)
- type Term
- type TermKind
- type TopKBuild
- type TopKCandidate
- func ExtractTopK[ID ~uint32, Node, Value any](root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, ...) ([]TopKCandidate[Value], error)
- func ExtractTopKWithChildPreservation[ID ~uint32, Node, Value any](root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, ...) ([]TopKCandidate[Value], error)
- func ExtractTopKWithChildPreservationAndHash[ID ~uint32, Node, Value any](root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, ...) ([]TopKCandidate[Value], error)
- func ExtractTopKWithHash[ID ~uint32, Node, Value any](root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, ...) ([]TopKCandidate[Value], error)
- type TopKNodeEligible
- type Value
- func BigInt[ID ~uint32](v string) Value[ID]
- func BigRat[ID ~uint32](v string) Value[ID]
- func Bool[ID ~uint32](v bool) Value[ID]
- func Class[ID ~uint32](id ID) Value[ID]
- func Float64[ID ~uint32](v float64) Value[ID]
- func Int64[ID ~uint32](v int64) Value[ID]
- func MergeFunctionValue[ID ~uint32](policy FunctionMergePolicy, old, incoming, constant Value[ID], ...) (Value[ID], error)
- func String[ID ~uint32](v string) Value[ID]
- func Unit[ID ~uint32]() Value[ID]
- type ValueIndex
- func (index *ValueIndex[ID]) Add(row []Value[ID], key string) bool
- func (index *ValueIndex[ID]) Clone() *ValueIndex[ID]
- func (index *ValueIndex[ID]) Contains(column int, value Value[ID], key string) bool
- func (index *ValueIndex[ID]) Count(column int, value Value[ID]) int
- func (index *ValueIndex[ID]) Range(column int, value Value[ID], visit func(string) bool) bool
- func (index *ValueIndex[ID]) Remove(row []Value[ID], key string) bool
- type ValueKind
- type WorkBudget
Examples ¶
- DriveCongruenceWithBudget
- FactStore.CanonicalCopyWithBudget
- FactStore.CloneWithBudget
- FactStore.RecanonicalizeWithBudget
- FindMemoCandidateIterWithBudget
- MemoryScope
- NewWorkBudgetWithMemory
- Relation.SchemaWithBudget
- RelaxBestCostsWorklistWithBudget
- Store.AddMemoCandidateIfWithBudget
- Store.CloneWithBudget
- Store.InsertWithBudget
- WouldCreateCycleWithBudget
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidFunctionMerge reports an invalid policy, value kind, or missing callback. ErrInvalidFunctionMerge = errors.New("egraphcore: invalid function merge") // ErrConflictingFunctionResults reports unequal results under assert-equal policy. ErrConflictingFunctionResults = errors.New("egraphcore: conflicting function results") )
var ( // ErrInvalidSaturationInput reports a nil budget or pass callback. ErrInvalidSaturationInput = errors.New("egraphcore: invalid saturation input") // ErrIncompleteSaturationPass reports a pass that returned incomplete before // its work budget was exhausted. ErrIncompleteSaturationPass = errors.New("egraphcore: incomplete pass without exhausted work budget") // ErrSaturationCounterOverflow reports an unrepresentable changes or // iteration count. ErrSaturationCounterOverflow = errors.New("egraphcore: saturation counter overflow") )
var ( // ErrInvalidSchedule reports a malformed schedule or missing callback. ErrInvalidSchedule = errors.New("egraphcore: invalid schedule") // ErrScheduleCounterOverflow reports an unrepresentable run or change count. ErrScheduleCounterOverflow = errors.New("egraphcore: schedule counter overflow") )
var ErrAdditiveExtractionWorkLimit = errors.New("egraphcore: additive extraction work limit exceeded")
ErrAdditiveExtractionWorkLimit reports that additive extraction exhausted its node and edge work limit.
var ErrAdditiveNegativeCycle = errors.New("egraphcore: reachable negative-cost cycle")
ErrAdditiveNegativeCycle reports a reachable cycle whose additive local costs make the total unbounded below.
var ErrAdditiveUnresolved = errors.New("egraphcore: unresolved additive extraction root")
ErrAdditiveUnresolved reports that the requested root has no finite acyclic derivation.
var ErrChoiceFingerprintLimit = errors.New("egraphcore: choice fingerprint size limit exceeded")
ErrChoiceFingerprintLimit reports that a selected node's fingerprint input is too large.
var ErrChoiceFingerprintWorkBudget = errors.New("egraphcore: choice fingerprint work budget exceeded")
ErrChoiceFingerprintWorkBudget reports exhausted work budget during hashing.
var ErrCongruencePassLimit = errors.New("egraphcore: congruence pass limit exceeded")
ErrCongruencePassLimit reports that the driver exhausted its pass bound before the policy callbacks reached a stable result.
var ErrCostRelaxationLimit = errors.New("egraphcore: cost relaxation limit exceeded")
ErrCostRelaxationLimit reports that cost relaxation reached its pass or node visit limit before reaching a fixed point.
var ErrInvalidAdditiveExtraction = errors.New("egraphcore: invalid additive extraction")
ErrInvalidAdditiveExtraction reports missing callbacks or an invalid work limit.
var ErrInvalidAnalysisPropagation = errors.New("egraphcore: invalid analysis propagation")
ErrInvalidAnalysisPropagation reports a missing callback for analysis propagation.
var ErrInvalidChoiceGraph = errors.New("egraphcore: invalid selected choice graph")
ErrInvalidChoiceGraph reports an incomplete or invalid selected choice.
var ErrInvalidCongruenceDriver = errors.New("egraphcore: invalid congruence driver")
ErrInvalidCongruenceDriver reports a missing callback for a congruence driver.
var ErrInvalidCongruencePass = errors.New("egraphcore: invalid congruence pass")
ErrInvalidCongruencePass reports missing callbacks for a congruence pass.
var ErrInvalidCostRelaxation = errors.New("egraphcore: invalid cost relaxation")
ErrInvalidCostRelaxation reports missing callbacks or an invalid pass bound.
var ErrInvalidFactAction = errors.New("egraphcore: invalid fact action")
ErrInvalidFactAction reports a malformed action or missing variable.
var ErrInvalidJoin = errors.New("egraphcore: invalid relation join")
ErrInvalidJoin reports an invalid atom or binding join.
var ErrInvalidMemoLookup = errors.New("egraphcore: invalid memo lookup")
ErrInvalidMemoLookup reports missing callbacks for a memo candidate lookup.
var ErrInvalidPattern = errors.New("egraphcore: invalid pattern matcher input")
ErrInvalidPattern reports a nil pattern or incomplete matcher callback.
var ErrInvalidRewriteApplication = errors.New("egraphcore: invalid rewrite application")
ErrInvalidRewriteApplication reports an invalid graph or missing callback.
var ErrInvalidTopKExtraction = errors.New("egraphcore: invalid top-k extraction")
ErrInvalidTopKExtraction reports missing callbacks.
var ErrMatchWorkLimit = errors.New("egraphcore: pattern match work limit exceeded")
ErrMatchWorkLimit reports that structural pattern matching exhausted its work budget before it could determine all matches.
var ErrMemoryClosed = errors.New("egraphcore: memory scope is closed")
ErrMemoryClosed reports use of a released allocation scope.
var ErrMemorySize = errors.New("egraphcore: invalid memory size")
ErrMemorySize reports an invalid or overflowing storage request.
var ErrMissingCanonicalizer = errors.New("egraphcore: missing class canonicalizer")
ErrMissingCanonicalizer reports an operation that requires class canonicalization but received no canonicalizer.
var ErrRelationReset = errors.New("egraphcore: relation cursor invalidated; recompute required")
ErrRelationReset reports that a relation cursor predates a mutation that invalidated incremental evaluation. The caller must recompute from the current relation and take a new snapshot.
var ErrRewriteNodeLimit = errors.New("egraphcore: rewrite node limit exceeded")
ErrRewriteNodeLimit reports that an application admission check rejected a match because its conservative node-growth bound exceeds the graph limit.
var ErrRewriteWorkBudget = errors.New("egraphcore: rewrite work budget exceeded")
ErrRewriteWorkBudget reports that applying prepared rewrite matches exhausted its work budget.
var ErrTopKExpansionLimit = errors.New("egraphcore: top-k expansion limit exceeded")
ErrTopKExpansionLimit reports that extraction could not represent a larger saturated child result limit while the result might still be truncated.
var ErrTopKWorkBudget = errors.New("egraphcore: top-k work budget exceeded")
ErrTopKWorkBudget reports that top-k enumeration exhausted its work budget before finishing.
Functions ¶
func ASTSizeCost ¶
ASTSizeCost returns one unit for the current node plus the supplied costs for each child use.
func CanonicalChildIDs ¶
func CanonicalChildIDs[ID ~uint32](parent []ID, children []ID) []ID
CanonicalChildIDs returns the canonical representatives for children in their original order, applying path compression to parent as it goes.
func ChildCosts ¶
func ChildCosts[ID comparable](children []ID, costs map[ID]float64) ([]float64, bool)
ChildCosts returns the cost for each child ID in order. It returns false if any child has no cost or has a non-finite cost.
func CountInternalChildren ¶
CountInternalChildren counts distinct children of node that belong to component.
func CyclicComponents ¶
CyclicComponents returns the strongly connected components that contain a cycle in the reachable subgraph. Results are sorted by class ID and use an iterative Kosaraju traversal to handle deep graphs without recursion.
func EvaluateNodeCost ¶
func EvaluateNodeCost[Node any]( model CostModel[Node], node Node, childCosts []float64, cloneNode func(Node) Node, ) float64
EvaluateNodeCost calls model with a backend-cloned node and a copy of the child costs. cloneNode should copy mutable node data that the model could otherwise use to mutate graph state.
func ExtractBestAdditive ¶
func ExtractBestAdditive[ID ~uint32, Node any]( root ID, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, localCost func(Node) float64, maxWork int, ) (map[ID]AdditiveBestCostNode[Node], int, error)
ExtractBestAdditive selects a minimum-cost acyclic expression from root. It returns ErrAdditiveUnresolved if root has no finite derivation.
func ExtractBestAdditiveFromRoots ¶
func ExtractBestAdditiveFromRoots[ID ~uint32, Node any]( roots []ID, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, localCost func(Node) float64, nodeEligible func(Node) bool, maxWork int, ) (map[ID]AdditiveBestCostNode[Node], int, error)
ExtractBestAdditiveFromRoots selects minimum-cost acyclic expressions from one or more reachability seeds and returns selected nodes for all reachable classes with finite derivations. The cost of a node is its local cost plus the cost of every child use, so a repeated child is counted repeatedly. Local float64 costs are interpreted as exact binary rationals while comparing candidates. Equal-cost expressions are ranked by unfolded node count, then by the order returned from nodes.
Reachability follows eligible node alternatives. Seeds and other classes without a finite derivation are omitted. Reachable negative-cost cycles are rejected. maxWork bounds seed processing, scanned nodes, and eligible child edges across reachability, cost relaxation, cycle detection, size ranking, and final selection. The graph callbacks must describe an immutable graph for the duration of the call.
func Find ¶
func Find[ID ~uint32](parent []ID, id ID) ID
Find returns the root of id in parent and compresses the traversed path.
The caller must ensure parent is not concurrently modified. If id is out of range, Find returns id unchanged. This lets graph wrappers retain their own invalid-ID contracts while sharing the path-compression operation.
func FindMemoCandidate ¶
func FindMemoCandidate[ID ~uint32, Node any]( candidates []ID, want Node, find func(ID) ID, classNodes func(ID) []Node, canonicalize func(Node) Node, equal func(Node, Node) bool, ) (ID, bool, error)
FindMemoCandidate scans one hash-cons bucket and confirms node equality within each distinct canonical owner. The key has already selected the bucket; canonicalize and equal define the backend's node identity.
func FindMemoCandidateIter ¶
func FindMemoCandidateIter[ID ~uint32, Node any]( visitCandidates func(func(ID) bool), want Node, find func(ID) ID, classNodes func(ID) []Node, canonicalize func(Node) Node, equal func(Node, Node) bool, ) (ID, bool, error)
FindMemoCandidateIter performs the same lookup while consuming candidates through visitCandidates, which can avoid exposing or copying a memo bucket.
func FindMemoCandidateIterWithBudget ¶
func FindMemoCandidateIterWithBudget[ID ~uint32, Node any]( visitCandidates func(func(ID) bool), want Node, find func(ID) ID, classNodes func(ID) []Node, canonicalize func(Node) (Node, error), equal func(Node, Node) bool, budget *WorkBudget, ) (ID, bool, error)
FindMemoCandidateIterWithBudget admits lookup scratch before allocation. Allocating callbacks must admit their own storage using the same scope.
Example ¶
m := new(exampleMemory)
scope, _ := egraphcore.NewMemoryScope(m)
defer scope.Close()
b, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
nodes := []string{"a"}
id, found, err := egraphcore.FindMemoCandidateIterWithBudget(func(visit func(uint32) bool) { visit(3) }, "a", func(id uint32) uint32 { return id }, func(uint32) []string { return nodes }, func(s string) (string, error) { return s, nil }, func(a, c string) bool { return a == c }, b)
fmt.Println(id, found, err)
Output: 3 true <nil>
func LinkRoots ¶
LinkRoots joins two distinct roots in parent by making newRoot the parent of the other root. newRoot must be one of the supplied roots. Callers that use Store can select roots with LinkRootsBySize to share deterministic union-by-size behavior.
LinkRoots returns false when the roots are equal, either root is out of range, or newRoot is not one of the roots.
func MatchEClass ¶
func MatchEClass[ID comparable, Node any]( pattern *Pattern, classID ID, current map[string]ID, budget *WorkBudget, find func(ID) ID, nodes func(ID) []Node, op func(Node) string, children func(Node) []ID, ) ([]map[string]ID, error)
MatchEClass finds every match of pattern rooted at classID. The callbacks expose backend-specific graph storage while keeping matching shared. Current bindings are copied and canonicalized before matching and are not modified. work is shared across recursive calls and may be reused across root classes.
func MatchEClassWithMatcher ¶
func MatchEClassWithMatcher[ID comparable, Node, P any]( pattern P, classID ID, current map[string]ID, budget *WorkBudget, callbacks MatcherCallbacks[ID, Node, P], ) ([]map[string]ID, error)
MatchEClassWithMatcher finds every match rooted at classID using a backend-defined pattern type. Current bindings are copied and canonicalized before matching and are not modified. Matching uses an explicit work stack, so deeply nested patterns do not consume the Go call stack.
func MaterializeChoice ¶
func MaterializeChoice[ID ~uint32, Node, Value any]( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, build func(class ID, node Node, children []Value) (Value, error), ) (Value, error)
MaterializeChoice builds the acyclic graph selected by choice in postorder. The core validates each reachable choice, detects cycles, and reuses the built value when multiple parents refer to the same class. build supplies backend-specific value construction. It runs once per reachable class and receives child values in node child order. The alternatives and children callbacks must return stable results for the duration of the call. Class IDs in choice and children must already be canonical.
func MutateDiscreteChoice ¶
func MutateDiscreteChoice(genome []int, genes []DiscreteChoiceGene, mutationCount int, rng IntnSource) ([]int, error)
MutateDiscreteChoice applies mutationCount independent mutations to genome. Each mutation chooses one supplied gene uniformly, then chooses one of its allowed alleles uniformly. Genes and allele pools should be supplied in deterministic order when reproducible searches are required. The returned genome is a copy; the input is unchanged.
func PlanJoinOrder ¶
func PlanJoinOrder(boundVariables []string, conditions []JoinOrderCondition, budget *WorkBudget) ([]int, error)
PlanJoinOrder greedily orders conditions to prefer the greatest number of bindings shared with variables already bound, then the smallest candidate set. Original condition index breaks ties, so plans are deterministic. The input slices are not modified. A nil budget is unlimited.
func PropagateAnalysis ¶
func PropagateAnalysis[ID ~uint32, Node any]( seeds []ID, ops AnalysisPropagation[ID, Node], ) error
PropagateAnalysis repeatedly joins node facts into seeded classes and revisits dependent parents until the worklist is empty. Backend callbacks own graph storage, node interpretation, fact semantics, and work limits.
func PruneEmptyAlternatives ¶
func PruneEmptyAlternatives[ID ~uint32, Node any](alternatives map[ID][]Node, children func(Node) []ID) (map[ID][]Node, error)
PruneEmptyAlternatives removes alternatives whose children have no alternatives, propagating newly empty classes through reverse dependencies. The input map and slices are left unchanged. Each alternative and distinct child edge is processed at most once.
func RelaxBestCosts ¶
func RelaxBestCosts[ID ~uint32, Node any]( classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, children func(Node) []ID, canonicalChild func(ID) ID, visit CostVisit[Node], evaluate CostEvaluation[Node], better func(candidate Node, candidateCost float64, current Node, currentCost float64) bool, maxPasses int, ) (map[ID]BestCostNode[Node], int, error)
RelaxBestCosts computes bottom-up best costs by bounded fixed-point scans. The caller supplies class enumeration, node children, canonicalization, candidate validity, and tie policy; the core owns child-cost lookup and relaxation. A nil better callback selects only strictly lower costs. If maxPasses is reached while a pass still changes the result, the partial map is returned with ErrCostRelaxationLimit.
func RelaxBestCostsWorklist ¶
func RelaxBestCostsWorklist[ID ~uint32, Node, Rank any]( classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, children func(Node) []ID, canonicalChild func(ID) ID, dependencyVisit CostVisit[Node], visit CostVisit[Node], evaluate RankedCostEvaluation[Node, Rank], better func(candidate, current RankedBestCostNode[Node, Rank]) bool, accept RankedCostAcceptance[ID, Node, Rank], maxVisits int, ) (map[ID]RankedBestCostNode[Node, Rank], int, error)
RelaxBestCostsWorklist computes selected node states with a deterministic dependency worklist. It scans every class once, then requeues parents when a selected child state changes. dependencyVisit runs before each node's child edges are added to the reverse dependency index; visit runs before each cost evaluation. The caller supplies candidate evaluation, preference, rank, and acceptance policy; the core owns canonical child lookup and dependency scheduling. better must define a stable strict preference to ensure termination. maxVisits must be positive and limits node evaluations; on exhaustion the partial best-state map is returned with ErrCostRelaxationLimit.
func RelaxBestCostsWorklistWithBudget ¶
func RelaxBestCostsWorklistWithBudget[ID ~uint32, Node, Rank any]( classes []ID, nodes func(ID) []Node, canonicalClass func(ID) ID, children func(Node) []ID, canonicalChild func(ID) ID, dependencyVisit CostVisit[Node], visit CostVisit[Node], evaluate RankedCostEvaluation[Node, Rank], better func(candidate, current RankedBestCostNode[Node, Rank]) bool, accept RankedCostAcceptance[ID, Node, Rank], maxVisits int, budget *WorkBudget, ) (output map[ID]RankedBestCostNode[Node, Rank], visits int, err error)
RelaxBestCostsWorklistWithBudget is RelaxBestCostsWorklist with storage reservations through budget. The caller keeps its MemoryScope open through the last use of the returned table. Callbacks return borrowed data or reserve their own storage. Allocation refusal returns no partial table; other errors retain the original partial-table behavior. maxVisits and visit callbacks govern work independently of the allocation scope. A nil budget is unlimited.
Example ¶
nodes := []string{"leaf"}
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
best, _, err := egraphcore.RelaxBestCostsWorklistWithBudget([]uint32{0}, func(uint32) []string { return nodes },
func(id uint32) uint32 { return id }, func(string) []uint32 { return nil }, func(id uint32) uint32 { return id }, nil, nil,
func(string, []egraphcore.RankedBestCostNode[string, uint64], bool) (float64, uint64, bool, error) {
return 1, 1, true, nil
},
func(a, b egraphcore.RankedBestCostNode[string, uint64]) bool { return a.Cost < b.Cost }, nil, 10, budget)
fmt.Println(best[0].Cost, err)
Output: 1 <nil>
func RepairChoiceCycles ¶
func RepairChoiceCycles[ID ~uint32, Node any]( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, allowed func(ID, int) bool, pick func(n int) int, maxRounds int, ) (map[ID]int, error)
RepairChoiceCycles changes selected alternatives until the reachable choice graph is acyclic. allowed may restrict replacement alternatives; a nil callback permits all alternatives. pick must return an index in [0,n). maxRounds bounds repair attempts and must be positive.
func SelectedChoiceGraph ¶
func SelectedChoiceGraph[ID ~uint32, Node any]( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, ) (map[ID][]ID, map[ID]bool, error)
SelectedChoiceGraph builds the reachable directed graph induced by one alternative selected for each visited class. Repeated child classes in one node contribute one edge. The callbacks define backend node storage.
func SelectedChoiceMatches ¶
func SelectedChoiceMatches[ID ~uint32, Node any, Value comparable]( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, valueRoot Value, valueChildren func(Value) []Value, equal func(ID, Node, Value) bool, ) bool
SelectedChoiceMatches reports whether the selected choice graph rooted at root has the same structure as valueRoot. equal compares one selected node with its corresponding value; valueChildren returns the value's children in the same order as children returns the selected node's child classes.
The selected-choice callbacks must return stable results for the duration of the call. Class IDs in choice and children must already be canonical. Invalid choices, missing callbacks, and mismatching values return false. Repeated class/value pairs are compared once, so shared or cyclic structures do not require expansion into trees.
func StructuralFingerprint ¶
StructuralFingerprint combines operator fields, payload data, and ordered child fingerprints into a bucket key. Unsupported payloads use a type-only key. Collisions are possible; callers must still confirm structural equality.
func ValidateMonotoneCost ¶
ValidateMonotoneCost checks the per-node constraints required by the standard best and top-K extractors. It checks the returned value against the supplied child costs; callers remain responsible for ensuring their cost function is monotone for all possible child-cost inputs.
func ValidateSchedule ¶
func ValidateSchedule[R any](schedule *Schedule[R], validateRule ScheduleRuleValidator[R]) error
ValidateSchedule checks schedule structure and validates every rule. It reports cycles and nil nodes before execution begins.
func ValueFingerprint ¶
ValueFingerprint returns a conservative FNV-1a fingerprint for values made from booleans, numbers, strings, arrays, slices, structs, and interfaces. The result is a bucket key, not proof of equality; callers must still compare values when fingerprints match. It returns false for unsupported kinds, cyclic slices, or values nested more than 128 levels deep.
func WouldCreateCycle ¶
func WouldCreateCycle[ID comparable, Node any]( owner ID, childIDs []ID, canonicalize func(ID) ID, selected func(ID) (Node, bool), children func(Node) []ID, ) bool
WouldCreateCycle reports whether selecting owner with childIDs would create a cycle in the currently selected graph. canonicalize maps class IDs to their current representatives; selected returns the chosen node for a class; children returns a node's child class IDs. Missing selected nodes terminate a path. If a required callback is nil, the function conservatively reports a cycle.
func WouldCreateCycleWithBudget ¶
func WouldCreateCycleWithBudget[ID comparable, Node any]( owner ID, childIDs []ID, canonicalize func(ID) ID, selected func(ID) (Node, bool), children func(Node) []ID, visit CycleVisit[ID], budget *WorkBudget, ) (cycle bool, err error)
WouldCreateCycleWithBudget is WouldCreateCycleWithVisit with allocation reservations through budget. Traversal storage remains owned by the budget's scope until it closes. Callbacks return borrowed data or reserve their own allocations. A nil budget preserves unlimited allocation.
Example ¶
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
cycle, err := egraphcore.WouldCreateCycleWithBudget(uint32(1), []uint32{0}, func(id uint32) uint32 { return id }, func(id uint32) (uint32, bool) { return id, true }, func(uint32) []uint32 { return nil }, nil, budget)
fmt.Println(cycle, err)
Output: false <nil>
func WouldCreateCycleWithVisit ¶
func WouldCreateCycleWithVisit[ID comparable, Node any]( owner ID, childIDs []ID, canonicalize func(ID) ID, selected func(ID) (Node, bool), children func(Node) []ID, visit CycleVisit[ID], ) (bool, error)
WouldCreateCycleWithVisit reports whether selecting owner with childIDs creates a cycle and lets callers bound each selected-node/child-edge scan. If visit returns an error, traversal stops and returns that error.
Types ¶
type AdditiveBestCostNode ¶
AdditiveBestCostNode is the selected node and rounded total cost for an e-class returned by ExtractBestAdditive.
type AnalysisPropagation ¶
type AnalysisPropagation[ID ~uint32, Node any] struct { Canonical func(ID) ID Exists func(ID) bool Nodes func(ID) []Node Data func(ID) (any, bool) SetData func(ID, any, bool) Make func(Node) (any, bool, error) Merge func(any, any) (any, bool, error) VisitParents func(ID, func(ID)) Spend func() error }
AnalysisPropagation provides backend operations used by the shared fixed-point worklist. Make reports whether a node contributes a fact; Merge combines two present facts and reports whether the value changed. Data and SetData read and write a class's accumulated fact and its presence independently, allowing an explicit nil fact. VisitParents visits classes whose facts may depend on the given class. Spend accounts for one Make or Merge callback evaluation.
type Atom ¶
Atom applies terms to the columns of one relation. Repeated variable names within or across atoms impose equality. Variable names occupy one shared namespace; callers that distinguish backend namespaces should qualify names.
type BestCostNode ¶
BestCostNode is the selected node and accumulated cost for an e-class.
type Binding ¶
Binding is one variable assignment produced by Join.
func Join ¶
func Join[ID ~uint32](atoms []Atom[ID], canonicalize func(ID) ID, budget *WorkBudget) (results []Binding[ID], complete bool, err error)
Join evaluates a conjunction of relation atoms. At each step it probes the remaining atoms with current bindings and selects the one with the fewest rows. It uses Relation.Query indexes for constants and bound variables, and returns deterministic bindings. canonicalize is required to normalize class-valued columns. If work runs out, it returns no partial bindings and complete=false. A nil budget is unlimited.
func JoinBindings ¶
func JoinBindings[ID ~uint32](left, right []Binding[ID], rightKeys []string, canonicalize func(ID) ID, budget *WorkBudget) (results []Binding[ID], complete bool, err error)
JoinBindings joins two materialized binding sets on shared variable names. Every binding must contain every name in rightKeys; incomplete key plans return ErrInvalidJoin. It uses a hash index on rightKeys and also checks equality for every other variable present in both bindings. Class values are canonicalized before comparison and in returned bindings. Output bindings are deterministic and deduplicated. canonicalize is required. On budget exhaustion it returns no partial output and complete=false. A nil budget is unlimited.
func JoinDeltas ¶
func JoinDeltas[ID ~uint32]( atoms []Atom[ID], deltas []DeltaAtom[ID], canonicalize func(ID) ID, budget *WorkBudget, ) (results []Binding[ID], complete bool, err error)
JoinDeltas evaluates a conjunction using only newly added rows for each selected delta atom and the full current relations for all other atoms. Deletions, subsumption, and recanonicalization invalidate relation cursors; in that case the caller must recompute the rule from the full relations.
Results are canonicalized, deduplicated, and returned in deterministic order. An empty delta set produces no bindings. Work exhaustion returns no partial result and complete=false. A nil budget is unlimited.
type CandidateLattice ¶
type CandidateLattice[T any] struct { // contains filtered or unexported fields }
CandidateLattice walks a bounded Cartesian product of ranked bucket finalists from lowest aggregate score to highest. Equal aggregate scores are ordered lexicographically by bucket rank. Aggregate must be deterministic, must not modify its input, and must be coordinate-monotone: increasing one input score while holding the others fixed must not decrease the aggregate. Reject opens each one-coordinate slower successor; duplicate paths are suppressed.
func NewCandidateLattice ¶
func NewCandidateLattice[T any](buckets []CandidateLatticeBucket[T], aggregate func([]float64) float64, maxSets, maxFinalistsPerBucket int) (*CandidateLattice[T], error)
NewCandidateLattice creates a bounded best-first coordinator. maxSets caps proposals and maxFinalistsPerBucket caps lazy ranks fetched from each bucket. A nonpositive bound is an error. Each bucket must provide at least one finalist, either in Finalists or through LoadFinalist.
func (*CandidateLattice[T]) Accept ¶
func (l *CandidateLattice[T]) Accept(set *CandidateLatticeSet[T]) error
Accept resolves the pending proposal as viable and permits another Next.
func (*CandidateLattice[T]) Attempts ¶
func (l *CandidateLattice[T]) Attempts() int
Attempts reports the number of sets proposed, including rejected sets.
func (*CandidateLattice[T]) LastRejection ¶
func (l *CandidateLattice[T]) LastRejection() string
LastRejection reports the most recent aggregate validation failure.
func (*CandidateLattice[T]) LimitReached ¶
func (l *CandidateLattice[T]) LimitReached() bool
LimitReached reports whether maxSets or maxFinalistsPerBucket prevented the lattice from exploring another candidate set.
func (*CandidateLattice[T]) Next ¶
func (l *CandidateLattice[T]) Next() (*CandidateLatticeSet[T], bool, error)
Next returns the lowest-scoring unvisited set. The caller validates the aggregate and either accepts it or passes it to Reject. A returned set must be resolved before another call to Next. A false result means no proposal is currently available within the configured bounds; inspect StopReason and LimitReached before treating the search space as exhausted.
func (*CandidateLattice[T]) Reject ¶
func (l *CandidateLattice[T]) Reject(set *CandidateLatticeSet[T], reason string) error
Reject resolves a proposal that fails aggregate validation and adds its one-coordinate slower successors to the frontier.
func (*CandidateLattice[T]) SearchExpired ¶
func (l *CandidateLattice[T]) SearchExpired() bool
SearchExpired reports whether the overall search timeout has elapsed.
func (*CandidateLattice[T]) SetTimeouts ¶
func (l *CandidateLattice[T]) SetTimeouts(searchTimeout, candidateTimeout time.Duration) error
SetTimeouts configures optional overall search and per-proposal deadlines. Call it before Next. Zero disables the corresponding timeout. Deadlines are checked when callbacks return; they do not interrupt a loader or validator.
func (*CandidateLattice[T]) StopReason ¶
func (l *CandidateLattice[T]) StopReason() string
StopReason reports why Next last returned no proposal. An empty result can mean the search space was exhausted, a configured bound was reached, or a finalist load timed out; callers must not treat every empty result as proof that no unexamined candidate exists.
func (*CandidateLattice[T]) TimedOut ¶
func (l *CandidateLattice[T]) TimedOut(set *CandidateLatticeSet[T]) bool
TimedOut reports whether the proposal deadline has elapsed. A zero deadline means that proposal timeouts are disabled.
func (*CandidateLattice[T]) ValidateNext ¶
func (l *CandidateLattice[T]) ValidateNext(validate func(*CandidateLatticeSet[T]) error) (*CandidateLatticeSet[T], bool, error)
ValidateNext proposes sets until validate accepts one or the bounded search is exhausted. Rejected sets are expanded automatically.
type CandidateLatticeBucket ¶
type CandidateLatticeBucket[T any] struct { Finalists []CandidateLatticeFinalist[T] LoadFinalist func(rank int) (finalist CandidateLatticeFinalist[T], ok bool, err error) }
CandidateLatticeBucket supplies individually viable finalists in score order. Finalists may contain already-materialized values; LoadFinalist can lazily produce ranks beyond Finalists. It is called at most once for each rank, in rank order. Return ok=false when the bucket has no more viable finalists. Values are retained without copying and must remain immutable.
type CandidateLatticeFinalist ¶
CandidateLatticeFinalist is one individually viable bucket finalist at a rank. Scores must be finite and nondecreasing within each bucket. Value is retained without copying and must remain immutable while the lattice uses it.
type CandidateLatticeSet ¶
type CandidateLatticeSet[T any] struct { Indices []int Finalists []CandidateLatticeFinalist[T] Score float64 Deadline time.Time // contains filtered or unexported fields }
CandidateLatticeSet is one proposed Cartesian product, in bucket order. Indices and Finalists slices are copies and may be retained by the caller. Values inside Finalists are shallow copies and must remain immutable.
type ChoiceFingerprint ¶
type ChoiceFingerprint [32]byte
ChoiceFingerprint is a fixed-size structural digest for one selected class.
type ChoiceFingerprintBuild ¶
type ChoiceFingerprintBuild[ID ~uint32, Node any] func(ID, Node, []ChoiceFingerprint) ChoiceFingerprint
ChoiceFingerprintBuild combines a selected node with its child fingerprints. Child fingerprints are in the node's child order.
type ChoiceFingerprinter ¶
ChoiceFingerprinter caches subtree fingerprints for one immutable choice space. Cache entries depend on the selected alternative and child fingerprints, so changing one part of a choice only invalidates ancestors whose selected child fingerprints change. Do not reuse it with a different graph or callbacks that return different alternatives or fingerprints. It is not safe for concurrent use.
func NewChoiceFingerprinter ¶
func NewChoiceFingerprinter[ID ~uint32, Node any]() *ChoiceFingerprinter[ID, Node]
NewChoiceFingerprinter creates an empty cache for an immutable choice space.
func (*ChoiceFingerprinter[ID, Node]) Fingerprint ¶
func (f *ChoiceFingerprinter[ID, Node]) Fingerprint( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, build ChoiceFingerprintBuild[ID, Node], budget *WorkBudget, ) (ChoiceFingerprint, error)
Fingerprint computes the selected root's structural fingerprint without materializing backend expression values. It rejects missing choices, invalid alternatives, and cycles. A nil budget is unlimited; otherwise the budget charges selected classes, child edges, and cache-key construction.
type ChoiceMaterializer ¶
type ChoiceMaterializer[ID ~uint32, Node, Value any] struct { // contains filtered or unexported fields }
ChoiceMaterializer reuses dense traversal scratch for one fixed set of classes. Class IDs and child IDs must be canonical. It is not safe for concurrent or reentrant use.
func NewChoiceMaterializer ¶
func NewChoiceMaterializer[ID ~uint32, Node, Value any](classes []ID) (*ChoiceMaterializer[ID, Node, Value], error)
NewChoiceMaterializer creates reusable traversal scratch for classes. The class list is copied and must contain each class at most once. Its IDs must use the same canonical form as the IDs passed to Materialize.
func (*ChoiceMaterializer[ID, Node, Value]) Materialize ¶
func (m *ChoiceMaterializer[ID, Node, Value]) Materialize( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, build func(class ID, node Node, children []Value) (Value, error), ) (result Value, err error)
Materialize builds the selected root value in postorder. It validates reachable choices, rejects cycles, and reuses each completed class value within this result so shared children remain shared. On success, build is called once per reachable class, with child values in node child order. Scratch is cleared after success or error; no values are retained between calls. The choice space and callbacks must remain stable during the call; alternatives and children must return results whose contents and backing storage remain valid and unchanged until the call ends.
func (*ChoiceMaterializer[ID, Node, Value]) ReachableClasses ¶
func (m *ChoiceMaterializer[ID, Node, Value]) ReachableClasses( root ID, choice map[ID]int, alternatives func(ID) []Node, children func(Node) []ID, ) ([]ID, error)
ReachableClasses returns selected classes in ascending ID order. The returned slice is owned by the materializer and remains valid only until the next ReachableClasses call. It shares traversal scratch with Materialize and is not safe for concurrent or reentrant use. alternatives and children must return stable results for the duration of the call.
type ChoiceSpace ¶
ChoiceSpace is an immutable, reachable snapshot of alternatives rooted at Root. Node payload ownership is defined by the clone callback supplied to NewChoiceSpace; callers should clone any mutable fields such as child slices.
func NewChoiceSpace ¶
func NewChoiceSpace[ID ~uint32, Node any]( root ID, alternatives map[ID][]Node, children func(Node) []ID, clone func(Node) Node, lessNode func(Node, Node) bool, ) (*ChoiceSpace[ID, Node], error)
NewChoiceSpace prunes alternatives with missing children, orders the remaining alternatives, and retains only classes reachable from root. clone must return an independent node when Node contains mutable data. lessNode defines deterministic alternative order; equal nodes preserve their input order. Child IDs and node canonicalization remain backend concerns.
func NewChoiceSpaceFrom ¶
func NewChoiceSpaceFrom[ID ~uint32, Node any]( root ID, canonicalClass func(ID) (ID, error), alternatives func(ID) ([]Node, error), canonicalizeNode func(Node) (Node, error), children func(Node) []ID, keep func(Node) bool, clone func(Node) Node, lessNode func(Node, Node) bool, ) (*ChoiceSpace[ID, Node], error)
NewChoiceSpaceFrom builds a reachable choice space through backend callbacks. canonicalClass resolves union-find IDs; canonicalizeNode copies a node and canonicalizes backend-specific fields; keep filters backend-specific nodes. Each child returned by children must already be canonical.
func (*ChoiceSpace[ID, Node]) AlternativeCount ¶
func (s *ChoiceSpace[ID, Node]) AlternativeCount(class ID) int
AlternativeCount reports the number of alternatives for class.
func (*ChoiceSpace[ID, Node]) Alternatives ¶
func (s *ChoiceSpace[ID, Node]) Alternatives(class ID) []Node
Alternatives returns an independent slice of alternatives for class. Nodes themselves follow the ownership contract passed to NewChoiceSpace.
func (*ChoiceSpace[ID, Node]) Classes ¶
func (s *ChoiceSpace[ID, Node]) Classes() []ID
Classes returns reachable classes in ascending ID order.
func (*ChoiceSpace[ID, Node]) Root ¶
func (s *ChoiceSpace[ID, Node]) Root() ID
Root returns the root class captured by the space.
type Column ¶
Column describes the type of one relation column. Sort is meaningful only for class columns; backends may use it to enforce their own sort policy.
type CongruencePlan ¶
type CongruencePlan[ID comparable, Node any] struct { Nodes []OwnedNode[ID, Node] ByOwner map[ID][]Node Merges []OwnerPair[ID] }
CongruencePlan is the result of one global congruence pass. Nodes contains one canonical node per owner and structural identity, in first-seen order. Merges contains distinct owner pairs whose nodes were structurally equal.
func ApplyCongruencePass ¶
func ApplyCongruencePass[ID ~uint32, Node any, Key comparable]( graph Graph[ID, Node], owned []OwnedNode[ID, Node], key func(Node) Key, equal func(Node, Node) bool, mergeEquivalent func(Node, Node) Node, ) (CongruencePlan[ID, Node], int, error)
ApplyCongruencePass plans one set of canonical nodes and applies the owner unions required by structural duplicates. The caller owns node collection, canonicalization, and any follow-up rebuild work. A pass that merges owners must be recollected before its ByOwner groups are published.
func PlanCongruencePass ¶
func PlanCongruencePass[ID comparable, Node any, Key comparable]( owned []OwnedNode[ID, Node], key func(Node) Key, equal func(Node, Node) bool, mergeEquivalent func(Node, Node) Node, ) (CongruencePlan[ID, Node], error)
PlanCongruencePass deduplicates structurally equal nodes and reports owners that must be merged. The input nodes must already have canonical children and canonical owner IDs. Equal nodes must have the same key. A key narrows equality candidates but never defines equality by itself; equal confirms every key match. mergeEquivalent combines backend metadata for duplicates, such as a monotone subsumed flag. A nil mergeEquivalent keeps the first node. A merge callback must preserve the node's key and structural identity.
type CongruenceReport ¶
CongruenceReport summarizes the scopes and owner unions processed by a congruence driver.
func DriveCongruence ¶
func DriveCongruence[ID ~uint32, Node any, Key comparable, Scope any]( graph Graph[ID, Node], maxPasses int, next func(pass, index int) (scope Scope, owned []OwnedNode[ID, Node], ok bool, err error), key func(Node) Key, equal func(Node, Node) bool, mergeEquivalent func(Node, Node) Node, publish func(Scope, map[ID][]Node) (repeat bool, err error), ) (CongruenceReport, error)
DriveCongruence runs policy-provided congruence scopes until they are stable. next returns scope batches in order, using pass and index to restart backend enumeration on each outer pass. publish receives stable owner groups only; it may request another outer pass for backend work such as function-table canonicalization. If applying a scope changes graph owners, its plan is not published and the driver restarts enumeration immediately. Thus callbacks must provide canonical owners and children for the requested pass. maxPasses bounds outer passes, including the final pass that observes stability.
func DriveCongruenceWithBudget ¶
func DriveCongruenceWithBudget[ID ~uint32, Node any, Key comparable, Scope any]( graph Graph[ID, Node], maxPasses int, next func(pass, index int) (scope Scope, owned []OwnedNode[ID, Node], ok bool, err error), key func(Node) (Key, error), equal func(Node, Node) bool, mergeEquivalent func(Node, Node) Node, publish func(Scope, map[ID][]Node) (repeat bool, err error), budget *WorkBudget, ) (CongruenceReport, error)
DriveCongruenceWithBudget is DriveCongruence with admitted planner storage. Backend callbacks own admission of their storage and may return errors. Keep budget's scope open through the last use of published node groups.
Example ¶
m := new(exampleMemory)
scope, _ := egraphcore.NewMemoryScope(m)
defer scope.Close()
b, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
// No backend scopes: the common driver observes stability in one pass.
report, err := egraphcore.DriveCongruenceWithBudget(mutationExampleGraph{}, 1, func(int, int) (int, []egraphcore.OwnedNode[uint32, string], bool, error) { return 0, nil, false, nil }, func(n string) (string, error) { return n, nil }, func(a, c string) bool { return a == c }, nil, func(int, map[uint32][]string) (bool, error) { return false, nil }, b)
fmt.Println(report.Passes, err)
Output: 1 <nil>
type CostEvaluation ¶
type CostEvaluation[Node any] func(node Node, childCosts []float64, allChildrenKnown bool) (cost float64, eligible bool, err error)
CostEvaluation computes an eligible node's cost from child costs. It is called for every visited node, including nodes with unknown child costs, so adapters can preserve work accounting before deciding whether to skip it.
type CostModel ¶
CostModel assigns a cost to one node using costs already computed for its child classes. A model must be deterministic, must not mutate the node or its payload, and must return finite, non-negative costs that are monotone in every child cost and no smaller than any child cost. Backend-specific models supply their own cost policy within that contract. Use measured candidate search when ranking by a whole-expression runtime metric.
type CostVisit ¶
CostVisit runs once for each node before the helper canonicalizes its children or looks up their costs. It can be used for accounting that must include nodes whose children are not yet extractable.
type CycleVisit ¶
type CycleVisit[ID comparable] func(id ID, work int) error
CycleVisit runs before a selected node and its child edges are added to the traversal stack. work is one unit for the class and one for each child edge.
type DeltaAtom ¶
type DeltaAtom[ID ~uint32] struct { Index int Cursor RelationCursor }
DeltaAtom selects one relation atom whose additions should seed an incremental join. Every atom in a rule body that has new rows should be included; JoinDeltas evaluates one join per selected atom and deduplicates matches that contain more than one new row.
type DiscreteChoiceGene ¶
DiscreteChoiceGene identifies one mutable position in an integer genome and the alleles permitted at that position.
type FactAction ¶
type FactAction[ID ~uint32] struct { Kind FactActionKind Relation string Terms []Term[ID] }
FactAction is a relation mutation whose terms are constants or variables. Wildcards are useful in queries but cannot identify an action tuple.
type FactActionKind ¶
type FactActionKind uint8
FactActionKind identifies a mutation to a registered relation.
const ( FactInsert FactActionKind = iota + 1 FactDelete FactSubsume )
type FactStore ¶
type FactStore[ID ~uint32] struct { // contains filtered or unexported fields }
FactStore owns named typed relations. It is not safe for concurrent use. Relation schemas and fact values are backend-neutral; class canonicalization remains the backend's responsibility.
func NewFactStore ¶
NewFactStore creates an empty fact store.
func (*FactStore[ID]) Add ¶
func (s *FactStore[ID]) Add(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
Add inserts a fact into a registered relation.
func (*FactStore[ID]) ApplyActions ¶
func (s *FactStore[ID]) ApplyActions(actions []ResolvedFactAction[ID], canonicalize func(ID) ID, budget *WorkBudget) (int, error)
ApplyActions applies resolved relation mutations in order. It stages every touched relation on a clone, then commits all changed relations together. Existing relation pointers remain valid. It returns the number of relations whose final state changed. A nil budget means unlimited work.
func (*FactStore[ID]) ApplyActionsDetailed ¶
func (s *FactStore[ID]) ApplyActionsDetailed(actions []ResolvedFactAction[ID], canonicalize func(ID) ID, budget *WorkBudget) ([]bool, int, error)
ApplyActionsDetailed applies resolved relation mutations in order. It stages multiple actions on relation clones and commits all changed relations together. A singleton action uses a prepared in-place update after all validation and budget checks have succeeded. The returned slice has one entry per action and reports whether that action changed its relation at the point where it was applied. The second result is the number of relations whose final state changed. On error, no mutation is published and the action results are nil. A nil budget means unlimited work.
func (*FactStore[ID]) CanonicalCopyWithBudget ¶
func (s *FactStore[ID]) CanonicalCopyWithBudget(canonicalize func(ID) ID, budget *WorkBudget) (*FactStore[ID], error)
CanonicalCopyWithBudget creates a detached canonical fact view. All created objects, indexes, rows and keys reserve storage through budget before allocation. Strings remain borrowed immutable values. The caller keeps the budget's MemoryScope open while using the copy. The source is unchanged; the copy starts a new delta epoch, like Recanonicalize.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/egraphcore"
)
type exampleMemory struct{ used int64 }
func (m *exampleMemory) Reserve(bytes int64) error {
if bytes > 1<<20-m.used {
return errors.New("memory limit")
}
m.used += bytes
return nil
}
func (m *exampleMemory) Release(bytes int64) { m.used -= bytes }
func main() {
source := egraphcore.NewFactStore[uint32]()
relation, _ := source.Register(egraphcore.Schema{Name: "class", Columns: []egraphcore.Column{{Kind: egraphcore.ClassValue}}})
_, _ = relation.Add([]egraphcore.Value[uint32]{egraphcore.Class(uint32(2))}, func(id uint32) uint32 { return id })
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(1000, scope)
copy, err := source.CanonicalCopyWithBudget(func(uint32) uint32 { return 1 }, budget)
if err != nil {
fmt.Println(err)
return
}
rows, _, _ := copy.Get("class").Query(nil, func(id uint32) uint32 { return id }, budget)
fmt.Println(rows[0][0].Class, relation.Len())
}
Output: 1 1
func (*FactStore[ID]) Clone ¶
Clone returns an independent store with the same schemas, facts, indexes, and subsumed-fact state.
func (*FactStore[ID]) CloneWithBudget ¶
func (s *FactStore[ID]) CloneWithBudget(budget *WorkBudget) (*FactStore[ID], error)
CloneWithBudget copies schemas, facts, indexes and delta history, reserving storage before allocation. The caller owns budget's MemoryScope and keeps it open through the copy's last use. Strings and immutable ancestor epoch tokens remain borrowed. Unlike a canonical copy, this preserves cursor lineage.
Example ¶
source := egraphcore.NewFactStore[uint32]()
relation, _ := source.Register(egraphcore.Schema{Name: "count", Columns: []egraphcore.Column{{Kind: egraphcore.Int64Value}}})
cursor := relation.Snapshot()
relation.Add([]egraphcore.Value[uint32]{egraphcore.Int64[uint32](3)}, nil)
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
copy, err := source.CloneWithBudget(budget)
rows, historyErr := copy.Get("count").AddedSince(cursor)
fmt.Println(len(rows), err, historyErr)
Output: 1 <nil> <nil>
func (*FactStore[ID]) Delete ¶
func (s *FactStore[ID]) Delete(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
Delete removes a fact from a registered relation.
func (*FactStore[ID]) Get ¶
Get returns the named relation, or nil when it is not registered. The returned relation is owned by the store and can be mutated directly.
func (*FactStore[ID]) MarkSubsumed ¶
func (s *FactStore[ID]) MarkSubsumed(name string, values []Value[ID], canonicalize func(ID) ID) (bool, error)
MarkSubsumed inserts values if absent, then marks the fact hidden from Query.
func (*FactStore[ID]) Recanonicalize ¶
Recanonicalize atomically updates class-valued facts in all relations.
func (*FactStore[ID]) RecanonicalizeWithBudget ¶
func (s *FactStore[ID]) RecanonicalizeWithBudget(canonicalize func(ID) ID, budget *WorkBudget) error
RecanonicalizeWithBudget stages canonical relations with allocation-site admission, preserving registered pointers and invalidating old delta cursors. A nil memory scope retains ordinary Recanonicalize behavior.
Example ¶
m := new(exampleMemory)
scope, _ := egraphcore.NewMemoryScope(m)
defer scope.Close()
b, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
s := egraphcore.NewFactStore[uint32]()
r, _ := s.Register(egraphcore.Schema{Name: "r", Columns: []egraphcore.Column{{Kind: egraphcore.ClassValue}}})
r.Add([]egraphcore.Value[uint32]{egraphcore.Class[uint32](2)}, func(id uint32) uint32 { return id })
fmt.Println(s.RecanonicalizeWithBudget(func(uint32) uint32 { return 0 }, b), r.Rows()[0][0].Class)
Output: <nil> 0
func (*FactStore[ID]) Register ¶
Register adds schema to the store. Re-registering an identical schema is idempotent and returns the existing relation; a conflicting schema fails.
func (*FactStore[ID]) ReplaceFrom ¶
func (s *FactStore[ID]) ReplaceFrom(other *FactStore[ID], budget *WorkBudget) error
ReplaceFrom copies another store's relation state into s. Registered relation pointers remain valid. Both stores must have the same schemas. For each relation, insertion history is preserved only when other descends from s's current state; replacing it with unrelated or diverged state invalidates old cursors. A nil budget means unlimited work.
func (*FactStore[ID]) TupleCount ¶
TupleCount reports the number of stored facts across all relations, including facts marked subsumed. It saturates at the largest int on overflow.
type FunctionMergeCallbacks ¶
type FunctionMergeCallbacks[ID ~uint32] struct { Canonicalize func(ID) ID Union func(ID, ID) (ID, error) Custom func(old, incoming Value[ID]) (Value[ID], error) }
FunctionMergeCallbacks supplies graph-dependent merge operations.
type FunctionMergePolicy ¶
type FunctionMergePolicy uint8
FunctionMergePolicy selects how two results for one function key combine.
const ( FunctionMergeKeepOld FunctionMergePolicy = iota + 1 FunctionMergeUseNew FunctionMergeAssertEqual FunctionMergeConstant FunctionMergeMinInt64 FunctionMergeMaxInt64 FunctionMergeUnionClass FunctionMergeCustom )
type Graph ¶
type Graph[ID ~uint32, Node any] interface { AddChecked(Node) (ID, error) Find(ID) ID UnionChecked(ID, ID) (ID, bool, error) RebuildChecked() error }
Graph is the checked mutation surface shared by e-graph implementations. Node remains a type parameter so each backend can retain its own operator and payload representation. Implementations keep backend-specific node validation, union policy, and rebuild behavior behind these methods.
type IntnSource ¶
IntnSource supplies the bounded random integers used by discrete choice operators. math/rand.Rand implements this interface.
type JoinOrderCondition ¶
JoinOrderCondition describes one candidate set for a conjunctive match. Variables must list the set's distinct binding names; Cardinality is the number of candidate bindings.
type Match ¶
type Match[ID comparable] struct { ClassID ID Subst map[string]ID }
Match is one structural match rooted at an equivalence class.
func Search ¶
func Search[ID comparable, Node any]( pattern *Pattern, roots []ID, budget *WorkBudget, maxMatches int, find func(ID) ID, nodes func(ID) []Node, op func(Node) string, children func(Node) []ID, ) ([]Match[ID], bool, error)
Search applies pattern to roots in order. A positive maxMatches limits the returned matches; reaching that count sets limited. Work is shared across every root, and an exhausted budget returns ErrMatchWorkLimit without a partial result.
func SearchWithMatcher ¶
func SearchWithMatcher[ID comparable, Node, P any]( pattern P, roots []ID, budget *WorkBudget, maxMatches int, callbacks MatcherCallbacks[ID, Node, P], ) ([]Match[ID], bool, error)
SearchWithMatcher applies pattern to roots in order using backend supplied class eligibility, candidate selection, and node predicates. A positive maxMatches limits returned matches; reaching that count sets limited. Work is shared across all roots, and exhaustion returns no partial result.
type MatcherCallbacks ¶
type MatcherCallbacks[ID comparable, Node, P any] struct { Find func(ID) ID ValidPattern func(P) bool IsVariable func(P) (name string, variable bool) PatternChildren func(P) []P ClassEligible func(ID, P) bool Candidates func(ID, P) []Node NodeChildren func(Node) []ID NodeEligible func(Node, P) bool }
MatcherCallbacks expose graph and pattern operations to the shared structural matcher. Pattern is backend-defined, so adapters can retain sort, payload, and other pattern metadata. ClassEligible may reject a class for a pattern. Candidates may use backend indexes to preserve efficient node selection and order. NodeEligible decides whether a candidate satisfies node-specific pattern constraints; the matcher separately checks arity. A nil ClassEligible accepts every class. All other callbacks are required.
type MeasuredCandidate ¶
type MeasuredCandidate[T any] struct { ID string Score float64 // Value is retained and returned without copying. Callers must treat it // as immutable after Record. Value T }
MeasuredCandidate is a candidate selected by a caller's measured score. Value is opaque to egraphcore; the backend owns candidate construction.
type MeasuredSearch ¶
type MeasuredSearch[T any] struct { // contains filtered or unexported fields }
MeasuredSearch tracks measured parents and generation-level progress for a caller that generates and evaluates candidates. It is backend-neutral.
func NewMeasuredSearch ¶
func NewMeasuredSearch[T any](config MeasuredSearchConfig) (*MeasuredSearch[T], error)
NewMeasuredSearch creates an empty measured population. Zero KeepBest and GenerationSize default to one and ten, respectively.
func (*MeasuredSearch[T]) Best ¶
func (s *MeasuredSearch[T]) Best() (MeasuredCandidate[T], bool)
Best returns the current best measured candidate.
func (*MeasuredSearch[T]) CloseGeneration ¶
func (s *MeasuredSearch[T]) CloseGeneration(remaining int)
CloseGeneration advances generation state and sets the next candidate budget using remaining measured-candidate capacity.
func (*MeasuredSearch[T]) Generation ¶
func (s *MeasuredSearch[T]) Generation() int
Generation reports the number of completed generations.
func (*MeasuredSearch[T]) MutationLimit ¶
func (s *MeasuredSearch[T]) MutationLimit(base int) int
MutationLimit returns the configured mutation ceiling after stagnation escalation. The caller chooses a count in [1, limit].
func (*MeasuredSearch[T]) ParentFor ¶
func (s *MeasuredSearch[T]) ParentFor(position int) (MeasuredCandidate[T], bool)
ParentFor returns the parent assigned to a zero-based candidate position in this generation. It uses deterministic, balanced parent allocation.
func (*MeasuredSearch[T]) Parents ¶
func (s *MeasuredSearch[T]) Parents() bool
Parents reports whether a measured parent is available.
func (*MeasuredSearch[T]) Ranking ¶
func (s *MeasuredSearch[T]) Ranking() []MeasuredCandidate[T]
Ranking returns all measured candidates in score order. Equal scores retain encounter order. The returned slice is independent of the search state; values are retained without copying and must remain immutable after Record.
func (*MeasuredSearch[T]) Record ¶
func (s *MeasuredSearch[T]) Record(candidate MeasuredCandidate[T]) (bool, error)
Record adds a finite measured candidate to the parent pool and reports whether its score improves the incumbent. Equal scores retain encounter order, so a full pool is not displaced by a later tie.
func (*MeasuredSearch[T]) Resample ¶
func (s *MeasuredSearch[T]) Resample() bool
Resample reports whether the next candidate should be generated without a parent, due to an unviable or stagnant generation.
type MeasuredSearchConfig ¶
type MeasuredSearchConfig struct {
KeepBest int
GenerationSize int
RestartStagnation int
Descending bool
}
MeasuredSearchConfig controls the score-driven part of an evolutionary search. Candidate generation and evaluation remain with the caller.
type Memory ¶
Memory reserves storage before allocation. Reserve must leave its live byte count unchanged on error. Release relinquishes a previous reservation; it does not free or inspect the associated Go values. Implementations may share one limit with executable workspace. Calls need not be safe for concurrent use.
type MemoryScope ¶
type MemoryScope struct {
// contains filtered or unexported fields
}
MemoryScope owns reservations for one operation and its returned values. Close must follow the last use of those values. Temporary and replaced backing arrays remain charged until Close, giving a conservative upper bound on live storage. Units cover Go objects, backing-array slots and map entries; allocator and map-bucket overhead are outside these units. Callbacks must return borrowed data or reserve their own storage. A nil scope is unlimited. A scope is not safe for concurrent use.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/egraphcore"
)
type exampleMemory struct{ used int64 }
func (m *exampleMemory) Reserve(bytes int64) error {
if bytes > 1<<20-m.used {
return errors.New("memory limit")
}
m.used += bytes
return nil
}
func (m *exampleMemory) Release(bytes int64) { m.used -= bytes }
func main() {
memory := new(exampleMemory)
scope, err := egraphcore.NewMemoryScope(memory)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(scope.Reserve(16), scope.Bytes() > 0, scope.Err())
scope.Close()
fmt.Println(memory.used)
}
Output: <nil> true <nil> 0
func NewMemoryScope ¶
func NewMemoryScope(memory Memory) (*MemoryScope, error)
NewMemoryScope reserves and creates a result owner. A nil memory capability returns a nil, unlimited scope. A failed reservation creates no owner.
func (*MemoryScope) Bytes ¶
func (s *MemoryScope) Bytes() int64
Bytes reports reservations held by the scope, including its own storage.
func (*MemoryScope) Close ¶
func (s *MemoryScope) Close()
Close releases all reservations once. Returned values must no longer be used.
func (*MemoryScope) Err ¶
func (s *MemoryScope) Err() error
Err returns the first failed storage reservation.
func (*MemoryScope) Reserve ¶
func (s *MemoryScope) Reserve(bytes int64) error
Reserve charges bytes before creating storage. The first error is sticky.
type OrderedRow ¶
type OrderedRow[ID ~uint32, Row any] struct { Key string Values []Value[ID] Payload Row Order uint64 Subsumed bool }
OrderedRow is a copied row returned by OrderedTable. Values is a copy of the indexed tuple; Payload is copied by assignment and must not contain mutable data that callers change. Order is stable insertion order; Subsumed rows remain inspectable.
type OrderedTable ¶
OrderedTable owns keyed rows, value indexes, insertion order, and subsumption state. It supports backend-specific schemas and canonical keys; callers validate values and choose keys before mutation. It is not concurrency-safe.
func NewOrderedTable ¶
func NewOrderedTable[ID ~uint32, Row any](columnCount int) *OrderedTable[ID, Row]
NewOrderedTable creates an empty table indexed by columnCount values. The zero value is also usable as a table with no indexed columns.
func NewOrderedTableWithClone ¶
func NewOrderedTableWithClone[ID ~uint32, Row any](columnCount int, clone func(Row) Row) *OrderedTable[ID, Row]
NewOrderedTableWithClone creates a table whose row payloads are copied with clone when inserted, returned, and cloned. A nil clone treats payloads as immutable values copied by assignment.
func (*OrderedTable[ID, Row]) Clone ¶
func (t *OrderedTable[ID, Row]) Clone() *OrderedTable[ID, Row]
Clone returns independent rows and indexes.
func (*OrderedTable[ID, Row]) Contains ¶
func (t *OrderedTable[ID, Row]) Contains(column int, value Value[ID], key string) bool
Contains reports whether key is indexed for column and value.
func (*OrderedTable[ID, Row]) Counters ¶
func (t *OrderedTable[ID, Row]) Counters() (order, fresh uint64)
Counters returns the next stable row order and fresh-value ordinal.
func (*OrderedTable[ID, Row]) Delete ¶
func (t *OrderedTable[ID, Row]) Delete(key string) bool
Delete removes a row and all of its index entries.
func (*OrderedTable[ID, Row]) Get ¶
func (t *OrderedTable[ID, Row]) Get(key string) (OrderedRow[ID, Row], bool)
Get returns one copied row.
func (*OrderedTable[ID, Row]) Len ¶
func (t *OrderedTable[ID, Row]) Len() int
Len returns the number of rows, including subsumed rows.
func (*OrderedTable[ID, Row]) MarkSubsumed ¶
func (t *OrderedTable[ID, Row]) MarkSubsumed(key string) bool
MarkSubsumed marks an existing row hidden from matching. It returns false when the row is absent or already subsumed.
func (*OrderedTable[ID, Row]) Put ¶
func (t *OrderedTable[ID, Row]) Put(key string, values []Value[ID], payload Row) (inserted bool, ok bool)
Put inserts or replaces a row. New rows receive the next stable order; replacements retain their existing order and subsumption state.
func (*OrderedTable[ID, Row]) PutAt ¶
func (t *OrderedTable[ID, Row]) PutAt(key string, values []Value[ID], payload Row, order uint64, subsumed bool) bool
PutAt inserts or replaces a row with an explicit order. It is used when folding rows whose keys collide after backend canonicalization.
func (*OrderedTable[ID, Row]) Range ¶
Range visits keys indexed for column and value. Iteration order is unspecified. It stops and returns false when visit returns false.
func (*OrderedTable[ID, Row]) ReplaceFrom ¶
func (t *OrderedTable[ID, Row]) ReplaceFrom(other *OrderedTable[ID, Row]) bool
ReplaceFrom atomically replaces row state from a table with equal index width. The receiver retains its identity for outstanding references.
func (*OrderedTable[ID, Row]) Rows ¶
func (t *OrderedTable[ID, Row]) Rows() []OrderedRow[ID, Row]
Rows returns copied rows in insertion order, with key as a tie breaker.
func (*OrderedTable[ID, Row]) SetCounters ¶
func (t *OrderedTable[ID, Row]) SetCounters(order, fresh uint64)
SetCounters advances table counters without moving them backwards.
type OwnedNode ¶
type OwnedNode[ID comparable, Node any] struct { Owner ID Node Node }
OwnedNode associates a canonical node with its current equivalence-class owner.
type OwnerPair ¶
type OwnerPair[ID comparable] struct { Left ID Right ID }
OwnerPair requests a union between two owners of equal nodes.
type Pattern ¶
Pattern is a structural term pattern. Variables bind canonical class IDs; non-variable leaves match zero-child nodes with the same operator.
func ParsePattern ¶
ParsePattern parses one S-expression structural pattern. Commas are separators and variable names begin with '?'. The parser uses an explicit stack so deeply nested patterns do not consume the Go call stack.
type RankedBestCostLookup ¶
type RankedBestCostLookup[ID ~uint32, Node, Rank any] func(ID) (RankedBestCostNode[Node, Rank], bool)
RankedBestCostLookup reads the selected state for one canonical class.
type RankedBestCostNode ¶
RankedBestCostNode is a selected node, its cost, and caller-defined rank. Rank can carry secondary extraction information such as expression size.
type RankedCostAcceptance ¶
type RankedCostAcceptance[ID ~uint32, Node, Rank any] func(class ID, candidate RankedBestCostNode[Node, Rank], lookup RankedBestCostLookup[ID, Node, Rank]) (bool, error)
RankedCostAcceptance may reject a candidate that is otherwise preferred, for example when selecting it would create a cycle. lookup is read-only; an error aborts relaxation and is returned to the caller.
type RankedCostEvaluation ¶
type RankedCostEvaluation[Node, Rank any] func(node Node, childStates []RankedBestCostNode[Node, Rank], allChildrenKnown bool) (cost float64, rank Rank, eligible bool, err error)
RankedCostEvaluation evaluates a node from the selected states of its children. childStates has one entry per child; entries are zero values when allChildrenKnown is false. The adapter decides whether an incomplete child set is eligible.
type Relation ¶
type Relation[ID ~uint32] struct { // contains filtered or unexported fields }
Relation is a set of typed tuples with one equality index per column. It is not safe for concurrent use. A backend supplies canonicalize to map class-valued cells to current representatives.
func NewRelation ¶
NewRelation creates an empty relation and validates its schema.
func (*Relation[ID]) Add ¶
Add inserts values after canonicalizing class values. It reports whether a new tuple was added. Invalid tuples are rejected without mutation.
func (*Relation[ID]) AddedSince ¶
func (r *Relation[ID]) AddedSince(cursor RelationCursor) ([][]Value[ID], error)
AddedSince returns facts added after cursor in insertion order. Additions are reported once; duplicate Add calls do not advance the version. A successful Delete, MarkSubsumed, or Recanonicalize invalidates old cursors; cursors used with unrelated, diverged, or old clones return ErrRelationReset. In either case the caller must recompute the current relation.
func (*Relation[ID]) AddedSinceWithBudget ¶
func (r *Relation[ID]) AddedSinceWithBudget(cursor RelationCursor, budget *WorkBudget) (rows [][]Value[ID], complete bool, err error)
AddedSinceWithBudget is AddedSince with bounded history lookup and row-copy work. complete is false when budget runs out; no partial rows are returned. A nil budget means unlimited work.
func (*Relation[ID]) Clone ¶
Clone returns an independent copy of r, including its indexes, delta history, and subsumed fact state. Cursors from r remain valid while their epochs remain in the bounded clone lineage. The clone has its own epoch so cursors from diverged clones cannot be mixed. The returned relation is not safe for concurrent use.
func (*Relation[ID]) Compact ¶
func (r *Relation[ID]) Compact(cursor RelationCursor) error
Compact discards additions at or before cursor to bound retained delta history. Cursors older than cursor become invalid and require recomputation. Callers with multiple consumers must pass the oldest cursor they still need.
func (*Relation[ID]) Delete ¶
Delete removes a tuple after canonicalizing class values. A successful deletion invalidates existing cursors because insertion-only deltas cannot represent retraction; callers must recompute and take a new snapshot.
func (*Relation[ID]) MarkSubsumed ¶
MarkSubsumed inserts values if absent and hides the resulting fact from Query while retaining it in Rows. It reports whether the fact was newly marked subsumed. A successful mark invalidates existing cursors because it changes the query-visible relation; callers must recompute and take a new snapshot.
func (*Relation[ID]) Query ¶
func (r *Relation[ID]) Query(filters []Filter[ID], canonicalize func(ID) ID, budget *WorkBudget) (rows [][]Value[ID], complete bool, err error)
Query returns matching rows in deterministic tuple-key order. Each candidate examined spends one unit; on exhaustion it returns no partial result and complete=false.
func (*Relation[ID]) Recanonicalize ¶
Recanonicalize atomically replaces class IDs with current representatives, merges duplicate rows, and rebuilds all indexes. It starts a new delta epoch; callers must recompute the resulting rows and take a new snapshot.
func (*Relation[ID]) SchemaWithBudget ¶
func (r *Relation[ID]) SchemaWithBudget(budget *WorkBudget) (Schema, error)
SchemaWithBudget returns a defensive schema copy after reserving its column backing storage. The budget's scope remains open through the copy's last use.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/egraphcore"
)
type exampleMemory struct{ used int64 }
func (m *exampleMemory) Reserve(bytes int64) error {
if bytes > 1<<20-m.used {
return errors.New("memory limit")
}
m.used += bytes
return nil
}
func (m *exampleMemory) Release(bytes int64) { m.used -= bytes }
func main() {
relation, _ := egraphcore.NewRelation[uint32](egraphcore.Schema{Name: "count", Columns: []egraphcore.Column{{Kind: egraphcore.Int64Value}}})
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(100, scope)
schema, err := relation.SchemaWithBudget(budget)
fmt.Println(schema.Name, len(schema.Columns), err)
}
Output: count 1 <nil>
func (*Relation[ID]) Snapshot ¶
func (r *Relation[ID]) Snapshot() RelationCursor
Snapshot returns a cursor at the current insertion history position. Cursors are relation-state-specific and become invalid after deletion, subsumption, or recanonicalization. A source cursor can be used with a descendant clone while its epoch remains in the bounded clone lineage.
type RelationCursor ¶
type RelationCursor struct {
// contains filtered or unexported fields
}
RelationCursor identifies a point in one relation's insertion history. Its fields are private; obtain cursors with Relation.Snapshot.
type ResolvedFactAction ¶
type ResolvedFactAction[ID ~uint32] struct { Kind FactActionKind Relation string Values []Value[ID] }
ResolvedFactAction is a typed relation mutation ready to apply.
func ResolveFactActions ¶
func ResolveFactActions[ID ~uint32](store *FactStore[ID], actions []FactAction[ID], binding Binding[ID], canonicalize func(ID) ID, budget *WorkBudget) ([]ResolvedFactAction[ID], error)
ResolveFactActions checks and evaluates every action against one binding. It returns no partial plan on invalid input or work exhaustion. Class values are canonicalized while resolving. A nil budget means unlimited work.
type RewriteApplicationReport ¶
RewriteApplicationReport summarizes one ordered batch of prepared term rewrites.
func ApplyMatches ¶
func ApplyMatches[ID ~uint32, Node, Match any]( graph Graph[ID, Node], matches []Match, class func(Match) ID, instantiate func(Match) (ID, error), instantiationWork func(Match) int, admit func(Match) error, budget *WorkBudget, rebuild bool, ) (RewriteApplicationReport, error)
ApplyMatches instantiates each prepared match in order, unions the result with its matched class, and optionally rebuilds once after the batch. Match search, validation, transactional staging, and backend side effects remain the caller's responsibility. A nil budget is unlimited; otherwise the budget charges one unit per match, estimated work for instantiate and admit, and one for a possible rebuild. instantiationWork must be deterministic, side-effect free, and return a conservative non-negative work estimate for those callbacks. The estimate callback itself and graph callback work are not included. admit, when non-nil, checks each match immediately before its RHS is instantiated. All charges are reserved before the first mutation. On error, the report describes mutations completed before the error; callers that require rollback must apply the batch to a staged graph and publish it only on success.
type RootPairStatus ¶
type RootPairStatus uint8
RootPairStatus reports the result of resolving two class IDs in a Store.
const ( RootPairInvalidID RootPairStatus = iota + 1 RootPairSame RootPairMissingClass RootPairDistinct )
type RuleMatch ¶
RuleMatch is one complete rule match. ClassID is anchored to the root of the first structural pattern; Binding contains values from structural and relation conditions.
func JoinMatches ¶
func JoinMatches[ID ~uint32]( anchors []Match[ID], structuralConditions [][]Match[ID], relationConditions []Atom[ID], canonicalize func(ID) ID, budget *WorkBudget, ) ([]RuleMatch[ID], error)
JoinMatches combines structural matches and positive relation conditions. anchors are the matches for the first structural LHS pattern. Each entry in structuralConditions is an alternative set for one additional structural condition. relationConditions are conjoined and joined with the structural bindings. The returned ClassID always comes from anchors, never a condition. Class-valued bindings are canonicalized before comparison and output. Results are deterministic and deduplicated. On work exhaustion, no partial result is returned. With no anchors, this function returns no matches; relation-only rules must provide a separate anchor policy.
func JoinMatchesDeltas ¶
func JoinMatchesDeltas[ID ~uint32]( anchors []Match[ID], structuralConditions [][]Match[ID], atoms []Atom[ID], deltas []DeltaAtom[ID], canonicalize func(ID) ID, budget *WorkBudget, ) ([]RuleMatch[ID], error)
JoinMatchesDeltas joins structural matches with bindings produced by JoinDeltas. Each delta identifies one relation atom changed since the corresponding cursor. No structural matches are returned when no delta bindings are available.
func JoinMatchesWithBindings ¶
func JoinMatchesWithBindings[ID ~uint32]( anchors []Match[ID], structuralConditions [][]Match[ID], relationBindings []Binding[ID], canonicalize func(ID) ID, budget *WorkBudget, ) (output []RuleMatch[ID], err error)
JoinMatchesWithBindings joins structural matches with a precomputed set of relation bindings. anchors are the matches for the first structural pattern. Each structuralConditions entry is an alternative set for one additional condition. relationBindings is the result of a required relation condition; an empty slice yields no matches. To represent no relation condition, pass one empty binding. ClassID is taken from anchors and class-valued bindings are canonicalized before comparison and output.
Results are deterministic and deduplicated. Work exhaustion returns no partial result. With no anchors, this function returns no matches. A nil budget or canonicalize function is invalid.
type SaturationLimits ¶
SaturationLimits bounds a fixed-point run. Non-positive limits are disabled; work is bounded by the supplied budget.
type SaturationPass ¶
type SaturationPass func(budget *WorkBudget) (changes, nodes int, complete bool, err error)
SaturationPass performs one complete pass over a rule group. It returns the number of changes, current node count, whether the pass completed, and any error. If the pass is incomplete or exceeds MaxNodes, adapters must not commit its effects. An incomplete result is classified as a node-limit stop when nodes exceeds MaxNodes, otherwise as a work-limit stop when budget is exhausted.
type SaturationResult ¶
type SaturationResult struct {
Iterations int
Changes int
Work int
Nodes int
StopReason SaturationStopReason
}
SaturationResult summarizes a fixed-point run. Iterations counts pass invocations, Changes sums completed pass changes, and Work is the budget's recorded work at return.
func RunFixedPoint ¶
func RunFixedPoint(limits SaturationLimits, budget *WorkBudget, initialNodes int, pass SaturationPass) (SaturationResult, error)
RunFixedPoint runs pass until it completes without changes or reaches a configured limit. A completed pass may consume the final work unit: if it reports no changes, the fixed point is known. Errors from pass are returned with the partial result.
type SaturationStopReason ¶
type SaturationStopReason uint8
SaturationStopReason describes why RunFixedPoint stopped.
const ( SaturationFixedPoint SaturationStopReason = iota + 1 SaturationIterationLimit SaturationWorkLimit SaturationNodeLimit SaturationScheduleDone SaturationTupleLimit SaturationTimeLimit SaturationRuleMatchLimit )
func (SaturationStopReason) String ¶
func (r SaturationStopReason) String() string
type Schedule ¶
type Schedule[R any] struct { // contains filtered or unexported fields }
Schedule describes an ordered plan for running backend-defined rules. Construct schedules with Run, Saturate, Sequence, and Repeat.
func Repeat ¶
Repeat creates a node that executes child at most count times. It stops early when one complete child execution reports no changes.
func RepeatNamed ¶
RepeatNamed creates a bounded repeat node with a stable execution name.
func Run ¶
Run creates a schedule node that executes rules as one ordered rule group. name identifies the group in execution paths and must be non-empty.
func Saturate ¶
Saturate creates a node that repeats child until a full child execution reports no changes, the callback halts, or the execution run limit is met.
func SaturateNamed ¶
SaturateNamed creates a fixed-point node with a stable execution name.
type ScheduleResult ¶
type ScheduleResult struct {
Runs int
Changes int
Halted bool
RunLimitReached bool
Reports []ScheduleRunReport
}
ScheduleResult reports executions and changes. RunLimitReached is true when the maximum number of rule callbacks was reached before the plan completed.
func ExecuteSchedule ¶
func ExecuteSchedule[R any](schedule *Schedule[R], maxRuns int, validateRule ScheduleRuleValidator[R], run ScheduleRun[R]) (ScheduleResult, error)
ExecuteSchedule validates and executes schedule in order. maxRuns must be positive and bounds the number of rule callback invocations. Run names are deterministic paths such as schedule/sequence[1]/repeat[0]/run(rewrite).
type ScheduleRuleValidator ¶
ScheduleRuleValidator validates one backend-defined rule.
type ScheduleRun ¶
ScheduleRun executes one ordered rule group as a phase. It returns the phase's change count, whether execution should halt, and any error.
type ScheduleRunReport ¶
ScheduleRunReport records one rule-group callback, including attempts that return an error. Path identifies the nested schedule location.
type Store ¶
Store owns the common, representation-independent state of an e-graph. Class values retain each backend's node representation and metadata. Callers must serialize mutations to a Store.
func (*Store[ID, Class]) AddMemoCandidate ¶
AddMemoCandidate appends id to the memo bucket selected by key.
func (*Store[ID, Class]) AddMemoCandidateIf ¶
AddMemoCandidateIf appends id unless an existing candidate satisfies same. The callback lets each backend define canonical candidate identity.
func (*Store[ID, Class]) AddMemoCandidateIfWithBudget ¶
func (s *Store[ID, Class]) AddMemoCandidateIfWithBudget(key string, id ID, same func(ID, ID) bool, budget *WorkBudget) (bool, error)
AddMemoCandidateIfWithBudget is AddMemoCandidateIf with storage admission. same must return borrowed results without allocating unreserved storage.
Example ¶
m := new(exampleMemory)
scope, _ := egraphcore.NewMemoryScope(m)
defer scope.Close()
b, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
s := egraphcore.NewStore[uint32, int]()
added, err := s.AddMemoCandidateIfWithBudget("a", 0, func(a, c uint32) bool { return a == c }, b)
fmt.Println(added, err)
Output: true <nil>
func (*Store[ID, Class]) CanonicalChildren ¶
func (s *Store[ID, Class]) CanonicalChildren(children []ID) []ID
CanonicalChildren returns the canonical representatives for children in their original order.
func (*Store[ID, Class]) Class ¶
func (s *Store[ID, Class]) Class(id ID) Class
Class returns the class record stored for id, or its zero value when absent.
func (*Store[ID, Class]) ClassCount ¶
ClassCount reports the number of stored class records.
func (*Store[ID, Class]) Clone ¶
Clone copies union-find and memo state and applies cloneClass to each class record. A nil cloneClass copies class values as-is.
func (*Store[ID, Class]) CloneWithBudget ¶
func (s *Store[ID, Class]) CloneWithBudget(cloneClass func(Class, *WorkBudget) (Class, error), budget *WorkBudget) (*Store[ID, Class], error)
CloneWithBudget copies the store's collections, reserving each object, backing array and map entry before allocation. The caller keeps budget's MemoryScope open until the copy is no longer used. Strings remain borrowed. cloneClass must copy backend-owned mutable data using the supplied budget; a nil callback borrows class values, as Clone does.
Example ¶
source := egraphcore.NewStore[uint32, int]()
source.Insert("leaf", func(uint32) int { return 7 })
scope, _ := egraphcore.NewMemoryScope(new(exampleMemory))
defer scope.Close()
budget, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
copy, err := source.CloneWithBudget(nil, budget)
fmt.Println(copy.Class(0), err)
Output: 7 <nil>
func (*Store[ID, Class]) Find ¶
func (s *Store[ID, Class]) Find(id ID) ID
Find returns the canonical class ID and compresses the traversed path.
func (*Store[ID, Class]) FindWithoutCompression ¶
func (s *Store[ID, Class]) FindWithoutCompression(id ID, maxVisits int) (root ID, visits int, ok bool)
FindWithoutCompression inspects at most maxVisits parent entries and leaves the store unchanged. visits includes the root entry. It returns false for invalid IDs, exhausted budgets, or malformed parent cycles.
func (*Store[ID, Class]) Initialized ¶
Initialized reports whether the class and memo tables have been created.
func (*Store[ID, Class]) Insert ¶
Insert allocates an ID, constructs its class record, and adds the ID to the selected memo bucket. The caller supplies the backend-specific key and class construction policy.
func (*Store[ID, Class]) InsertWithBudget ¶
func (s *Store[ID, Class]) InsertWithBudget(key string, newClass func(ID) (Class, error), budget *WorkBudget) (ID, error)
InsertWithBudget reserves the store's growth before publishing a new class. newClass owns admission of its class storage. The caller retains budget's scope through the last use of the store and any construction scratch.
Example ¶
m := new(exampleMemory)
scope, _ := egraphcore.NewMemoryScope(m)
defer scope.Close()
b, _ := egraphcore.NewWorkBudgetWithMemory(0, scope)
s := egraphcore.NewStore[uint32, int]()
id, err := s.InsertWithBudget("a", func(uint32) (int, error) { return 7, nil }, b)
fmt.Println(id, s.Class(id), err)
Output: 0 7 <nil>
func (*Store[ID, Class]) LinkRootsBySize ¶
LinkRootsBySize links the smaller root below the larger root. Equal-size roots are resolved by ID, keeping the result deterministic across backends.
func (*Store[ID, Class]) LookupClass ¶
LookupClass returns the class record stored for id and whether it exists.
func (*Store[ID, Class]) MergeRoots ¶
func (s *Store[ID, Class]) MergeRoots(root1, root2, winner ID, merge func(Class, Class) Class) (ID, bool)
MergeRoots links two existing class roots, combines their class records, and removes the losing record. The winner-selection and record-merge policies remain with the backend.
func (*Store[ID, Class]) MergeRootsBySize ¶
func (s *Store[ID, Class]) MergeRootsBySize(root1, root2 ID, merge func(Class, Class) Class) (ID, bool)
MergeRootsBySize merges two classes using the shared deterministic union-by-size policy. The merge callback combines backend-owned class data.
func (*Store[ID, Class]) Parent ¶
Parent returns the class ID that id links to in the union-find, without following the link further or compressing the path. A root links to itself. It returns false for an ID the store did not allocate. Parent lets a checker walk the union-find with its own code.
func (*Store[ID, Class]) RangeClasses ¶
RangeClasses calls visit for each class until it returns false.
func (*Store[ID, Class]) ResetMemo ¶
func (s *Store[ID, Class]) ResetMemo()
ResetMemo discards all hash-cons buckets while retaining class storage.
func (*Store[ID, Class]) ResolveRoots ¶
func (s *Store[ID, Class]) ResolveRoots(id1, id2 ID) (ID, ID, RootPairStatus)
ResolveRoots validates two IDs and returns their canonical roots. Same-root pairs are reported before class-record checks, matching checked union's no-op behavior. Distinct roots require class records for both IDs.
func (*Store[ID, Class]) VisitMemoCandidates ¶
VisitMemoCandidates visits the candidate bucket for key in insertion order. Returning false from visit stops the scan.
type Term ¶
Term is a wildcard, a named variable, or a typed constant.
type TopKBuild ¶
type TopKBuild[ID ~uint32, Node, Value any] func( class ID, node Node, children []TopKCandidate[Value], ) (TopKCandidate[Value], error)
TopKBuild combines a node with one candidate for each child, or returns a backend validation error.
type TopKCandidate ¶
TopKCandidate is one expression produced while enumerating an e-class. Value is owned by the backend; the core only combines candidates and reads Cost when constructing candidates through the supplied callback.
func ExtractTopK ¶
func ExtractTopK[ID ~uint32, Node, Value any]( root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, build TopKBuild[ID, Node, Value], nodeEligible TopKNodeEligible[ID, Node], less func(TopKCandidate[Value], TopKCandidate[Value]) bool, comboLess func(TopKCandidate[Value], TopKCandidate[Value]) bool, equal func(Value, Value) bool, budget *WorkBudget, ) ([]TopKCandidate[Value], error)
ExtractTopK enumerates acyclic expressions from root and returns exact top-k results for arbitrary build and equal callbacks. If child alternatives may collapse to the same parent value, it expands capped child result sets until the result is complete. This can enumerate the full finite acyclic search space; use a work budget to bound it, or use ExtractTopKWithChildPreservation when the build callback has the documented preservation property. Retries share the same work budget. Graph and ordering callbacks must return stable results across retries. The core owns traversal, cycle rejection, ancestor-sensitive memoization, and a bounded best-first heap for each node's child-choice combinations. Backend callbacks define graph access and expression semantics. build receives selected child candidates, allowing the backend to calculate and validate cost. less must provide a deterministic strict weak ordering. equal reports structural equality for backend values; equal candidates must have the same rank under less and comboLess. comboLess may order candidates that compare equal under less, but the combined order must also be monotone in each child: replacing one child with a later (no better) candidate must not produce a better parent candidate. This applies to the full tie-break order, not just cost. Nodes and children are visited in the order supplied by the backend. Backends are responsible for this cost-model property. A nil result with no error means there were no valid acyclic candidates. A nil result is also returned when k is nonpositive. A nil budget is unlimited. A non-nil budget charges graph visits, ancestor-sensitive memo keys, node and child scans, candidate builds, heap operations, duplicate comparisons, hash-key callback calls, and result sorting. Hash callback work is charged as one unit per call; its internal cost is backend-defined. Exceeding it returns ErrTopKWorkBudget without partial results. If the limit cannot be represented while expanding a result that may be truncated, ErrTopKExpansionLimit is returned. Traversal uses an explicit stack and is not limited by Go call-stack depth.
func ExtractTopKWithChildPreservation ¶
func ExtractTopKWithChildPreservation[ID ~uint32, Node, Value any]( root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, build TopKBuild[ID, Node, Value], nodeEligible TopKNodeEligible[ID, Node], less func(TopKCandidate[Value], TopKCandidate[Value]) bool, comboLess func(TopKCandidate[Value], TopKCandidate[Value]) bool, equal func(Value, Value) bool, budget *WorkBudget, ) ([]TopKCandidate[Value], error)
ExtractTopKWithChildPreservation uses the bounded top-k search when build preserves child distinctions: for a fixed class and node, two child tuples that differ under equal must build values that also differ under equal. In addition to the ordering requirements of ExtractTopK, this property lets each child contribute at most k alternatives without hiding a distinct parent result. Callers must ensure the property; it cannot be checked for child alternatives that have not been enumerated.
func ExtractTopKWithChildPreservationAndHash ¶
func ExtractTopKWithChildPreservationAndHash[ID ~uint32, Node, Value any]( root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, build TopKBuild[ID, Node, Value], nodeEligible TopKNodeEligible[ID, Node], less func(TopKCandidate[Value], TopKCandidate[Value]) bool, comboLess func(TopKCandidate[Value], TopKCandidate[Value]) bool, equal func(Value, Value) bool, hash func(Value) string, budget *WorkBudget, ) ([]TopKCandidate[Value], error)
ExtractTopKWithChildPreservationAndHash combines bounded child-preserving extraction with hash-based duplicate bucketing. hash must be consistent with equal; collisions are always checked with equal.
func ExtractTopKWithHash ¶
func ExtractTopKWithHash[ID ~uint32, Node, Value any]( root ID, k int, nodes func(ID) []Node, canonical func(ID) ID, children func(Node) []ID, build TopKBuild[ID, Node, Value], nodeEligible TopKNodeEligible[ID, Node], less func(TopKCandidate[Value], TopKCandidate[Value]) bool, comboLess func(TopKCandidate[Value], TopKCandidate[Value]) bool, equal func(Value, Value) bool, hash func(Value) string, budget *WorkBudget, ) ([]TopKCandidate[Value], error)
ExtractTopKWithHash is ExtractTopK with hash-based duplicate bucketing. hash must return the same key for values considered equal by equal. Hashes only select a bucket; equal remains the authority when resolving collisions.
type TopKNodeEligible ¶
TopKNodeEligible may exclude a node before its child alternatives are enumerated. A nil callback accepts every node.
type Value ¶
type Value[ID ~uint32] struct { Kind ValueKind Class ID Int64 int64 Bool bool Float uint64 String string }
Value is a comparable typed value suitable for a relation column. Float64 values are represented by their IEEE bits, so NaNs and signed zero remain distinct facts.
func MergeFunctionValue ¶
func MergeFunctionValue[ID ~uint32]( policy FunctionMergePolicy, old, incoming, constant Value[ID], callbacks FunctionMergeCallbacks[ID], ) (Value[ID], error)
MergeFunctionValue combines two results using a backend-neutral policy. Backends validate column sorts and canonicalize inputs before calling it. Union and Custom delegate operations that depend on graph state or a backend-defined expression language.
type ValueIndex ¶
type ValueIndex[ID ~uint32] struct { // contains filtered or unexported fields }
ValueIndex maps each value in a row column to the keys of rows containing that value. It is not safe for concurrent use. Rows remain owned by the caller; the index stores only their comparable values and row keys.
func NewValueIndex ¶
func NewValueIndex[ID ~uint32](columnCount int) *ValueIndex[ID]
NewValueIndex creates an index with columnCount columns.
func (*ValueIndex[ID]) Add ¶
func (index *ValueIndex[ID]) Add(row []Value[ID], key string) bool
Add records key in the index for every value in row. It returns false when the row has the wrong number of columns or the index is nil.
func (*ValueIndex[ID]) Clone ¶
func (index *ValueIndex[ID]) Clone() *ValueIndex[ID]
Clone returns an independent copy of the index.
func (*ValueIndex[ID]) Contains ¶
func (index *ValueIndex[ID]) Contains(column int, value Value[ID], key string) bool
Contains reports whether key is indexed for column and value.
func (*ValueIndex[ID]) Count ¶
func (index *ValueIndex[ID]) Count(column int, value Value[ID]) int
Count reports the number of row keys indexed for column and value.
type WorkBudget ¶
type WorkBudget struct {
// contains filtered or unexported fields
}
WorkBudget tracks work units used by a search or rewrite pass. A positive limit is enforced; a non-positive limit means unlimited work.
func NewWorkBudget ¶
func NewWorkBudget(limit int) *WorkBudget
NewWorkBudget creates a work budget. A positive limit bounds TrySpend; zero or a negative limit means unlimited work.
func NewWorkBudgetWithMemory ¶
func NewWorkBudgetWithMemory(limit int, scope *MemoryScope) (*WorkBudget, error)
NewWorkBudgetWithMemory attaches the caller-owned result scope to a work budget. Keep scope open until all returned matches, bindings and expressions are no longer used. The work and memory limits are independent.
Example ¶
package main
import (
"errors"
"fmt"
"github.com/tmc/lib/egraphcore"
)
type exampleMemory struct{ used int64 }
func (m *exampleMemory) Reserve(bytes int64) error {
if bytes > 1<<20-m.used {
return errors.New("memory limit")
}
m.used += bytes
return nil
}
func (m *exampleMemory) Release(bytes int64) { m.used -= bytes }
func main() {
memory := new(exampleMemory)
scope, err := egraphcore.NewMemoryScope(memory)
if err != nil {
fmt.Println(err)
return
}
defer scope.Close() // Matches remain owned until their last use below.
budget, err := egraphcore.NewWorkBudgetWithMemory(1000, scope)
if err != nil {
fmt.Println(err)
return
}
pattern := &egraphcore.Pattern{Op: "?x", Variable: true}
matches, limited, err := egraphcore.Search(pattern, []uint32{2, 5}, budget, 10,
func(id uint32) uint32 { return id }, func(uint32) []string { return nil },
func(node string) string { return node }, func(string) []uint32 { return nil })
fmt.Println(len(matches), limited, err)
}
Output: 2 false <nil>
func (*WorkBudget) Exhausted ¶
func (b *WorkBudget) Exhausted() bool
Exhausted reports whether a bounded budget has been fully spent.
func (*WorkBudget) MemoryError ¶
func (b *WorkBudget) MemoryError() error
MemoryError returns the first failed memory reservation, if any.
func (*WorkBudget) MemoryScope ¶
func (b *WorkBudget) MemoryScope() *MemoryScope
MemoryScope returns the borrowed result owner attached to b. A nil result means allocation is unlimited. The caller that created the scope closes it.
func (*WorkBudget) Remaining ¶
func (b *WorkBudget) Remaining() int
Remaining returns the remaining bounded work. math.MaxInt denotes an unlimited budget; a nil budget has no remaining work.
func (*WorkBudget) ReserveMemory ¶
func (b *WorkBudget) ReserveMemory(bytes int64) bool
ReserveMemory checks storage before allocation. A nil work budget carries no memory capability. A false result is available through MemoryError.
func (*WorkBudget) TrySpend ¶
func (b *WorkBudget) TrySpend(units int) bool
TrySpend records units of work and reports whether the budget permits them. Negative units are invalid and return false. In unlimited mode the used counter saturates at the largest int rather than overflowing.
func (*WorkBudget) Used ¶
func (b *WorkBudget) Used() int
Used returns the recorded work count. In unlimited mode this count saturates at the largest int if the exact total cannot be represented.
Source Files
¶
- additive_extract.go
- analysis.go
- apply.go
- budget.go
- candidate_lattice.go
- children.go
- choice.go
- choice_fingerprint.go
- choice_match.go
- choice_materializer.go
- choice_space.go
- clone_memory.go
- congruence.go
- congruence_driver.go
- cost.go
- cycle.go
- delta_join.go
- discrete_choice.go
- doc.go
- evaluate.go
- extract.go
- factaction.go
- factstore.go
- function_merge.go
- graph.go
- join.go
- join_order.go
- match_bindings.go
- match_join.go
- measured_search.go
- memo.go
- memory.go
- mutation_memory.go
- ordered_table.go
- parse.go
- pattern.go
- relation.go
- saturation.go
- schedule.go
- store.go
- topk.go
- union.go
- unionfind.go
- value_fingerprint.go
- value_index.go