Documentation
¶
Overview ¶
Package datalog is a Datalog engine for graph-shaped data: a small declarative query language whose every answer carries the provenance of the facts that produced it.
It supports conjunction, comparison, stratified negation, recursion to a fixpoint, aggregation with `having` and `distinct` in the answer and in a rule head (stratified, as negation is), `order by`, `limit` and `offset`, and computed predicates. A Query is the whole program: rules that define derived relations, a goal to solve, and the columns to answer with. An answer is sorted, absent values first, then numbers by value, then text, unless `order by` says otherwise. Parse reads the text syntax; the builders (V, Rel, Pos, Def, Build, ...) construct the same Query in code.
The engine knows nothing about any domain. Names come from an ns.Vocabulary, the namespace tree a host composes from base relations, predicates and derived modules (see package ns). This package provides Language, which lets a vocabulary hold modules written in Datalog, and NewBase, which pairs a vocabulary with one Source's facts for querying. A host builds and checks its vocabulary once and builds a Base per dataset; every Base over a vocabulary shares its resolved modules.
A query naming a derived relation pulls in the module that defines it, and whatever that module reads, when it is linked (Link, which Eval does first). A linked query is an ordinary query: the evaluator never sees a module. Inside a module's text a bare name is that module's member first and the root's second, and a member starting with "_" is private to its module.
A derived relation may declare its arguments' types in a rule head, `has_test_point(?n: net) :- ...`, and what it leaves undeclared is inferred through its rules, following agni's column typing. ColumnKinds carries the kinds through to a query's answer columns. A constant, or a bound value, is read as the type of the argument it stands in, or of the number it is compared with, and refused when it cannot be, so a question asked with the wrong type fails rather than answering empty.
A Base caches and indexes what it reads, and keeps the derived relations SemiNaive evaluated in full for later queries (see Base.LimitDerivedCache, Base.Forget and ns.Versioned), so one Base serves many queries, concurrently, and an Evaluator answers a Query over it. A Source that implements ns.LookupSource is asked for the facts a call with bound arguments needs, rather than read whole, and what it returns is kept for that one Eval. SemiNaive is the one to run: it derives recursive rules semi-naively, inlines single-rule non-recursive relations so a bound argument reaches the literals that can use it, derives a relation called with bound arguments only for the values demanded (magic sets, with right-linear recursion from a constant start reduced to the set of nodes it visits), and plans each body, so a literal runs once as much as possible is bound and a generator once one of its Modes is satisfied. Each round of the fixpoint starts from its delta when that is the smaller side. Naive is the reference: written order, naive fixpoint, kept simple so every faster strategy can be tested against it. Every Eval takes a context, which reaches the host's generators and cancellable Sources, and options: Bind gives goal variables values from the host (one, or a set the variable ranges over), Budget limits the work one Eval may do, and Witnesses records how each answer was derived (Row.Witness), as the tree of rules and facts behind it.
A Source that implements ns.TimedSource serves several versions of its facts, each fact once with the versions it holds in, and At(v) answers at one of them as a Base over only that version's facts would, while Base.Diff lists a relation's facts gained and lost between two. Across(vs) evaluates once over many versions, each row carrying the versions it holds in (Row.Versions). A TimedSource that is an ns.SourceAt serves each version as a Source of its own, which At(v) reads as it reads any Source, through its lookups, pushes and walks, and one that is an ns.TimedLookupSource is asked by Across for what a call binds.
Evaluation is guaranteed to terminate because no rule can invent a value: every answer is built from constants in the facts and values a host's generators draw from finite data. That guarantee is why the value model is scalar for now.
The engine was extracted from agni (github.com/panyam/agni), an EDA tool that queries circuit designs, and the examples in these comments use its vocabulary: component-on-net(ref, net) places a part on a net, reaches(from, to) walks a circuit's series connections, and so on. References to "agni issue N" point at the history behind a rule.
The package imports only the standard library and jaala/ns, and builds for GOOS=js GOARCH=wasm.
Index ¶
- Constants
- Variables
- func ExplainName(s string) string
- func NonInjectiveRules(q Query) []string
- func Reads(q Query, reg *ns.Vocabulary) []string
- func Validate(q Query, reg *ns.Vocabulary) error
- func ValidateBound(q Query, reg *ns.Vocabulary, vars ...Var) error
- type Aggregate
- type Atom
- type Base
- func (b *Base) Diff(ctx context.Context, rel string, from, to ns.Version) (Diff, error)
- func (b *Base) Forget()
- func (b *Base) KeepDerivedIn(s ns.DerivedStore)
- func (b *Base) LimitDerivedCache(tuples int)
- func (b *Base) LimitLookupCache(tuples int)
- func (b *Base) LimitVersions(n int)
- func (b *Base) Source() ns.Source
- func (b *Base) Unindexed() *Base
- func (b *Base) Vocabulary() *ns.Vocabulary
- func (b *Base) Work() int64
- type Body
- type BodyAggregate
- type BodyReport
- type BudgetExceeded
- type CheckError
- type ColdReport
- type ColumnKind
- type Compare
- type Diff
- type EmptyReport
- type ErrorKind
- type Evaluator
- type Expr
- type IndexReport
- type Literal
- type LiteralReport
- type Naive
- type Option
- type Order
- type ParseError
- type Position
- type Query
- type RelationReport
- type Report
- type Row
- type Rule
- type SemiNaive
- func (s SemiNaive) Eval(ctx context.Context, q Query, b *Base, opts ...Option) ([]Row, error)
- func (s SemiNaive) EvalTable(ctx context.Context, q Query, b *Base, opts ...Option) (*Table, error)
- func (s SemiNaive) Materialize(ctx context.Context, q Query, b *Base, rels []string, opts ...Option) error
- type SourceReport
- type Table
- type Term
- type Var
- type Warning
- type Witness
Constants ¶
const IndexMinTuples = indexMinFacts
IndexMinTuples is the relation size below which scanning beats indexing, exported so a host's equivalence test can build data large enough to exercise the indexed path.
const LanguageName = "datalog"
LanguageName is the name Language registers under, for ns.Vocabulary.AddModule.
Variables ¶
var Language ns.Language = language{}
Language is Datalog as a module language for an ns.Vocabulary. A host registers it once, then adds modules written in it:
v.AddLanguage(datalog.Language)
v.AddModule("net", datalog.LanguageName, `has_test_point(?n: net) :- component.net(?tp, ?n), ...;`, "lib/net.dl")
A module's text is rules only. Each rule head names a member of the module, written bare: `has_test_point(?n) :- ...` at "net" defines net.has_test_point. Inside the text a bare name is this module's member first, among members of every kind and from any module at the same path, and then the root's; a dotted name is always a full path. So in module "net", `pin_count(?n, ?c)` reads net.pin_count when that is registered, and `component.pin(...)` reads component.pin wherever it sits.
A member whose name starts with "_" is private to its module: it gets no path, no query can name it, and another module's _helper is a different relation. A rule head may declare its arguments' types, `has_test_point(?n: net)`; an argument no head declares is inferred, and Check refuses a declaration its rules contradict. The comment lines directly above a member's first rule are its doc.
Functions ¶
func ExplainName ¶ added in v0.1.24
ExplainName makes query text that holds the names rewrites give their relations and variables readable: reach/bf is reach called with its first argument bound, demand:reach/bf the values demanded of it, reach/bf+ what a semi-naive round added to it, prefix:0 a stored body prefix, reach:from1 and reach:answer1 a factored walk, pushed{edge(?a, ?b), edge(?b, ?c)} a conjunction the Source evaluated (#237), values:x a set-bound variable's values, facts:edge(?a, ?b, ?r) a call binding its fact to ?r (#279), closure:edge the relation graph.closure walks (#281), paths:edge the one graph.paths walks (#280), and ?1.x a variable inlining renamed. Report uses it for every rule and literal it shows.
func NonInjectiveRules ¶
NonInjectiveRules reports rules whose body puts two DIFFERENT variables in the SAME argument position of the SAME relation without separating them, naming each offender by its head relation. Empty means every such pair is separated.
Datalog matches by homomorphism, so two body variables may bind the same node. Circuit intent is almost always the opposite: a divider's two resistors must be two parts, a pull-up's rail must not be the net it pulls up. The language cannot say that, so an author writes a disequality by hand and forgetting one is neither a parse error nor a crash. It is a silently wrong verdict.
The shipped case that shows the cost: the interface-presence rule derives "in use" from two matching signals, `has_signal(?x), has_signal(?y), ?x != ?y`. Drop that comparison and one matching signal satisfies "two distinct signals are present", so an interface reports itself in use on half the evidence and every completeness check scoped to it inherits the mistake, with nothing in the output saying so.
SCOPE, stated because it is narrower than it looks, and deliberately so.
It reports SAME-relation, SAME-position pairs only. That is the shape both shipped disequalities guard, and it is the one where two variables are interchangeable by construction: the relation says what the position means, so two variables there range over the same set. Comparing variables ACROSS positions or across different relations would be guesswork about sorts the query language does not carry.
It is therefore silent on a rule like
clamped(?n) :- reaches(?n, ?rn, ?h), ?h <= 2, component-on-net(?t, ?rn), component.class(?t, "tvs")
where ?n and ?rn are both nets and no disequality relates them. That is CORRECT rather than a miss: `reaches` is reflexive (from == to at distance zero), so a clamp on the net itself is a genuine answer and separating the two would break the rule. Two positions of one atom are not the interchangeable shape; two atoms of one relation are.
It examines rule bodies, not the goal, because a goal is written per query by someone reading its result while a rule is authored once and consumed silently.
func Reads ¶
func Reads(q Query, reg *ns.Vocabulary) []string
Reads returns the base relations a query references, the ones reg holds as base relations, sorted and deduped. Rule-defined relations and predicates are excluded; only base relations count as reads. A host uses it to declare which facts a query-backed check depends on.
It counts reads inside the module relations the query reaches, since a check built on net.has_test_point depends on whatever net.has_test_point reads, and only those: a relation defined beside it in the same module, but never reached, is not a dependency. When the query does not link, it reports the query's own reads, and Validate says why.
func Validate ¶
func Validate(q Query, reg *ns.Vocabulary) error
Validate reports why a query cannot run, reading only the query and the vocabulary it would run against: the schemas of its base relations, its predicates and its derived modules, which it links first (see Link). No tuple is read.
It exists because a rule compiled from a query used to be un-rejectable: RuleFromQuery returned no error, and the failure surfaced only when the rule ran, where it was swallowed into a clean pass (agni issue 540). Every fault a query can carry turns out to be static — an unknown relation, a wrong arity, a negation with nothing to range over, a projected variable nothing binds, a rule head colliding with a fact relation, recursion through negation — so the check belongs where the rule is BUILT rather than where it first meets a design.
It cannot be implemented by evaluating against an empty fact base, which is the obvious shortcut. Solving stops at the first atom that yields nothing, so on an empty base every atom after the first goes unexamined and a wrong-arity relation in position two passes validation.
func ValidateBound ¶ added in v0.1.14
func ValidateBound(q Query, reg *ns.Vocabulary, vars ...Var) error
ValidateBound is Validate for a query whose host will Bind the given goal variables when it runs it. A bound variable counts as a constant written in the goal, as it does in Eval, so a variable that appears only inside a `not`, or one a generator's mode needs bound, is accepted when the host binds it and still refused when it doesn't (#61). Only the names matter: each stands in as an absent value, which neither coercion nor a closed Domain refuses (#68). Naming a variable the goal does not use is the error Eval gives for binding one.
Types ¶
type Aggregate ¶
type Aggregate struct {
Func string // count | min | max | sum | list
Var Var
// Distinct reduces Var's distinct values rather than one entry per binding. Spelled
// `count(distinct ?x)`. Bare aggregates keep their binding-wise meaning, so no existing query
// moves.
Distinct bool
}
An Aggregate reduces Var over each group of the projection's plain-variable columns. Example: `component-on-net(?ref,?net) => ?net, count(?ref)` groups by ?net and counts the ?ref bindings per group (parts per net); Aggregate{Func: "count", Var: "ref"}. min/max/sum reduce Var's numeric value over the group, and list joins its values.
EVERY AGGREGATE REDUCES BINDINGS, NOT VALUES, unless Distinct is set. A binding is the unit the whole evaluator deals in, so a group holds one row per solution and a goal that binds anything Var does not determine repeats Var once per combination. On a net carrying 7 test points and 20 capacitors, `component.class(?tp,"test_point"), component-on-net(?tp,?net), component.class(?c,"capacitor"), component-on-net(?c,?net) => ?net, count(?tp)` reports 140.
Distinct reduces the SET of Var's values instead: count(distinct ?tp) is 7 on that net, and list(distinct ?tp) names those 7 once each. It is uniform across every function rather than special-cased on count, deliberately. Making list implicitly distinct would put count(?tp) and list(?tp) in one projection disagreeing about what the group holds, 140 against 7, with nothing in the query saying why — which is this same trap one function over, and harder to see because both columns look right on a group of size one.
A derived relation is the other way to get a distinct reduce, by projecting the extra variable away before the group forms:
has_tp(?n) :- component-on-net(?x,?n), component.class(?x,"test_point"); component.class(?p,"capacitor"), component-on-net(?p,?n), has_tp(?n) => ?p, count(?n)
The rule makes has_tp a SET of nets, so count(?n) counts nets whether or not Distinct is set.
type Atom ¶
type Atom struct {
Relation string
Args []Term
// Fact is the variable `edge(?a, ?b) as ?r` binds to the fact the atom matched (#279): the
// Source's Tuple.ID, or the relation and values when it gives none. Only a positive atom over a
// base relation binds one, and lowerFacts rewrites it into a call to the relation's fact relation
// before any check reads the program, so nothing after it sees the field set.
Fact Var
}
An Atom applies a relation to argument terms: Relation(Args...). Relation is an EDB name a Source serves, a computed predicate, or an IDB name a Rule defines. Example: `component.mpn(?r,?m)` is Atom{Relation: "component.mpn", Args: [Var("r"), Var("m")]}.
type Base ¶
type Base struct {
// contains filtered or unexported fields
}
Base is the queryable fact base: a Vocabulary's names, with one Source's relations indexed by binding pattern on first use. Built once per dataset; many queries reuse it, including concurrently.
Concurrency. Any number of goroutines may Eval on one Base at once, with any evaluators, mixed: Naive and SemiNaive in any mode share a Base safely. Each Eval derives its rules into its own copy, so derived relations and their indexes never cross queries. What is shared is read-mostly and guarded: each base relation is read from the Source once, however many Evals ask for it at the same moment (the others wait for that read), and each of its indexes is built once. Work, Source, Vocabulary and Unindexed are safe at any time; Work totals the work of every Eval on the Base, while each Eval's context and Budget are its own. The vocabulary's resolved modules are shared through its memo.
Not safe: registering into the Vocabulary while Evals run on a Base over it.
Host code is called without any jaala lock held. A generator may run in several Evals at once and must be safe for that, or serialize itself, as a host whose engine has one connection would.
func MustBase ¶ added in v0.1.3
func MustBase(v *ns.Vocabulary, src ns.Source) *Base
MustBase is NewBase for a Source known to match its vocabulary, such as a test fixture. It panics on the error NewBase would return.
func NewBase ¶
NewBase builds a fact base that answers with v's names over src's facts. A host composes and checks its vocabulary once, and builds a Base per dataset it reads: every Base over v shares v's resolved modules and signatures, and each reads tuples, and hands generators, only its own Source.
The vocabulary stays the authority on what each relation is. src must serve every base relation v holds, at the same arity, and NewBase refuses it otherwise, naming each relation that is missing or disagrees: a relation silently reading as empty would answer as if the dataset had none of it. Relations src serves beyond v's are ignored, since no query can name them.
v is read, never changed, by any number of Bases at once; registering into it while they evaluate is not supported. A nil v is a base that knows no names at all.
func (*Base) Diff ¶ added in v0.1.61
Diff is how rel's facts changed from version from to version to of the Base's ns.TimedSource (#179). A fact is its values, read as the engine reads them (as rel's declared types, units folded), so a fact whose citations changed and nothing else is in neither list. Each list is in the order the Source serves its facts. A relation the vocabulary doesn't hold, a Base whose Source isn't a TimedSource, or a version it doesn't serve is refused.
func (*Base) Forget ¶ added in v0.1.23
func (b *Base) Forget()
Forget drops everything the Base has cached: base relations' tuples and indexes, the derived relations kept for later queries, and what the Source's Lookup returned (#212). The next query reads the Source again. A host calls it after changing a Source's facts in place; a Source that reports a Version doesn't need it. A query running meanwhile finishes on what it already read, and keeps nothing it derived.
func (*Base) KeepDerivedIn ¶ added in v0.1.58
func (b *Base) KeepDerivedIn(s ns.DerivedStore)
KeepDerivedIn keeps the derived relations the Base evaluates in full in s too, behind its own memory, filed by the relation's rules and the Source's version (#220), so another Base over the same facts, in this process or another, reads them from s instead of deriving them. Only a Versioned Source's relations go to s, and s is read when the Base's memory misses, so LimitDerivedCache(0) leaves s as the only tier. A nil s stops using one. It applies to the Base and every copy of it, and is safe to call while queries run. See ns.DerivedStore for what s must do.
func (*Base) LimitDerivedCache ¶ added in v0.1.23
LimitDerivedCache sets how many derived tuples, across all relations, the Base keeps for later queries (#140); 0 keeps none. A relation larger than the limit is never kept, and when one would overflow it, the relations used least recently are dropped first. It applies to the Base and every copy of it, such as Unindexed's, and is safe to call while queries run.
func (*Base) LimitLookupCache ¶ added in v0.1.44
LimitLookupCache sets how many tuples a LookupSource returned, across all lookups, the Base keeps for later queries (#212); 0 keeps none, so every query asks the Source again. A result that matched nothing counts as one, since knowing a value has no facts saves a call too. When a result would overflow the limit, the ones used least recently are dropped first, and one larger than the limit is never kept. It applies to the Base and every copy of it, and is safe to call while queries run. A query keeps whatever it looked up until it finishes, whatever the limit.
func (*Base) LimitVersions ¶ added in v0.1.61
LimitVersions sets how many versions' caches the Base keeps for At, the ones used least recently dropped first (8 by default; 0 keeps none, so each Eval at a version reads its facts again). A version's caches are as large as a Base's over its facts, so a host asking about many versions in turn bounds them here. The facts themselves are read from the TimedSource once, for every version.
func (*Base) Unindexed ¶
Unindexed returns a Base over the same vocabulary and Source that scans every base relation instead of consulting an index. It answers exactly as the indexed Base does, only slower, which is what makes it useful: comparing the two is how a host asserts that indexing changed no answer on its own data, rather than hoping so.
func (*Base) Vocabulary ¶ added in v0.1.3
func (b *Base) Vocabulary() *ns.Vocabulary
Vocabulary returns the vocabulary this base resolves names in.
type Body ¶
type Body struct{ Literals []Literal }
A Body is an implicit conjunction (AND) of Literals. Disjunction (OR) is several Rules sharing one Head relation — never an OR node — so the program stays stratifiable. Example: the body of `a(?x), b(?x,?y), ?y < 5` is Body{Literals: [Atom a, Atom b, Compare]}.
type BodyAggregate ¶ added in v0.1.31
A BodyAggregate binds Result to an aggregate over the bindings of Body, reduced once per value of the variables Body shares with the rest of the clause (#71): `part(?r), ?c = count(?n) : { pin(?r, ?n, _) }` counts each part's pins. Every value the rest of the clause gives those variables gets a row, so a part with no pins counts 0. Over no bindings count and sum are 0, min and max absent and list empty, as an aggregate over nothing answers in a projection (#122).
Body reads only relations complete before the clause's own, as a rule head aggregate does, and a shared variable has to be bound outside the braces by a positive relation and inside them by one.
type BodyReport ¶ added in v0.1.24
type BodyReport struct {
// Rule is the rule as written, when this body came from one; a body the demand rewrite added has
// none. Ran is the body as evaluated, after inlining, demand and planning, with the names those
// rewrites give their relations made readable (see ExplainName).
Rule string `json:"rule,omitempty"`
Ran string `json:"ran"`
// Relation is the relation the body derives tuples of, by its written name; "" for the goal and
// for a body that only stores a demanded prefix.
Relation string `json:"relation,omitempty"`
Runs int `json:"runs"` // times the body was solved
Tuples int `json:"tuples,omitempty"` // tuples it added that were new
// Work is its literals' work, and what storing the tuples it derived cost.
Work int64 `json:"work"`
Elapsed time.Duration `json:"elapsed_ns"`
Literals []*LiteralReport `json:"literals"`
}
A BodyReport is one body as it ran: a rule's, or the goal's.
type BudgetExceeded ¶ added in v0.1.9
type BudgetExceeded struct {
Work, Limit int64
}
BudgetExceeded is the error an Eval stops with when its work passes its Budget, so a host can tell a query that ran too long from one that is wrong. Work counts the streamed tuples read too, so it can be more than Base.Work or Report.Work saw.
func (*BudgetExceeded) Error ¶ added in v0.1.9
func (e *BudgetExceeded) Error() string
type CheckError ¶ added in v0.1.65
type CheckError struct {
Kind ErrorKind
// Fix says how to change the program when the engine can tell: the vocabulary's suggestion for a
// name, the expected signature for an arity, what to bind for an unbound variable. "" when it
// can't, as for a cycle through negation.
Fix string
// Rule is the head relation of the rule the error is in, "" for the goal or when the check
// doesn't know.
Rule string
// Relation is the call the error is about, and Args its argument count as written, or -1.
Relation string
Args int
// Var is the variable the error is about, without "?".
Var string
// Arg is the argument of Relation's call the error is about, from 0, when it is about a value
// written there (a constant its type or Domain refuses), else -1. Locate then finds the call
// holding that value, rather than the first call to Relation.
Arg int
// contains filtered or unexported fields
}
A CheckError is what Validate and Eval return for a program that can't run as written: a name the vocabulary doesn't hold, a call at the wrong arity, a variable nothing binds, a cycle through negation (#321). Its message is the one the engine has always written, so a host matching on fragments sees no change; the fields say the same thing as data, so a host can count failures by Kind and a model can be told how to fix one.
A Query carries no positions (a host may build one in Go, and two parses of one text compare equal), so the error names what it is about instead: Locate finds that in the program's text.
func (*CheckError) Error ¶ added in v0.1.65
func (e *CheckError) Error() string
type ColdReport ¶ added in v0.1.25
type ColdReport struct {
Work int64 `json:"work"`
Lookups int64 `json:"lookups,omitempty"`
Batches int64 `json:"batches,omitempty"`
Fetched int64 `json:"fetched,omitempty"`
Pushes int64 `json:"pushes,omitempty"`
Walks int64 `json:"walks,omitempty"`
// Error is why the cold run stopped, such as the Eval's Budget, when it did.
Error string `json:"error,omitempty"`
}
A ColdReport is an Eval's cost with nothing kept from earlier queries: no derived relation reused (#140), and every relation it read whole counted as fetched. Unlike Report's Work, which depends on what ran on the Base before, it is the same for one query over one Base however often it runs, so it is the number to compare queries or plans by, or to suggest a budget from. When the Eval did reuse something (or the Base held whole a relation the Source would otherwise have been asked to look up), Explain finds it by running the query again on a copy of the Base that keeps nothing, which doesn't count toward Base.Work but does read the Source again; otherwise it is Report's own numbers.
type ColumnKind ¶ added in v0.1.2
type ColumnKind struct {
// Kind is the entity kind of every cell in the column.
Kind string
// KindFrom is the variable whose value in each row is that row's kind. It must be read from the
// solution rather than the projection when it is not itself a column.
KindFrom Var
// Owner is the term that locates a Kind entity found only through another, such as the component
// a pin belongs to: a variable to read from each row, or a constant.
Owner Term
// Type and Unit describe a column that is a plain value.
Type, Unit string
}
A ColumnKind is what one answer column denotes, for a host deciding what a cell is, such as whether it can be clicked. Exactly one of the three shapes holds, or none for a plain value.
func ColumnKinds ¶ added in v0.1.2
func ColumnKinds(q Query, reg *ns.Vocabulary) ([]ColumnKind, error)
ColumnKinds reports what each answer column of q denotes, in Select order (or goal-variable order when Select is empty), read from what the vocabulary's relations declare and inferred through the query's rules and the modules it links. An aggregate is a number whatever it reduces: count(?ref) counts parts, it does not name one.
type Compare ¶
A Compare is a built-in predicate over two terms, evaluated once both are bound: Left Op Right, Op in {<, <=, =, !=, >, >=}. Numeric when both bound values carry a number, string otherwise.
type Diff ¶ added in v0.1.61
A Diff is what changed in a base relation between two versions of a TimedSource: the facts that hold in the second and not the first, with the second's citations, and those that held in the first and not the second, with the first's (see Base.Diff).
type EmptyReport ¶ added in v0.1.68
type EmptyReport struct {
// Rule is the rule as written whose body the literal is in; "" for the goal's.
Rule string `json:"rule,omitempty"`
// Literal is the literal as it ran (see ExplainName), which a rewrite may have moved: an inlined
// rule's literal shows in its caller's body.
Literal string `json:"literal"`
// Called is the first call of it that passed nothing, with the variables bound by then written as
// their values. "" when it was never reached.
Called string `json:"called,omitempty"`
// Alone says whether the literal's atom, run by itself with only its constants bound, matches
// anything (#348): false says the data holds nothing like it (a wrong value or name), true that it
// matches alone and only the values the literals before it bound found nothing (a wrong join). nil
// when it wasn't run: for a comparison or a `not`, a relation of the Source's the Base doesn't hold
// (one streamed, or only looked up) unless the Source looks it up and the call has a constant, since
// otherwise the probe reads the store whole, a probe the budget stopped (the Eval's Budget, or
// probeBudget when it has none) or one that failed. The probe counts toward neither Work nor
// Base.Work. A whole read from a Source that doesn't stream isn't charged to a budget, so a derived
// atom whose rules read one is read whole.
Alone *bool `json:"alone,omitempty"`
// Relation and Args are the literal's atom as written, when it is one: the relation it reads and
// each argument's constant, nil for a variable or an expression. A host says what the data holds
// where the atom matched nothing from them (nl.Pack.Hint), without parsing Literal. Both are empty
// for a comparison or a `not`.
Relation string `json:"relation,omitempty"`
Args []*ns.Value `json:"args,omitempty"`
Because []*EmptyReport `json:"because,omitempty"`
}
An EmptyReport is the first literal of a body, in the order the body ran, that passed no binding on: a call that matched nothing, a comparison that held for none, or a `not` that let nothing through. The goal's is the report's root. When that literal reads a derived relation none of whose rules derived anything, Because holds the same for each of those rules, so the trail ends at the literal over the data that matched nothing. Saying what values the data does hold is the host's: jaala names the call and what it was called with.
func (*EmptyReport) String ¶ added in v0.1.68
func (er *EmptyReport) String() string
String writes the trail as text, one literal a line, each rule's under the literal that called it: what a model retrying the program, or a person, reads.
type ErrorKind ¶ added in v0.1.65
type ErrorKind string
An ErrorKind sorts CheckErrors by what a program got wrong.
const ( KindUnknown ErrorKind = "unknown" // a relation, module or aggregate the vocabulary doesn't hold KindArity ErrorKind = "arity" // a call with the wrong number of arguments KindUnbound ErrorKind = "unbound" // a variable that has to be bound where nothing binds it KindType ErrorKind = "type" // a value or unit an argument or comparison can't take KindStratify ErrorKind = "stratify" // recursion through negation, an aggregate or arithmetic KindDefinition ErrorKind = "definition" // a rule head that can't define its relation KindAggregate ErrorKind = "aggregate" // an aggregate written where or how it can't reduce KindAnswer ErrorKind = "answer" // order by, having, limit, offset or after KindFact ErrorKind = "fact" // an `as ?r` on an atom that matches no stored fact (#279) )
The kinds of CheckError.
type Evaluator ¶
type Evaluator interface {
Eval(ctx context.Context, q Query, b *Base, opts ...Option) ([]Row, error)
// EvalTable answers as Eval does, as one Table rather than a map per row (#195).
EvalTable(ctx context.Context, q Query, b *Base, opts ...Option) (*Table, error)
}
Evaluator answers a Query over a Base, each answer Row carrying the provenance of the facts that derived it. The IR is declarative, so strategies swap behind this interface: Naive is the reference, SemiNaive the one a host should run.
ctx bounds the evaluation: when it is cancelled or its deadline passes, Eval stops within a short stretch of work and returns an error wrapping ctx.Err(), and the context reaches the host's generators and ContextSource reads, so a walk or a read in progress can stop too. Options bind goal variables (Bind) and limit work (Budget).
type Expr ¶ added in v0.1.37
An Expr is Op over Args: "+", "-", "*", "/" over two, "neg" over one, or "call" of Func.
type IndexReport ¶ added in v0.1.24
type IndexReport struct {
On []string `json:"on"` // the arguments it is keyed on, by label
Built bool `json:"built"` // built by this Eval, rather than kept by the Base
Probes int64 `json:"probes"` // lookups made in it
}
An IndexReport is one index of a base relation the Eval probed.
type Literal ¶
type Literal struct {
Pos *Atom
Neg *Atom
Compare *Compare
Agg *BodyAggregate
// Opt is `optional { body }` (#282): the clause's row holds whether body matches or not, and a
// variable only body binds is absent when it doesn't. lowerOptionals rewrites it into rules before
// anything else reads the program, so nothing after it sees one.
Opt *Body
// contains filtered or unexported fields
}
A Literal is exactly one of: a positive atom, a negated atom (stratified negation), a comparison built-in, or an aggregate over a body of its own. Exactly one field is non-nil. Examples: `param(?m,"VIN",?v)` is Literal{Pos: &Atom{...}}; `not param(?m,"VIN",?v)` is Literal{Neg: ...}; `?v < 30` is Literal{Compare: ...}; `?c = count(?n) : { pin(?r, ?n, _) }` is Literal{Agg: ...}.
type LiteralReport ¶ added in v0.1.24
type LiteralReport struct {
Literal string `json:"literal"`
// Access says how it was read, each way it was: "index (from)" for a base relation probed on its
// from argument, "scan", "derived index (to)", "derived scan", "generator", "filter",
// "comparison", "lookup (from)" for a call the Source looked up (ns.LookupSource), "stream" for a
// goal's relation solved as its Source streamed it (#264), or "not" over one of those.
Access []string `json:"access,omitempty"`
// Reached is how often solving got to it, Passed how many bindings it passed on (for a `not`,
// the ones it let through), and Work the candidates it examined.
Reached int64 `json:"reached"`
Passed int64 `json:"passed"`
Work int64 `json:"work"`
// Spent is what the Sources and generators it called charged for their own work (ns.Allowance,
// #361), apart from Work.
Spent int64 `json:"spent,omitempty"`
// Missed is the first call of it that passed nothing on, with the variables bound by then written
// as their values (for a `not`, the first binding it refused), or "" when every call passed one.
Missed string `json:"missed,omitempty"`
// Stopped is set on the literal being solved when the Eval's Budget ran out.
Stopped bool `json:"stopped,omitempty"`
}
A LiteralReport is one literal of a body, in the order it ran: positive literals first, as solved, then the negated ones, which filter each solution.
type Naive ¶
type Naive struct{}
Naive is the reference interpreter: a backtracking join in written order, with rules derived by a naive fixpoint that re-runs every rule over everything derived so far until a round adds nothing. It serves the full fragment (conjunction, comparison, stratified negation, aggregation, recursive rules, host predicates) through one positive primitive, extendAtom, which negation reuses (atomHolds), so a single dispatch covers every kind of relation.
It is kept deliberately simple and is not the fast path. Its job is to be obviously right, so the optimized evaluators can be tested against it: every optimization must answer exactly as Naive does. A host should use SemiNaive.
func (Naive) Eval ¶
Eval answers the query. It links the query first (see Link), derives its rules, then solves the positive body (atoms + comparisons) by backtracking, filters each binding through the negated literals (stratified negation), then projects: a plain select-project, or a group-and-reduce when the projection contains an aggregate. Results are deduplicated and sorted, so a query is a deterministic, regenerable view; each row carries the provenance of the facts that produced it.
type Option ¶ added in v0.1.9
type Option func(*evalOptions)
An Option adjusts one Eval: Bind gives goal variables values from the host, Budget limits its work.
func Across ¶ added in v0.1.61
func Across(vs ns.VersionSet) Option
Across evaluates the query once over every version in vs of the Base's ns.TimedSource (#180), each answer row carrying the versions it holds in (Row.Versions): the rows whose Versions hold v are exactly the rows At(v) answers. A join holds in the versions all its facts hold in, a tuple derived two ways holds in either's, and a `not` holds in the versions the negated relation doesn't, so a recursive relation whose facts barely change between versions is derived about once rather than once per version (the provenance semiring, with version sets as the annotation).
A generator, filter or comparison holds in every version, so a host generator reading versioned data of its own belongs under At. Where two versions of a row are derived differently (a witness, a spelling of a number), the row is answered once per way, each with the versions it holds in, so each version's row is the one At gives it; Row.CitesAt and Witness.At give a version's citations. An aggregate is reduced per stretch of versions over which its inputs don't change (#181), each with its own row. Every version in vs must be one the Source serves. Across reads the Source's facts through TimedTuples, or through LookupTimed for a bound call when the Source is an ns.TimedLookupSource (#317), without pushes, walks or streaming, and keeps nothing for a later query.
func After ¶ added in v0.1.33
After answers only the rows strictly after row in the query's order by, as the query's after clause does: row is the last one of the previous page, as the host got it, so the next page continues from it by value rather than by count, and stays put when facts change between pages (#194). The query needs an order by naming every variable column, so no row ties with row and is skipped. It replaces an after clause the query writes.
func At ¶ added in v0.1.61
At answers the query at version v of the Base's ns.TimedSource (#179): over exactly the facts that hold in v, each with the citations recorded for v, as a Base over a Source serving only those facts would answer, witnesses included. Every evaluator, rewrite and option works as without it. The version's base relations, indexes, lookups and derived relations are cached apart from every other version's (see LimitVersions), and the context a host's generators and Source are handed carries v (ns.VersionOf). A Base whose Source isn't a TimedSource, or a version it doesn't serve, is refused.
func Bind ¶ added in v0.1.9
Bind gives goal variables values from the host, so a parameterized query needs no program text built per request: Eval(ctx, q, b, Bind(map[Var][]ns.Value{"target": {ns.S(id)}})). Rules are not affected: their variables are their own. Binding a variable the goal does not use is an error.
A variable bound to one value is exactly a constant written in the goal, so inlining, demand (magic sets) and planning all start from it, and it stays an answer column, holding its value in every row. Like a constant, a bound value is read as the type of the argument it stands in (see ns.ArgType.Type), so a host holding only text, such as an input box's, can bind ns.S("3") to a number argument; text that argument cannot read is refused. The answer column still holds the value as bound.
A variable bound to several values ranges over them, as if the goal were joined with a relation holding exactly those values (#132): the answer is the union over them, an aggregate reduces across all of them, and demand starts from every one, so a derived relation is evaluated only for the values asked. Each value is checked as a single bound value is, and an error names the one refused. Bound to no values, the variable matches nothing, so the answer is empty, or the one row an aggregate gives over nothing. The values carry no citations.
ValidateBound checks a goal ahead of time knowing which variables the host will bind.
func Budget ¶ added in v0.1.9
Budget limits one Eval to maxWork units of the work Base.Work counts (candidate comparisons, and each solution a generator emits), plus each tuple an ns.StreamSource yields as a relation is read whole (#233). Exceeding it stops the Eval with a *BudgetExceeded. The budget is the Eval's own: concurrent Evals on one Base do not spend each other's. It bounds work, and memory only so far: the goal holds one row per distinct answer or one accumulator per group, not its bindings (#120), and a streamed read stops at the budget, but a Source read as one slice arrives whole before it is counted, and the derived relations its rules produce are held whole.
func CanonicalCites ¶ added in v0.1.23
func CanonicalCites() Option
CanonicalCites makes every answer's citations, and its witness when Witnesses is set too, the same whichever evaluator answers and however its rules are written or planned (#22). Without it a derived tuple keeps its first derivation, and the evaluators find derivations in different orders, so a row reachable two ways can cite either path.
Each derived tuple, and each answer row, keeps its shortest derivation: the one with the fewest rule steps above the facts. Of those, it keeps the one whose rule comes first by its written text, then whose body facts come first by relation and values, in written order, and then a source's facts by their citations. The shortest derivation is the same however it is found, and the rest reads only what was derived, so every evaluator keeps the same one. It is also the easiest to check by hand.
It costs work: a tuple derived again is compared with the one kept rather than dropped, and one that a shorter derivation replaces is derived from again, so its own consumers can shorten too. Like Witnesses, it keeps SemiNaive from inlining and factoring relations, which would change the steps a derivation counts, or from storing a body prefix in a supplementary relation (see magic), which would merge derivations it has to tell apart. Witnesses are recorded to compare derivations, but Row.Witness is set only when Witnesses asks for it.
func Explain ¶ added in v0.1.24
Explain asks an Eval to fill r with what it did (#147): the plan each body ran in, where its work went, which derived relations were evaluated in full, under demand or read from the Base, and how each base relation was read. A query that is slow then shows which rule, literal or relation spent the work, rather than one total to bisect by hand.
r is reset when the Eval starts and filled when it ends, whether or not it succeeds, so a query stopped by its Budget still reports where its work went. A Report is plain data, with JSON tags, and String renders it as text. Explaining costs time and memory in proportion to the rules and literals a query runs, not its tuples, and an Eval that doesn't ask for it pays one nil check per unit of work.
func Total ¶ added in v0.1.33
Total sets *n to the number of rows the answer has before after, offset and limit, so a host showing a page can say how many it left out (#194). A limit without an order by solves the whole goal when Total is asked for, since counting needs every row.
func Witnesses ¶ added in v0.1.10
func Witnesses() Option
Witnesses asks an Eval to record how each answer was derived, in Row.Witness. Recording keeps the program's shape: SemiNaive does not inline relations into their callers for a witnessed Eval, so every derived relation the query reaches is its own node. Planning and demand still apply; their rewrites are invisible in the witness. An aggregate row has no witness, since a group merges many derivations.
type Order ¶ added in v0.1.13
An Order is one `order by` item: an answer column, ascending unless Desc. Descending reverses the whole order, so absent values come last.
type ParseError ¶ added in v0.1.61
type ParseError struct {
Offset int // bytes from the start of the text
Line int // 1 for the first line
Column int // 1 for a line's first character, counting characters rather than bytes
// contains filtered or unexported fields
}
ParseError is the error Parse and ParseRules return. Its message is the one the parser has always written, so a host matching on its text sees no change, and it says where in the text the piece it is about starts, so an editor or an agent can point at it. A message about a part of a having or an order by (`query: having "count(?b) > ?x": ...`) wraps the part's own error, which Unwrap returns, and takes its position.
func (*ParseError) Error ¶ added in v0.1.61
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶ added in v0.1.61
func (e *ParseError) Unwrap() error
Unwrap returns the error a contextual message wraps, or nil.
type Position ¶ added in v0.1.65
type Position struct {
Offset int // bytes from the start of the text
Line int // 1 for the first line
Column int // 1 for a line's first character, counting characters rather than bytes
}
A Position is a place in a program's text, as ParseError gives one.
func Locate ¶ added in v0.1.65
Locate says where in text, the program err came from, the error points: a ParseError's own position, or for a CheckError the first call to its Relation with its Args (in its Rule's clauses when it names one), else the first ?Var there. It reports false when the text holds no such place, as for an error in a module's rules rather than the program's.
type Query ¶
type Query struct {
Rules []Rule
Goal Body
// Select is the answer columns: each item is a variable (a group key) or an aggregate over the
// group formed by the variable columns (count/min/max/sum/list). Empty selects Goal's variables
// in first-seen order. When any item is an aggregate, the result is grouped-and-reduced.
Select []Term
// Having filters the GROUPS a Select's aggregates form, after the reduce. Each item is a Compare
// whose left term is an aggregate, so `=> ?p, count(?n) having count(?n) < 2` keeps the groups of
// size one. A Goal comparison cannot express this: it is applied per binding, before there is a
// group to count.
//
// An aggregate may appear here without being selected, which is how you ask for the subjects
// rather than the tally. That still groups: a Having aggregate makes the query grouped-and-reduced
// exactly as a Select one does, and its column is computed, filtered on, and then not printed
// (Columns is keyed off Select alone).
Having []Compare
// OrderBy sorts the answer by answer columns, after the reduce and the having filter. Each item
// names a Select column (a variable or an aggregate, as written there). Rows that tie on every
// item keep the default order, so the answer stays deterministic. Empty keeps the default order
// alone: absent values first, then numbers by value, then other strings by their text.
OrderBy []Order
// After keeps only the rows strictly after these values in the OrderBy columns, one value per
// column, so a page continues from the last row of the one before it by value (#194). It needs
// an OrderBy naming every variable column. The After option sets it from a row.
After []ns.Value
// Limit keeps at most this many rows of the ordered answer, after skipping Offset of them. Zero
// means no limit. With an OrderBy the goal holds only Limit plus Offset rows while it is solved;
// without one it answers the first Limit distinct rows it finds and stops there, so which rows
// depends on the evaluator. Offset needs an OrderBy, since a page has to continue from the one
// before it in a stable order.
Limit int
Offset int
}
A Query is a datalog program answered over a fact base: Rules define derived (IDB) relations and Goal is the conjunction to solve. Goal's free variables — narrowed by Select — are the answer columns. EDB relations come from the Base's Source; IDB relations come from Rules; predicates are computed (see ns.Vocabulary.AddPredicate).
The whole IR is what Parse produces. For the query text
component.mpn(?r,?m), net.max_voltage(?n,?v), ?v < 30 => ?r, ?n
the Query is: no Rules; Goal.Literals = [ Atom component.mpn(?r,?m), Atom net.max_voltage(?n,?v), Compare(?v < 30) ]; Select = [?r, ?n].
func Build ¶
Build assembles a Query from its IDB rules, the goal literals to solve, and the projected answer terms (the => columns). Passing no rules is the common single-goal case.
func Link ¶ added in v0.1.2
func Link(q Query, reg *ns.Vocabulary) (Query, error)
Link returns q with every derived module it reaches expanded into its rules, so the result is an ordinary query that evaluates without the vocabulary's modules. Every evaluator, Validate and Reads link first; a host calls Link itself to inspect or cache the expanded program.
Loading is transitive and by need, one relation at a time: a query naming net.has_test_point pulls in the rules defining net.has_test_point, then the rules of whatever those read, and so on. A member defined in the same module but never reached is not loaded, so a query pays for the relations it names, not for their neighbours: a cheap member and an expensive one can share a module. Each relation is loaded once, however many paths reach it. Module rules come after the query's own, heads renamed to full paths and private members to names no query can spell. The query's own rules are all kept, reached or not, so Validate still checks every rule its author wrote. Because the result is ordinary rules, stratification, negation safety and range restriction apply to module rules exactly as to a query's own.
A query's own rules stay local and bare. Link refuses a query rule whose head is a qualified path (quietly adding a rule to a shared relation is the accident a namespace exists to prevent), names a module, or names a derived relation a module registered. It returns Check's error when the vocabulary's modules do not check.
func MustParse ¶
MustParse parses a query string and panics on error — for hand-authored rules constructed at package init, where a malformed built-in query is a programming error surfaced at startup (the same contract RuleFromQuery had when it parsed internally).
func Parse ¶
Parse reads a text query into a Query. Grammar (EBNF; whitespace is insignificant):
query = { rule end } goal [ "." ] ; (* zero or more rules, then one goal *)
end = ";" | "." ; (* a "." only before whitespace or the end, #276 *)
rule = head ":-" literals ; (* head :- body; defines a derived relation *)
head = relation "(" [ harg { "," harg } ] ")" ;
harg = term [ ":" decl ] | aggregate | expr ; (* a declared type: ?n: net, see parseArgType *)
goal = literals [ "=>" projection [ "having" havings ] [ "order" "by" orders ]
[ "limit" count ] [ "offset" count ] ]
| ( "?-" | "=>" ) literals ; (* asks literals with no projection, #276 *)
literals = literal { "," literal } ;
literal = atom [ "as" variable ] | ( "not" | "!" ) atom | comparison | bodyagg | optional ; (* "not atom" = stratified negation; "as ?r" binds the fact, #279 *)
optional = "optional" "{" literals "}" ; (* holds whether literals match; what only they bind is absent when not, #282 *)
bodyagg = variable "=" aggregate ":" "{" literals "}" ; (* per shared variable's value, #71 *)
atom = relation "(" [ term { "," term } ] ")" ;
comparison = operand op operand ;
operand = term | expr ;
expr = sum ; (* arithmetic over num.* and functions, #5 *)
sum = product { ( "+" | "-" ) product } ;
product = unary { ( "*" | "/" ) unary } ;
unary = "-" unary | "(" expr ")" | call | term ;
call = relation "(" [ expr { "," expr } ] ")" ; (* a function relation; its last argument is the result *)
op = "<" | "<=" | "=" | "!=" | ">" | ">=" ;
projection = column { "," column } ;
column = variable | aggregate | expr ; (* an expr column is labelled as written without ?s, #206 *)
aggregate = aggfunc "(" [ "distinct" ] variable ")" ; (* grouped by the variable columns *)
aggfunc = "count" | "min" | "max" | "sum" | "avg" | "list" ;
havings = having { "," having } ;
having = aggregate op term ; (* filters GROUPS, after the reduce *)
orders = order { "," order } ;
order = column [ "asc" | "desc" ] ; (* a selected column; ties keep the default order *)
count = digit { digit } ;
term = variable | string | number ;
variable = "?" ident | "_" ;
ident = ( letter | digit | "_" ) { letter | digit | "_" } ; (* ASCII *)
string = '"' { char | "\\" char } '"' ; (* kept as written: \" is a backslash and a quote *)
number = [ "+" | "-" ] digit { digit } [ "." digit { digit } ] [ ( "e" | "E" ) [ "+" | "-" ] digit { digit } ] ;
relation = ident { "." | "-" | ident } ; (* a path: net.max_voltage, component-on-net *)
A "#" outside a string starts a comment that runs to the end of the line. The text is read as tokens first (lex.go, #167), and an error is a *ParseError saying where the piece it is about starts.
Clauses are separated by ";", or ended by "." as Datalog and Prolog end them; a clause with ":-" is a rule, and the one clause without one is the goal. A goal may also be written as Prolog and agents write it, `?- r(?a)` or `=> r(?a)`, meaning `r(?a)`, and a "." between a goal and its "=>" is read as if absent. A rule head defines a derived (IDB) relation the goal (or another rule) can then read, and a rule whose body reads its own head is recursion (evaluated to a stratified fixpoint). Some relation names are predicates the host registered rather than fact-base relations: reaches(from, net) (transitive connectivity) and the string filters str.contains/str.prefix/str.suffix(?value, "pattern"). A dotted name is a path in the vocabulary's tree (see ns.Vocabulary). They parse as ordinary atoms; the evaluator dispatches them. A rule head may not redefine a built-in or an EDB relation.
A comparison in the LITERALS and one after `having` read alike and are applied at different times, which is the distinction to hold on to. A literal comparison filters BINDINGS, before any grouping; a having filters GROUPS, after the reduce. So `?c < 2` in the body narrows the facts that reach the group, and `having count(?n) < 2` narrows the groups the reduce produced. Only the second can ask about a count, because before grouping there is nothing to count.
The answer is ordered and cut last: `order by` sorts the rows the having kept, and `limit` and `offset` take a page of them. Without `order by` the answer is in the default order (absent values, then numbers by value, then strings by text), which is also what breaks a tie under `order by`.
This covers the whole bounded fragment the evaluator serves: user-defined (recursive, stratified) rules, conjunction, comparison, the built-in reaches and string predicates, stratified negation, aggregation, and post-aggregation filtering. It parses to the query.Query IR; for
component.mpn(?r,"REG-24"), net.max_voltage(?n,?v), ?v < 30 => ?r, ?n
the result is Query{Goal.Literals: [Atom component.mpn(?r,"REG-24"), Atom net.max_voltage(?n,?v), Compare(?v < 30)], Select: [?r, ?n]}. And `component-on-net(?r,?n) => ?n, count(?r)` parses to a Goal with one Atom and Select [Term{Var:"n"}, Term{Agg: &Aggregate{Func:"count", Var:"r"}}].
type RelationReport ¶ added in v0.1.24
type RelationReport struct {
Relation string `json:"relation"`
// How is "full" (every tuple derived), "demand" (only those the query's bound arguments asked for;
// Adornments says which arguments were bound, b, or free, f), "factored" (a right-linear
// recursion walked from the goal's constants), "reused" (read from what the Base kept from an
// earlier query, #140), or "inlined" (its body copied into its callers, so it was never derived).
How string `json:"how"`
Adornments []string `json:"adornments,omitempty"`
Demanded int `json:"demanded,omitempty"` // values demanded, summed over adornments
Tuples int `json:"tuples"`
Rounds int `json:"rounds,omitempty"`
Work int64 `json:"work"` // its bodies' work, and the demand rules feeding it
Elapsed time.Duration `json:"elapsed_ns"`
}
A RelationReport is one derived relation the query reached.
type Report ¶ added in v0.1.24
type Report struct {
Work int64 `json:"work"`
Budget int64 `json:"budget,omitempty"`
Elapsed time.Duration `json:"elapsed_ns"`
Rows int `json:"rows"`
// Held is the most answer rows (or groups, for an aggregate) the goal held at once, before
// offset and limit, which is what the answer's memory grows with rather than the bindings the goal
// found (#120). A limit with an order by holds at most limit plus offset.
Held int `json:"held"`
Error string `json:"error,omitempty"`
// Lookups are the calls the Eval made to the Source's Lookup (ns.LookupSource), Batches those to
// its LookupBatch (ns.BatchLookupSource, #153), so the round trips are the two together, and
// Fetched the tuples the Source returned to this Eval: those calls', and those of each relation it
// read whole that the Base didn't already hold.
Lookups int64 `json:"lookups,omitempty"`
Batches int64 `json:"batches,omitempty"`
Fetched int64 `json:"fetched,omitempty"`
// Spent is what the Eval's Sources and generators charged for their own work (ns.Allowance,
// #361): it counts against the Budget beside Work, and isn't part of Work, which stays the
// engine's own.
Spent int64 `json:"spent,omitempty"`
// Pushes are the calls to the Source's Push (ns.PushSource, #237), each a conjunction of several
// relations and another round trip; Fetched counts the tuples of the rows they returned.
Pushes int64 `json:"pushes,omitempty"`
// Walks are the calls to the Source's Walk (ns.WalkSource, #239), each answering every round of a
// recursive relation's probes of one relation; Fetched counts the facts they returned.
Walks int64 `json:"walks,omitempty"`
// Cold is what the Eval would have cost on a Base that kept nothing from earlier queries. Unset
// when the Eval failed.
Cold *ColdReport `json:"cold,omitempty"`
// Goal is the goal's body as it ran, after any rewrite reordered it.
Goal *BodyReport `json:"goal,omitempty"`
// Rules are the rule bodies that ran, in the order they first did. A rewrite can run one rule as
// several bodies: under demand, each with a guard; in a recursive relation, each round's variant
// reading what the last round derived.
Rules []*BodyReport `json:"rules,omitempty"`
// Relations are the derived relations the query reached, by the names the program gives them.
Relations []*RelationReport `json:"relations,omitempty"`
// Sources are the base relations the Eval read, by name.
Sources []*SourceReport `json:"sources,omitempty"`
// Empty says where an Eval that checked and answered no rows lost its last binding (#343). It is
// nil when the Eval answered rows or failed, and when every literal of the goal passed something on,
// so a limit, offset or having dropped the rows.
Empty *EmptyReport `json:"empty,omitempty"`
// Warnings are Lint's, over the program as written (#477): likely mistakes that change no answer,
// filled whether or not the Eval succeeded.
Warnings []Warning `json:"warnings,omitempty"`
}
A Report is what Explain fills: the totals, then the goal and each rule body as they ran, the derived relations, and the base relations read. Work is Base.Work's unit (see Budget); times are wall clock.
type Row ¶
type Row struct {
Bind map[Var]ns.Value
Cites []string
// Witness says how the row holds, one node per goal literal in written order, when the Eval asked
// for witnesses (see Witnesses). It is nil otherwise, and on an aggregate row.
Witness []*Witness
// Why says why an aggregate column is absent, keyed like Bind: "no rows" (a group over nothing),
// "no numbers" (min, max or avg over text) or "mixed units: A, V" (min, max, sum or avg over numbers in
// different units, #80). A host shows it beside the absent value. It is nil when no column is
// absent, and an aggregate a rule stores keeps only its value, so it's set on a goal's own
// aggregates.
Why map[Var]string
// Versions are the versions the row holds in, when an Across Eval answered it (#180), else nil. Its
// Cites are then its citations in the latest of them, and CitesAt gives another's.
Versions ns.VersionSet
// contains filtered or unexported fields
}
Row is one answer: the projected variables bound to values, plus the provenance of the base facts that produced it — so an answer stays verifiable.
type Rule ¶
type Rule struct {
Head Atom
Body Body
Hops int // 0 = run to fixpoint; >0 = bound recursion depth (reserved; the fixpoint is finite regardless)
// HeadTypes are the types the rule declares for its head's arguments, by position, written
// `has_test_point(?n: net)`. Empty, or a zero entry, declares nothing for that argument, which is
// then inferred (see ns.Vocabulary.Lookup). KindFrom and Owner name other head VARIABLES, without "?".
HeadTypes []ns.ArgType
// contains filtered or unexported fields
}
A Rule derives its Head for every binding satisfying Body. A rule is recursive when its Head relation is reachable from a Body atom in the rule dependency graph; recursion terminates by finiteness of the fact base (no function symbols). Rules materialize by stratified fixpoint (see Naive and SemiNaive): a program that reads a relation under negation from inside that relation's own recursive cycle is rejected, which is what keeps `not` well-defined.
Example (transitive closure over a derived edge): connected(?a,?c) :- connected(?a,?b), link(?b,?c) is Rule{Head: Atom connected(?a,?c), Body: [Atom connected(?a,?b), Atom link(?b,?c)]}.
A head may aggregate (#4): degree(?n, count(distinct ?m)) :- edge(?n, ?m) derives one tuple per group of the head's plain variables, reducing its body's bindings as an answer's aggregate does (see Aggregate), so a rule can count. It is evaluated once every relation its body reads is complete, which stratification arranges as it does for negation, so a relation can't aggregate over its own recursion. Such a rule must be its relation's only rule. As in an answer, a group exists only where the body has a binding: a part with no pins gets no count of zero, and a head with no plain variable gets one tuple even over nothing.
func Def ¶
Def builds an IDB rule Head :- body. Disjunction is several Defs sharing a Head relation.
func ParseRules ¶ added in v0.1.2
ParseRules reads text that holds rules only, such as a derived module's body (see Language). It accepts the same clause syntax as Parse, and a fact too: one atom of constants, pattern("rail", "^VCC"), is a rule with no body (#479). Any other goal clause is refused, since rules with nothing to ask are a definition rather than a query. Its errors are *ParseError, as Parse's are.
type SemiNaive ¶ added in v0.1.5
type SemiNaive struct {
// WrittenOrder runs bodies as written, with none of the rewrites (inlining, demand, planning).
// Its answers then match Naive's citations too, which is what the tests compare it on.
WrittenOrder bool
}
SemiNaive is the evaluator a host should run. It answers exactly as Naive does, deriving rules by a semi-naive fixpoint instead of a naive one.
A naive round re-runs every rule over everything derived so far, so on a chain of n nodes a transitive closure takes about n rounds of about n² derivations each, most of them repeats: the work grows with n³. A derivation that uses only facts older than the last round was already made in an earlier round, so a semi-naive round only runs the derivations that use at least one fact new in the last round (the delta). Each fact is joined against once rather than once per round, and the same closure grows with about n².
It reads a derived relation the Base already holds, from an earlier query that evaluated it in full, instead of deriving it (see reuseDerived). It also inlines single-rule, non-recursive derived relations into their callers (see unfold), so a bound argument reaches the literals that can use it; rewrites the derived relations still called with bound arguments so only what the query demands is derived (see magic, and factor for right-linear recursion); and then plans each rule body and the goal before evaluating (see plan): a literal runs once as much as possible is bound, a comparison or filter as soon as its variables are, and a generator once one of its Modes is satisfied. That makes cost independent of how a body is written, at the price of citations: a different join order can make a different derivation of a tuple the first, so a planned answer's rows match Naive's while a row's citations may come from another valid derivation.
func (SemiNaive) Materialize ¶ added in v0.1.58
func (s SemiNaive) Materialize(ctx context.Context, q Query, b *Base, rels []string, opts ...Option) error
Materialize evaluates each of rels in full over b, with q's rules and the vocabulary's modules, and keeps it, and every derived relation it reads, as an Eval that evaluated them in full would: in the Base's memory and, for a Versioned Source, in the DerivedStore KeepDerivedIn gave it (#220). A host calls it to fill the store ahead of the queries, or to put a relation there that its own tools read as facts, such as derived edges a walk follows. q's goal is ignored. A relation already held is read rather than derived again, and written to the store when the store doesn't hold it yet.
Every relation in rels must be derived, by one of q's rules or a module's member. It returns the first error an evaluation or the store's KeepDerived gave. Under Witnesses or CanonicalCites nothing is kept, as in Eval.
type SourceReport ¶ added in v0.1.24
type SourceReport struct {
Relation string `json:"relation"`
// Tuples is the relation's size when the Eval read it whole, and 0 when it only looked it up.
Tuples int `json:"tuples"`
// Cached is true when the Base already held the relation's tuples from an earlier query, false
// when this Eval read them from the Source.
Cached bool `json:"cached"`
Scans int64 `json:"scans,omitempty"` // reads of every tuple
Indexes []*IndexReport `json:"indexes,omitempty"`
// Lookups are the calls made to the Source's Lookup for it, Batches those to its LookupBatch,
// Fetched the tuples they returned, Hits the calls this Eval answered from what its own earlier
// lookup or batch of the same values returned, and Kept those it answered from what an earlier
// Eval's did, kept by the Base (#212).
Lookups int64 `json:"lookups,omitempty"`
Batches int64 `json:"batches,omitempty"`
Fetched int64 `json:"fetched,omitempty"`
Hits int64 `json:"hits,omitempty"`
Kept int64 `json:"kept,omitempty"`
// Pushes are the pushed conjunctions it was part of (#237); a conjunction answered from what was
// kept counts in Hits or Kept as a lookup does, and its tuples of their rows in Fetched.
Pushes int64 `json:"pushes,omitempty"`
// Walks are the walks that fetched its facts (#239).
Walks int64 `json:"walks,omitempty"`
}
A SourceReport is one base relation the Eval read.
type Table ¶ added in v0.1.33
type Table struct {
// Columns are the answer's columns as written: a variable, or "func(var)" for an aggregate, the
// keys Row.Bind uses.
Columns []Var
Rows [][]ns.Value
// Cites are each row's provenance, as Row.Cites.
Cites [][]string
// Witness is each row's witness when the Eval asked for witnesses (see Witnesses), else nil.
Witness [][]*Witness
// Why is, for each row with an absent aggregate column, the reason per column (see Row.Why), and
// nil for a row without one. It is nil when no row has one.
Why [][]string
// Versions are each row's versions, as Row.Versions, when an Across Eval answered (#180), else nil.
Versions []ns.VersionSet
// contains filtered or unexported fields
}
A Table is an answer as columns and rows of values, which EvalTable returns (#195). It holds what Eval's []Row does without a map per row, so a large answer costs its values. Rows, Cites, Witness and Why are indexed by row; a row's values, and its reasons, by column.
type Term ¶
type Term struct {
Var Var
Const *ns.Value
Agg *Aggregate
// Expr is arithmetic, or a call to a function relation, legal as a comparison's operand (#5).
Expr *Expr
}
A Term is a variable, a constant, or an aggregate over the group formed by the projection's plain variables. Exactly one of Var/Const/Agg is set (Var == "" means not a variable). An Agg is legal in a Select column, on the left of a Having, and in a rule head, which groups by the head's plain variables (see Rule); in a body literal there is no group for it to reduce.
type Var ¶
type Var string
Var is a logic variable name (the leading "?" is stripped at parse time).
type Warning ¶ added in v0.1.100
type Warning struct {
// Rule is the rule the warning is about, as written, or "" for the goal.
Rule string `json:"rule,omitempty"`
// Vars are the two variables that may bind one value, without "?".
Vars [2]Var `json:"vars"`
// Atoms are the two atoms, as written, that differ only in those variables.
Atoms [2]string `json:"atoms"`
// Message says all of the above in one line.
Message string `json:"message"`
}
A Warning is something a program likely got wrong although it checks and runs (#477). It changes no answer, and a host shows it beside the query's other diagnostics.
func Lint ¶ added in v0.1.100
Lint reports the likely mistakes in q's rules and goal that no check refuses. Today that is one kind (#477): two positive atoms of one relation that are the same but for one position, holding two different variables there (parallelPair, NonInjectiveRules' test), with no comparison between the two anywhere in the body and no other literal reading both. Any operator counts: ?a < ?b and ?a <= ?b both say the author thought about the pair, where NonInjectiveRules, an agni-shaped check of rules alone, takes only !=. A body matches by homomorphism, so both variables may bind the same value: term(?y, ?b), term(?y, ?c) with no ?b != ?c matches each term of ?y as both. That is sometimes meant (pairs of siblings, each with itself), so it is a warning rather than an error, and Lint needs no vocabulary: it reads the program as written. Rules come first, in order, then the goal.
type Witness ¶ added in v0.1.10
type Witness struct {
// Relation is the relation proved, as the program names it.
Relation string
// Values are the proved tuple's values. On a Negated node, an argument the negation did not bind
// is the zero Value.
Values []ns.Value
// Rule is the rule that derived a derived node, as query text in its written form.
Rule string
// Negated marks a `not` literal that held: it proves an absence, so it has no citations and no
// children.
Negated bool
// Cites are a leaf's citations in the order its Source or generator gave them, so a generator that
// cites a path's steps in walk order keeps that order here (Row.Cites is the sorted set).
Cites []string
// Children are a derived node's body witnesses, one per literal that proves something (relations,
// generators, filters and negations; not comparisons), in the order the rule is WRITTEN, whatever
// order it was evaluated in.
Children []*Witness
// Versions are, for a witness an Across Eval answered (#180), the versions this node's fact holds
// in, or this derivation was found for; nil otherwise. At gives the witness of one version.
Versions ns.VersionSet
// Fact is, for a leaf whose literal bound its fact (`edge(?a, ?b) as ?r`, #279), the fact's id,
// which Values leave out so the leaf reads as the relation the program names; "" otherwise.
Fact string
// contains filtered or unexported fields
}
A Witness says how one fact of an answer holds: the relation and values it proves, and either the citations a Source or generator gave for it (a leaf) or the rule that derived it with the witnesses of that rule's body (a derived node). A Row's Witness lists one per goal literal, so an answer can be drawn as the tree of facts and rules behind it rather than a flat set of citations.
Witnesses are recorded only when an Eval asks for them (see Witnesses), since keeping one per derived tuple costs memory a query that only wants answers should not pay.
Source Files
¶
- across.go
- bindset.go
- bodyagg.go
- build.go
- canonical.go
- checkerror.go
- closure.go
- closurefetch.go
- coerce.go
- constants.go
- derived.go
- doc.go
- eval.go
- explain.go
- exprs.go
- factor.go
- facts.go
- goalpush.go
- index.go
- infer.go
- ingest.go
- inputs.go
- lex.go
- link.go
- lint.go
- lookup.go
- lookupcache.go
- magic.go
- materialize.go
- module.go
- optional.go
- options.go
- parse.go
- paths.go
- plan.go
- preds.go
- prefetch.go
- printer.go
- push.go
- query.go
- rules.go
- seminaive.go
- signature.go
- sink.go
- stream.go
- table.go
- unfold.go
- units.go
- validate.go
- versions.go
- walk.go
- witness.go