ns

package
v0.1.108 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package ns is the namespace contract between a host and a query engine: what names exist, at which paths, and what each one's arguments denote. It holds names, never evaluates them, and imports nothing outside the standard library, so a host's fact layer can register into it without depending on an engine.

A Vocabulary is one namespace tree. Every name a query can call lives at a path, its segments separated by "." (edge, str.contains, acme.power.rail_budget), and a leaf of the tree is one of:

  • a base relation, described by a Schema, whose tuples a Source serves;
  • a predicate, a Builtin the host computes: a filter or a generator. A generator declares the binding patterns it accepts (Modes), so an engine can schedule it and refuse a call that can never be made. jaala/stdlib registers the standard ones: the string tests under str (str.contains, str.prefix, ...) and absent at the root;
  • a derived relation, defined by a module written in a Language an engine provides (jaala/datalog provides "datalog"). The vocabulary asks the language what a module defines and enters each member's path; it never parses the text itself.

A segment is a module or a member, never both, and each path has one definer; the vocabulary refuses anything else when it is registered, whatever the kinds involved.

A module records its Origin, such as the file it was read from, and AddModulesFS registers a whole tree of module files under a Layout (ByDirectory or ByFileName). A failure one module is responsible for, whether AddModule refuses it or a language's Check does, is a *ModuleError carrying that module's index and origin, so a host can name the file to fix.

Every member has a signature: per argument a name and an ArgType saying what it denotes (an opaque entity kind such as "net", a kind taken per row from another argument, a kind located through an owner argument, or a scalar type with a unit), optionally closed over a vocabulary of values. Base relations and predicates declare theirs; a derived member's comes from its language's Check, which may infer it. Check runs once per state of the vocabulary and is shared by every query over it. Lookup and Members answer what is at a path, for a host offering drill-down discovery, and Unknown and Hint word an unknown name the way every engine over the vocabulary should.

A Vocabulary holds no data. An engine pairs it with a Source per query, so a host composes its vocabulary once, checks it at load, and binds each dataset as it reads it. A Federation is one Source over several, for facts kept in several stores: each relation is the union of its members', and a lookup goes only to the members whose Holds says they can match. A TimedSource serves several versions of its facts, each fact once with its VersionSet (an IntervalSet for linear history, a BitSet for history that branches), so one Base answers at any version; one implementing SourceAt serves each version as a Source of its own, so a question at a version reaches its store, one implementing TimedLookupSource answers a bound call across every version at once, and Federation.Timed joins timed members with members that don't change between versions.

The engine never writes to a Source. A host edits its facts through a Changes, a change set of the facts to add to and remove from each base relation, which it builds from an edit (or from the diff between two versions) and applies to its own store, checked first against the vocabulary. Until it commits, Overlay serves its store with a session's change set applied, passing on the store's interfaces, and a commit keeps the session as a new version (TimedMemSource.Commit).

Index

Constants

View Source
const (
	TypeString = "string"
	TypeNumber = "number"
	TypeList   = "list"
)

The types an ArgType may name: two scalars, and a list, whose values are a List's text (jaala#283) and which a constant is read as text for.

View Source
const StreamCheckTimeout = 10 * time.Second

StreamCheckTimeout is how long CheckStreamReentrant waits for its reads when ctx has no deadline.

Variables

This section is empty.

Functions

func CheckStreamReentrant added in v0.1.102

func CheckStreamReentrant(ctx context.Context, src Source, rel string) error

CheckStreamReentrant reports whether src keeps StreamSource's promise for rel: that nothing a later read needs is held while TuplesSeq yields (#539). The engine solves a goal's first literal as its tuples arrive and runs the rest of the body for each one, so a Lookup, a LookupBatch or another stream can come between two of a stream's tuples. A store that keeps its one database connection in an open cursor across its yields waits on itself there forever (declaire#370).

It streams rel and, at the first tuple, reads again before asking for the next: rel streamed anew up to its first tuple, then, when src looks rel up, Lookup and LookupBatch with the first tuple's first value bound. It then stops the outer stream. A src that isn't a StreamSource, or a rel with no tuples, passes, since nothing is held across a yield. An error from any read is returned wrapped.

The reads run on a goroutine under ctx, or StreamCheckTimeout when ctx has no deadline. A read still blocked then fails the check, and its goroutine stays blocked unless src gives up when its context ends, so a store's test calls this once, not in a loop.

func DidYouMean

func DidYouMean(v *Vocabulary, name string) string

DidYouMean returns the hint an engine appends to an unknown-name error: `; did you mean "X"?` when a registered path is a plausible typo of name, an explanation when v holds no base relation at all, and "" otherwise. It is v.Hint, for a host that validates names itself, such as one checking a rule that arrived over its own wire format, so its errors read the same as the engine's.

func DidYouMeanValue

func DidYouMeanValue(allowed []string, got string) string

DidYouMeanValue suggests the closest legal value for a rejected constant, as `, did you mean "X"?`, the value-level twin of Hint. A typo is the common case this whole check exists for, so naming the intended value is most of its worth; returns "" when nothing is close enough to be worth guessing.

func HoldsPrefix added in v0.1.39

func HoldsPrefix(prefix string, positions map[string][]int) func(rel string, bound map[int]Value) bool

HoldsPrefix is a Member.Holds for a member whose stored values at some positions all start with prefix, such as the ids of one repo ("github.com/hashicorp/consul-template/"). positions names, per relation, those positions; a call binding one of them to a value without the prefix can't match. A relation it doesn't name may hold anything.

func ListText added in v0.1.79

func ListText(vals []Value) string

ListText is vals as a list's value.

func SameVersions added in v0.1.61

func SameVersions(a, b VersionSet) bool

SameVersions reports whether a and b hold the same versions, whatever their kinds.

func VersionsIn added in v0.1.61

func VersionsIn(s VersionSet) iter.Seq[Version]

VersionsIn lists s's versions in ascending order. A set holding a range up to Open lists without end, so a caller ranging over one stops on its own.

func WithAllowance added in v0.1.76

func WithAllowance(ctx context.Context, a Allowance) context.Context

WithAllowance is ctx carrying a, as the engine hands a host its evaluation's context.

func WithVersion added in v0.1.61

func WithVersion(ctx context.Context, v Version) context.Context

WithVersion is ctx carrying v, the version an Eval reads its TimedSource at. The engine sets it on the context a host's generators and Source are handed under datalog.At, so a generator that reads versioned data of its own reads v's.

Types

type Allowance added in v0.1.76

type Allowance interface {
	// Spend charges n units of the host's own work. A non-nil error means the budget is spent: the
	// host stops and returns it from the call unchanged, and the evaluation stops with it. Spend is
	// called on the goroutine the engine called the host on, as a generator's emit is.
	Spend(n int64) error
	// Left is how many units the budget has left, and false when the evaluation has no budget.
	Left() (int64, bool)
}

An Allowance is what is left of an evaluation's budget for a Source's or generator's own work (#361): the steps of a walk, the rows a store scans to answer one lookup, a remote call. The engine charges a generator per row it emits and a Source per tuple it returns, which comes after the work that found them; a host whose one call does much more than it returns charges that work here as it goes, and stops once the budget is spent.

The engine puts one on the context it hands a Source's read, lookup, push or walk and a generator's Gen. What a host spends counts against the evaluation's budget beside the engine's own work, and is reported apart from it (datalog's Report.Spent), so the engine's work counts don't move when a host starts spending.

func AllowanceFrom added in v0.1.76

func AllowanceFrom(ctx context.Context) (Allowance, bool)

AllowanceFrom is the Allowance ctx carries, and false when it carries none, as when a host calls its own Source outside an evaluation.

type Arg

type Arg struct {
	Value Value
	Bound bool
}

An Arg is one argument as a generator sees it: its value when the binding fixes it.

type ArgSig

type ArgSig struct {
	Name string
	ArgType
	// Inferred is set on a derived relation's argument whose type no rule head declares, so a host
	// can show a reader which types the author stated and which the engine worked out. A head
	// aggregate whose function decides its type (count a number, list a string, sum, avg, min and max a
	// number over a typed number) counts as declared.
	Inferred bool
	// Input marks an argument the relation takes from its caller rather than producing (jaala#200),
	// as ?line in loc.at(?n, ?repo, ?uri, ?line) :- home(?n, ?repo, ?uri, ?s, ?e), ?s <= ?line,
	// ?line <= ?e. Every call has to bind it, with a value or a variable its own clause binds.
	Input bool
}

An ArgSig is one argument of a signature: its name and type, and whether the type was inferred from rules rather than declared.

func (ArgSig) String

func (a ArgSig) String() string

String renders the argument as a rule head would declare it: "n: net", or "n" when nothing is known about it.

type ArgType

type ArgType struct {
	// Kind is the entity kind every value of the argument names, or "" for none.
	Kind string
	// KindFrom is the label of the argument whose value, in each row, is this one's kind. When it is
	// set, Kind is "".
	KindFrom string
	// Owner is the label of the argument that locates this one, set beside Kind for an entity that is
	// only found through another, such as a pin through its component.
	Owner string
	// Type is a scalar type, TypeString or TypeNumber, or TypeList, for an argument that is not an
	// entity. A query
	// constant (or bound value) is read as this type: text that parses as a number becomes one in a
	// number argument, and text that does not is refused; a number in a string argument, or in one
	// naming an entity, matches by its text.
	Type string
	// Unit is the base unit of a numeric argument ("V", "A"), for a reader; see Value.BaseUnit.
	Unit string
	// Domain closes the argument over a vocabulary. On a base relation or a derived one, a query
	// constant outside it is refused before evaluation. On a KindFrom argument it is also the set of
	// kinds a constant may name, so entity(?n, "net") types ?n as a net.
	Domain []string
}

An ArgType says what one argument of a relation denotes. The zero value says nothing: an argument the relation has not described.

The engine never interprets a kind. "net" and "component" are opaque strings a host defines and reads back, typically to make an answer cell clickable. What the engine does is carry them: from a base relation or predicate that declares them, through the rules that read it, to the columns of an answer (see ColumnKinds), so a derived relation's arguments keep the kinds of the facts it was built from.

An argument is described in one of three ways, plus an optional vocabulary:

  • a fixed entity Kind: every value is a net;
  • a kind taken from another argument per row (KindFrom): entity(name, kind) says in each row what that row's name is;
  • a Kind located through another argument (Owner): a pin names nothing on its own and is found through the component in its owner argument;

or, for a value that is not an entity, a scalar Type with its Unit.

func (ArgType) IsZero

func (t ArgType) IsZero() bool

IsZero reports whether the type says nothing about its argument.

func (ArgType) String

func (t ArgType) String() string

String renders the type in the syntax a rule head declares it with, without the leading ": ".

type BatchLookupSource added in v0.1.43

type BatchLookupSource interface {
	LookupBatch(ctx context.Context, rel string, positions []int, values [][]Value) ([][]Tuple, error)
}

BatchLookupSource is optionally implemented by a LookupSource that answers many lookups of one pattern in one call, such as a database asked `WHERE (a, b) IN (...)` across a worker boundary or a network, where each call is a round trip (#153). positions are the bound argument positions, from 0 and sorted, and each of values is one lookup's values at those positions, in that order. LookupBatch returns one result per value, in values' order, each what Lookup would return for it and under Lookup's contract: it may hold facts that don't match, and must not leave out one that does. A result count other than len(values) fails the query.

The planned SemiNaive asks for a batch as it solves a body, for the values the literals before a looked-up call bind it to, or for a negated call those the whole positive body binds it to (#230), and keeps each result as Lookup's is, so the calls it answers never reach Lookup. Each value asked counts one unit of work, as a Lookup does. A Source that doesn't implement it is asked one value at a time through Lookup.

type BitSet added in v0.1.61

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

A BitSet is a VersionSet held as bits, for history that branches, where a fact's versions are scattered rather than one range. Stretches of 64 versions are words, kept only where some are in the set, and a stretch of whole words all in it is kept as a run rather than its words, so a fact holding in most versions stays small too. The zero BitSet is empty.

func Bits added in v0.1.61

func Bits(vs ...Version) BitSet

Bits is the set of the given versions.

func BitsOf added in v0.1.61

func BitsOf(s VersionSet) BitSet

BitsOf is s as a BitSet.

func (BitSet) Contains added in v0.1.61

func (s BitSet) Contains(v Version) bool

func (BitSet) Empty added in v0.1.61

func (s BitSet) Empty() bool

func (BitSet) Intersect added in v0.1.61

func (s BitSet) Intersect(o VersionSet) VersionSet

func (BitSet) Minus added in v0.1.61

func (s BitSet) Minus(o VersionSet) VersionSet

func (BitSet) Ranges added in v0.1.61

func (s BitSet) Ranges() iter.Seq[VersionRange]

func (BitSet) Union added in v0.1.61

func (s BitSet) Union(o VersionSet) VersionSet

type Builtin

type Builtin struct {
	// Arity is the argument count, or the minimum when MaxArity is set.
	Arity int
	// MaxArity, when non-zero, is the inclusive maximum argument count. It exists so an optional
	// trailing argument is admitted by the POSITIVE path and the NEGATION path through one test
	// (Accepts) rather than two length checks that could drift.
	MaxArity int
	// Holds is a filter's test over its (all-bound) argument values.
	Holds func(args []Value) (bool, error)
	// Modes lists the binding patterns a generator accepts: in each mode, the positions that must be
	// bound when it is called. A generator that walks out from either end of a path has two modes,
	// {true, false, ...} and {false, true, ...}. A generator that may enumerate with nothing bound
	// says so with an all-false mode, so a full scan is a declaration rather than an accident.
	//
	// It is required for a generator, with every mode as long as the generator's longest call (MaxArity
	// when set, else Arity); a position past a call's own arity is not required. A filter needs none:
	// it is always called with every argument bound.
	Modes [][]bool
	// Labels names the arguments, and Types says what each denotes, exactly as for a base relation's
	// Schema. Both are optional; they are what a host lists and what column kinds are read from.
	Labels []string
	Types  []ArgType
	// Doc is a one-line description a host shows when the predicate is listed.
	Doc string
	// Gen is a generator's enumeration. args holds each argument's value where the binding fixes
	// it. Gen calls emit once per solution with a value for EVERY argument, plus the citations that
	// justify it; the engine unifies each solution against the atom, so one that disagrees with a
	// bound argument is dropped there rather than in Gen. src is the Source the query runs over, for a generator
	// that reads the host's data through it.
	//
	// The engine copies what it needs out of vals and cites before emit returns and never keeps
	// either slice, so a generator may reuse one buffer for every solution it emits.
	//
	// ctx is the query's: when it is cancelled or its deadline passes, Gen should stop and return
	// ctx.Err(), so a long walk does not outlive the request that asked for it. emit also returns an
	// error when the query stops (cancelled, or over its work budget, which counts every emitted
	// solution), and Gen should return it as is.
	Gen func(ctx context.Context, src Source, args []Arg, emit func(vals []Value, cites []string) error) error
	// Aliased marks a generator's arguments where a bound value can name a row its enumeration lists
	// under another value, such as str.split's index, where -1 names the last part and enumerating
	// lists it by its index from 0. The engine passes such an argument to Gen bound only when the call
	// writes a constant there (a host's Bind of the goal's variable writes one). A value bound while
	// the query runs, by a join or by a rewrite passing a caller's constant down, is matched against
	// the rows Gen lists instead, so the answer doesn't depend on the order or the rewrite that reached
	// the call (#480). nil marks none. No mode may require an aliased argument.
	Aliased []bool
	// Volatile marks a generator or filter whose answers can change while its Source's facts don't,
	// such as one reading the clock, the network, or a host index updated in place. A Base keeps the
	// derived relations a query evaluated in full and reuses them in later queries, which assumes every
	// predicate is a function of its arguments and the Source; a relation that reads a Volatile one,
	// directly or through other derived relations, is never kept.
	Volatile bool
}

A Builtin is a predicate the engine computes rather than looks up. It is exactly one of two kinds.

A FILTER (Holds set) tests arguments that must all be bound, keeping a binding when Holds is true. Because negation runs the same test and asks whether it yielded, `not name(...)` keeps a binding exactly when Holds is false, so the two directions cannot disagree. An unbound argument is an error, the same shape as an unbound comparison operand.

A GENERATOR (Gen set) PRODUCES values, enumerating solutions from wherever the host keeps them. That is the property that makes clause order matter: a generator whose own input is unbound enumerates from every candidate, so appearing first in a rule body is a whole-dataset scan no later literal can undo. Modes says which bindings a generator accepts, so an engine can schedule it once one is satisfied and refuse a body that can never satisfy any. A generator must also only ever emit values drawn from finite host data, or evaluation stops being guaranteed to terminate.

func Filter

func Filter(arity int, holds func(args []Value) (bool, error)) Builtin

Filter builds a filter Builtin from a boolean over its all-bound argument values.

func (Builtin) Accepts

func (bi Builtin) Accepts(n int) bool

Accepts reports whether n is a valid argument count for this builtin.

func (Builtin) ArityLabel

func (bi Builtin) ArityLabel() string

ArityLabel renders the accepted arity for an error message ("2" or "2 or 3").

func (Builtin) IsGenerator

func (bi Builtin) IsGenerator() bool

IsGenerator reports whether the builtin produces values rather than filtering them.

func (Builtin) Satisfied added in v0.1.6

func (bi Builtin) Satisfied(bound []bool) bool

Satisfied reports whether a call whose bound positions are bound satisfies one of the builtin's modes. A filter is satisfied only when every argument is bound.

type Changes added in v0.1.79

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

Changes is a change set: per base relation, the facts to add and the facts to remove (#287). The engine never writes to a Source, so a host edits its graph by building a Changes (from a UI's edit, or from Base.Diff between two versions) and applying it to its own store, or by reading it through an overlay over the store until it commits.

A fact is its values, as Base.Diff compares them: a number by its value (-0 is 0, units aside), text by its text, and absent apart from both, so ns.N(1) and ns.S("1") are two facts. Build each value as its argument's declared type, as the engine reads it. Its ID and Cites travel with it.

Operations apply in the order they are made, so the last one on a fact wins: adding a fact and then removing it removes it, and removing it then adding it adds it, whatever a store holds. The zero Changes is empty and ready to use. A Changes is not safe for concurrent use.

func (*Changes) Add added in v0.1.79

func (c *Changes) Add(rel string, t Tuple) *Changes

Add records that rel holds t.

func (Changes) Added added in v0.1.79

func (c Changes) Added(rel string) []Tuple

Added lists the facts c adds to rel, in the order they were first named.

func (Changes) Apply added in v0.1.79

func (c Changes) Apply(rel string, base []Tuple) []Tuple

Apply is rel's facts once c is applied to base: base's facts, in its order, but those c names, then the facts c adds. A fact c names is replaced wherever base holds it, every copy, so an added fact base already held is held once, with the ID and citations c gives it.

func (Changes) Check added in v0.1.79

func (c Changes) Check(v *Vocabulary) error

Check refuses a change set v couldn't hold: a relation that isn't one of v's base relations (a derived relation's facts follow from its rules, so they never change directly), or a fact whose arity isn't its relation's.

func (Changes) Empty added in v0.1.79

func (c Changes) Empty() bool

Empty reports whether c names no fact.

func (Changes) MarshalJSON added in v0.1.79

func (c Changes) MarshalJSON() ([]byte, error)

MarshalJSON writes c as {"format": 1, "ops": [...]}, each op {"rel", "op" ("add" or "remove"), "vals", "id", "cites"}, relation by relation in the order c first named them and, within one, each fact's last operation in the order c first named the fact, which is what c holds: decoding replays the ops into a change set equal to c in every respect, Relations' order and an Overlay's Version included, so two processes holding the same session key their caches alike. Empty and nil citations both write as none.

A value is written so it reads back as itself: absent is null, text a string, and a number whose text is its canonical spelling, with no unit, a number. Any other number is {"num": n} with "unit" when it has one and "text" when its text isn't the canonical spelling (data's own, such as "1.50" or "3.3V", which an answer keeps, #148), n being "NaN", "+Inf" or "-Inf" when JSON can't hold it; text with a unit is {"text", "unit"}. That reads every value a list writes (ListText) the same way.

func (Changes) Relations added in v0.1.79

func (c Changes) Relations() []string

Relations lists the relations c names, in the order they were first named. A relation whose operations all cancel is still listed: its facts are named, as removals.

func (*Changes) Remove added in v0.1.79

func (c *Changes) Remove(rel string, t Tuple) *Changes

Remove records that rel doesn't hold t, under whatever ID or citations it was stored with.

func (Changes) Removed added in v0.1.79

func (c Changes) Removed(rel string) []Tuple

Removed lists the facts c removes from rel, in the order they were first named.

func (Changes) Then added in v0.1.79

func (c Changes) Then(next Changes) Changes

Then is c followed by next, as one change set: what next does to a fact replaces what c did. A sequence of edits, each made over the last, composes this way, so a stack of change sets can be undone by dropping the top and composing the rest. Neither c nor next is changed.

func (*Changes) UnmarshalJSON added in v0.1.79

func (c *Changes) UnmarshalJSON(data []byte) error

UnmarshalJSON reads a change set MarshalJSON wrote, replacing c. It refuses a format it doesn't read, an op other than "add" or "remove", an op naming no relation, a field the format doesn't write, and a value MarshalJSON couldn't have written, so a session from a newer writer fails rather than reading as something else.

type Conjunction added in v0.1.46

type Conjunction struct {
	Atoms   []PushAtom
	Compare []PushComparison
	// Filter is the filter predicates over the conjunction's variables (#297), each one the store
	// names in FilterSource, which it applies as it does Compare, only to whole rows. The planner offers a group with its comparisons and
	// filters, then without the filters, then without either, so a store refusing filters in Pushes is
	// still asked the rest.
	Filter []PushFilter
	// Partial asks for every prefix of each match too: besides the rows satisfying every atom, for
	// each k from 1 below len(Atoms), one row of k tuples per combination of facts satisfying the
	// first k atoms (comparisons apply only to whole rows). A Federation over partitioned members
	// (NewPartitionedFederation) asks it, continuing a prefix in the members holding the facts the
	// next atom needs, so a join whose facts span members is still answered whole. A store that
	// can't return prefixes refuses a Partial conjunction in Pushes, and is then asked literal by
	// literal; one that returns only whole rows loses the matches that span members.
	Partial bool
	// PrefixesOnly, with Partial, asks for the prefixes alone, not the whole matches: a partitioned
	// Federation summarizing or paging a join across members (#253) has each member's whole matches
	// from its own summary or page, and needs only where each match leaves the member. A store that
	// takes Partial takes this too.
	PrefixesOnly bool
	// Page asks for only the matches behind the first rows of a goal's answer (#241); nil asks for
	// every match.
	Page *Page
	// Inputs are variables an earlier part of the body binds (#246), and Bindings their values, one
	// set per binding in Inputs' order: Push answers c once for each, returning every match whose
	// Inputs equal one of the Bindings, compared as Lookup's values are, in one call, as LookupBatch
	// answers a lookup for many values. A match for no binding may come back, since the engine reads
	// each row's inputs and files it under its binding, but a binding's match left out is lost. The
	// planner offers c with Inputs and no Bindings to Pushes; a store that declines is asked literal by
	// literal, as before.
	//
	// With Partial too, as a partitioned Federation asks (#268), a prefix row is one whose atoms agree
	// with some binding on the Inputs they bind: an input only a later atom reads can't filter it. A
	// store that pushes c with Inputs also pushes its suffixes with the Inputs they still read.
	Inputs   []int
	Bindings [][]Value
	// Units is the unit table the engine folds a Source's values by (#205), set on every conjunction
	// it sends when the vocabulary folds a Source's units (Vocabulary.FoldSourceUnits, #303) and nil
	// otherwise: the conjunction's values are folded by it, and a store holding prefixed values can
	// fold its own with Units.Fold to compare. A Federation folds by it the values it carries from one
	// member to another, so 4 kV from one meets 4000 V in the next. Nil folds nothing.
	Units *Units
}

A Conjunction is a group of base literals a PushSource evaluates together, and the comparisons over their variables.

type ConjunctionWalkSource added in v0.1.50

type ConjunctionWalkSource interface {
	// WalksConjunction reports whether the store walks c from its variable in to its variable out. It
	// is asked while planning and must be cheap.
	WalksConjunction(c Conjunction, in, out int) bool
	// WalkConjunction returns every match of c, one Tuple per atom as Push's rows, whose value at in is
	// reached: one of start, or the value at out of a match it returns. As with Walk, a match for a
	// reached value must not be left out, since the engine asks nothing more about that value, and
	// values compare as Lookup's do. Each row is charged to the Budget as it arrives.
	WalkConjunction(ctx context.Context, c Conjunction, in, out int, start []Value) iter.Seq2[[]Tuple, error]
}

ConjunctionWalkSource is optionally implemented by a Source that follows a step of several literals itself (#250): a recursive rule such as reach(?a, ?c) :- reach(?a, ?b), edge(?b, ?m), attr(?m, "kind", "func"), edge(?m, ?c) walks the conjunction of its edge and attr literals from ?b to ?c, a call (or batch) per round however its bindings batch (#246). The planned evaluator asks for the whole walk in one call instead, as WalkSource does for a single relation, and files each value's matches where a round under that value looks, so answers, citations and witnesses don't change.

type ContextSource added in v0.1.9

type ContextSource interface {
	TuplesContext(ctx context.Context, rel string) ([]Tuple, error)
}

ContextSource is optionally implemented by a Source whose reads take long enough to cancel, such as one that runs a query against a database. When a Source implements it, the engine reads a relation through TuplesContext with the query's context instead of through Tuples, and a cancelled or failed read is not cached: the next query needing the relation reads it again under its own context. A read error stops the query that asked, wrapped with the relation's name.

type DerivedKey added in v0.1.58

type DerivedKey struct {
	// Relation is the relation's name as a program calls it ("reach", "path.reach"). A host reading
	// the relation as facts, such as a walk over derived edges, finds it by Relation and Version.
	Relation string
	// Rules is the text of the relation's rules and of every derived relation they read, sorted and
	// led by Relation's own line, so two keys with the same Rules derive the same tuples from the same
	// facts and a change to any rule below the relation is a new key. It is text rather than a digest,
	// which would bring a hashing package into every host's build; a store wanting a short key hashes
	// it itself.
	Rules string
	// Version is the Source's Version (see Versioned) when the relation was derived.
	Version string
}

A DerivedKey names one derived relation as one set of rules derives it from one version of a Source's facts (#220).

type DerivedStore added in v0.1.58

type DerivedStore interface {
	Derived(ctx context.Context, key DerivedKey) ([]Tuple, bool, error)
	KeepDerived(ctx context.Context, key DerivedKey, tuples []Tuple) error
}

DerivedStore is optionally given to a Base (Base.KeepDerivedIn) to keep the derived relations it evaluates in full beyond its own memory, such as in the host's database, so a relation is derived once per version of the facts however many Bases and processes ask for it (#220). The Base consults it only for a Source that is Versioned, since an unversioned Source's facts have no name a stored relation could be filed under, and only where it would use its own cache: the planned SemiNaive, with no Witnesses or CanonicalCites. Forget doesn't reach the store; a Versioned Source doesn't need it.

Derived returns the tuples kept under key, and whether it holds them. They must come back as KeepDerived was given them: the same values (text, number, unit and absent alike) and citations, in the same order. A tuple of the wrong arity is taken as a miss. An error is taken as a miss too: the Base derives the relation, so a failing store costs work, never answers.

KeepDerived stores a relation an Eval evaluated in full. It may be called again for a key already held, as when two Bases derived it at once, and should then keep either copy. An Eval ignores its error, which the store can log; Materialize returns it. Both may be called from concurrent Evals, so a store guards its own state, and neither is called with the Base's locks held.

type Entry

type Entry struct {
	Path string
	Kind EntryKind
	// Args is a member's signature. On a derived member, an argument no rule head declares is
	// inferred and marked so.
	Args []ArgSig
	// Doc is the member's description: a Schema's or Builtin's Doc, or for a derived member the
	// comment lines above its first rule.
	Doc string
	// Module, Origin and Definition locate a derived member's definition: the path of the module
	// defining it, where that module came from (see Module.Origin), and its clauses as the module's
	// language reports them.
	Module     string
	Origin     string
	Definition []string
	// Members are a module's direct children as full paths, sorted. A child may itself be a module.
	Members []string
}

An Entry describes what sits at one path, for a host offering drill-down discovery: list a module, pick a member, read its definition.

func (Entry) Signature

func (e Entry) Signature() string

Signature renders a member as a rule head declaring its types: `net.has_test_point(n: net)`.

type EntryKind

type EntryKind string

An EntryKind is what sits at a path in the tree.

const (
	EntryModule    EntryKind = "module"
	EntryBase      EntryKind = "base"
	EntryPredicate EntryKind = "predicate"
	EntryDerived   EntryKind = "derived"
)

The things a path can name.

type Extreme added in v0.1.50

type Extreme struct {
	Unit     string
	Numbers  int
	NaN      bool
	Min, Max Value
}

An Extreme is a summary row's numbers in one unit at one of its Extremes variables, each value read as its argument's declared type: Unit is their unit ("" for none), Numbers how many matches hold a number there, NaN whether one of those is NaN, and Min and Max the smallest and largest of the rest by value, absent when every one is NaN. A match whose value isn't a number (text, absent) counts in Matches only. A row has one Extreme per unit its numbers are in; a store may report a unit in several, and the engine combines them. A prefixed Unit, with its Min and Max, is folded as a value is (#205), so extremes in mV and in V combine as one unit.

type Federation added in v0.1.39

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

A Federation is one Source over several (#211): each relation's tuples are the union of its members' tuples, read whole from every member serving it or looked up in only the members that can hold a match. A host passes it to NewBase like any other Source, so facts kept in several stores are queried without first being merged into one.

A fact two members serve is two facts, as it would be in one Source serving it twice: a goal's answer rows are distinct either way, and an aggregate counting bindings counts both.

It is a ContextSource, a StreamSource, a LookupSource, a BatchLookupSource, IndexedLookups, PushSource, SummarySource, WalkSource, ConjunctionWalkSource and Versioned whatever its members are, and pushes a conjunction to a lone member, or across partitioned ones (NewPartitionedFederation). A relation is looked up only when every member serving it looks it up (LooksUp), so a Federation can be a member of another; otherwise the engine reads it whole, from every member, and keeps it. Its version changes whenever a member's does, and a member that isn't Versioned is taken as fixed. Its methods are safe for concurrent use when its members' are.

func NewFederation added in v0.1.39

func NewFederation(members ...Member) (*Federation, error)

NewFederation builds a Federation over members, in the order their relations are listed and their tuples concatenated. A relation several members serve must have the same schema in each: the same arity, labels and types (Doc may differ, and the first member's is kept). It refuses one that doesn't, naming the relation and both members, since the engine would read the members' tuples as one relation.

func NewPartitionedFederation added in v0.1.47

func NewPartitionedFederation(members ...Member) (*Federation, error)

NewPartitionedFederation is NewFederation over members that partition the facts and evaluate conjunctions (PushSource), such as one SQLite file per repo, whose Holds routes each value to the member storing it (#238). It pushes a conjunction across them: to each member Holds allows for the first atom, asking for every prefix of its matches too (Conjunction.Partial), and continues each prefix in the other members Holds allows for the next atom, so a join whose facts span members costs a call per member asked rather than a call per literal, or per prefix leaving a member.

The answer never depends on how precisely Holds routes: a prefix is continued in every other member whose Holds allows the next atom, so a Holds that answers true when unsure costs calls, never matches. What the partition promises is that pushing pays off. A member is asked for prefixes only when another member's Holds allows an atom after the first, and otherwise gets the conjunction whole; a conjunction with an atom no member's Holds allows is answered with nothing (#307).

func (*Federation) Indexed added in v0.1.41

func (f *Federation) Indexed(rel string, bound []int) bool

Indexed implements IndexedLookups: a pattern is indexed when every member serving rel indexes it, a member that doesn't say counting as indexing everything, since one member's scan makes the call a scan.

func (*Federation) LooksUp added in v0.1.39

func (f *Federation) LooksUp(rel string) bool

LooksUp implements LookupRelations: rel is looked up when every member serving it answers lookups.

func (*Federation) Lookup added in v0.1.39

func (f *Federation) Lookup(ctx context.Context, rel string, bound map[int]Value) ([]Tuple, error)

Lookup implements LookupSource, asking each member serving rel whose Holds allows the bound values, in member order, and returning what they answer together. A member that doesn't answer lookups (only asked when LooksUp is false, which the engine doesn't do) returns its whole relation, as the contract allows. A member's failure fails the lookup, wrapped with the member's name.

func (*Federation) LookupBatch added in v0.1.43

func (f *Federation) LookupBatch(ctx context.Context, rel string, positions []int, values [][]Value) ([][]Tuple, error)

LookupBatch implements BatchLookupSource: each member serving rel is asked once for the values its Holds allows, through its own LookupBatch, or one Lookup per value when it has none, so a batch costs a member that batches one round trip however many values it carries. A value's result is its members' results in member order, as Lookup's is. A member that doesn't answer lookups returns its whole relation, read once, as in Lookup. A member's failure fails the batch, wrapped with the member's name.

func (*Federation) Push added in v0.1.46

func (f *Federation) Push(ctx context.Context, c Conjunction) iter.Seq2[[]Tuple, error]

Push implements PushSource, citing each tuple to the member it came from. With one member it asks that member. One atom, or a page of one, goes to each member whose Holds allows it, each answering its own facts' matches, or its own first rows, which hold the federation's (see Page). Partitioned, it asks each member whose Holds allows c's first atom for c with its prefixes, yields that member's whole rows, and continues its prefixes in the other members whose Holds allows the next atom: the rest of c once per member for all prefixes of as many atoms, their values as its Bindings (continuePrefixes), or once per prefix with its values as constants to a member that doesn't take Inputs. With Bindings, each goes only to the members whose Holds allows the first atom under its values, and each of those is asked once for all of its bindings (#268). A match is found once, through the member holding its first fact and then, at each fact held elsewhere, the member holding it. A member's failure is wrapped with its name.

func (*Federation) Pushes added in v0.1.46

func (f *Federation) Pushes(c Conjunction) bool

Pushes implements PushSource. A Federation of one member pushes what that member pushes. A conjunction of one atom, or a page (Conjunction.Page) of one, is pushed when every member serving it pushes it, since one fact is in one member (#263), and a page's first rows are among theirs. Otherwise one of several pushes only when it is partitioned (NewPartitionedFederation), every member serves every relation of c, and each pushes c with its prefixes (Partial), with c's Inputs when it has them (#268). A join of a federation's members otherwise could pair facts no one member sees, and is asked literal by literal.

func (*Federation) PushesFilter added in v0.1.57

func (f *Federation) PushesFilter(name string) bool

PushesFilter implements FilterSource: a Federation applies a filter predicate when every member that pushes does, and at least one pushes.

func (*Federation) Relations added in v0.1.39

func (f *Federation) Relations() []string

Relations implements Source: every member's relations, each once, in the order the members list them.

func (*Federation) Schema added in v0.1.39

func (f *Federation) Schema(rel string) (Schema, bool)

Schema implements Source.

func (*Federation) Summarize added in v0.1.49

Summarize implements SummarySource: each member whose Holds allows c's first atom summarizes its own matches, and its rows' citations name it. A join of a partitioned Federation's members adds the matches spanning members (see spanning), each a row of one match.

func (*Federation) Summarizes added in v0.1.49

func (f *Federation) Summarizes(c Conjunction, s Summary) bool

Summarizes implements SummarySource: a Federation of one member summarizes what it does, and one of several a conjunction of one atom, every member serving it summarizing too. A match of one atom is one fact, held by one member, so the members' rows together hold every match once. A join could pair facts across members, and is pushed (Pushes) or solved instead.

func (*Federation) Timed added in v0.1.63

func (f *Federation) Timed() (*TimedFederation, error)

Timed is f serving versions: a member that is a TimedSource holds its facts in their versions, and any other member holds its facts in every version. Its versions are those every TimedSource member serves. It is refused when no member is a TimedSource.

func (*Federation) Tuples added in v0.1.39

func (f *Federation) Tuples(rel string) []Tuple

Tuples implements Source: the members' tuples for rel, concatenated in member order.

func (*Federation) TuplesContext added in v0.1.39

func (f *Federation) TuplesContext(ctx context.Context, rel string) ([]Tuple, error)

TuplesContext implements ContextSource, reading each member through its TuplesContext when it has one. A member's failure fails the read, wrapped with the member's name.

func (*Federation) TuplesSeq added in v0.1.45

func (f *Federation) TuplesSeq(ctx context.Context, rel string) iter.Seq2[Tuple, error]

TuplesSeq implements StreamSource: the members' tuples for rel in member order, a member that streams one at a time and any other as it reads them whole, so the engine charges each to the budget and stops a large read before the next member is read. A member's failure ends the sequence with it, wrapped with the member's name.

func (*Federation) Version added in v0.1.39

func (f *Federation) Version() string

Version implements Versioned: the members' versions together, each length-prefixed so no two lists of versions read alike. A member that isn't Versioned contributes nothing, as fixed.

func (*Federation) Walk added in v0.1.48

func (f *Federation) Walk(ctx context.Context, w Walk) iter.Seq2[Tuple, error]

Walk implements WalkSource across the members (#239): each start value goes to the members whose Holds allows it, each member walks from its values in one call, and a value a member reached goes on to the other members whose Holds allows it, until no member has a value it hasn't walked. Each member walks a value once, so a walk staying in one store costs one call, and one crossing stores a call per store per crossing. Every member serving the relation is asked when Holds is nil. Each tuple is cited to its member, and a member's failure is wrapped with its name.

Under a MaxDepth (#396) a value goes on with the steps it has left: the Federation finds each reached value's depth from the facts the member returned, a member is asked once per distinct number of steps left among the values it is sent, and a value is walked again where it arrives with more steps left than it was walked with.

func (*Federation) WalkConjunction added in v0.1.50

func (f *Federation) WalkConjunction(ctx context.Context, c Conjunction, in, out int, start []Value) iter.Seq2[[]Tuple, error]

WalkConjunction implements ConjunctionWalkSource through the lone member, citing each tuple to it.

func (*Federation) Walks added in v0.1.48

func (f *Federation) Walks(rel string, from, to int, bound []int) bool

Walks implements WalkSource: a Federation walks rel when every member serving it does.

func (*Federation) WalksConjunction added in v0.1.50

func (f *Federation) WalksConjunction(c Conjunction, in, out int) bool

WalksConjunction implements ConjunctionWalkSource for a Federation of one member that walks it. Over several, a step's facts could lie in different members, and the step is pushed per round instead.

type FilterSource added in v0.1.57

type FilterSource interface {
	// PushesFilter reports whether the store applies the predicate registered under name exactly as
	// the vocabulary does, as stdlib's str.glob has SQLite GLOB's semantics.
	PushesFilter(name string) bool
}

FilterSource is optionally implemented by a PushSource that applies filter predicates to a conjunction's rows (#297). The planner sends a filter in Conjunction.Filter, and grows a group past it, only when PushesFilter names its predicate: a store that ignored a filter it was sent would still answer correctly, but it would join every row the filter drops, so a store that doesn't implement this is sent none. Like Pushes, it is asked while planning and must be cheap.

type IndexedLookups added in v0.1.41

type IndexedLookups interface {
	Indexed(rel string, bound []int) bool
}

IndexedLookups is optionally implemented by a LookupSource that knows which of its lookups it answers from an index, such as a database whose tables are indexed on some columns and not others (#154). Indexed reports whether a lookup of rel with the positions in bound bound (from 0, sorted) reads an index rather than scanning the relation. The planner ranks a call it would look up on an unindexed pattern as if nothing were bound, since the store scans either way, so a call it can answer from an index runs first and binds what the scan would otherwise be asked for. A LookupSource that doesn't implement it is taken as indexing every pattern. The answer for a pattern must not change for the life of a Base.

type IntervalSet added in v0.1.61

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

An IntervalSet is a VersionSet held as ranges, for linear history: a fact that holds from one revision until another is one range, and a new version only changes the ranges of the facts it changed. Ranges that meet are joined, so a set has one form. The zero IntervalSet is empty.

func Intervals added in v0.1.61

func Intervals(rs ...VersionRange) IntervalSet

Intervals is the set holding every version of rs, which may overlap and come in any order.

func IntervalsOf added in v0.1.61

func IntervalsOf(s VersionSet) IntervalSet

IntervalsOf is s as an IntervalSet.

func Since added in v0.1.61

func Since(v Version) IntervalSet

Since is the set of v and every version after it: a fact that still holds.

func Span added in v0.1.61

func Span(from, to Version) IntervalSet

Span is the set of the versions from from up to, but not including, to.

func (IntervalSet) Contains added in v0.1.61

func (s IntervalSet) Contains(v Version) bool

func (IntervalSet) Empty added in v0.1.61

func (s IntervalSet) Empty() bool

func (IntervalSet) Intersect added in v0.1.61

func (s IntervalSet) Intersect(o VersionSet) VersionSet

func (IntervalSet) Minus added in v0.1.61

func (s IntervalSet) Minus(o VersionSet) VersionSet

func (IntervalSet) Ranges added in v0.1.61

func (s IntervalSet) Ranges() iter.Seq[VersionRange]

func (IntervalSet) Union added in v0.1.61

func (s IntervalSet) Union(o VersionSet) VersionSet

type Language

type Language interface {
	// Name is the tag modules are registered under, such as "datalog".
	Name() string
	// Members reports what a module's text defines: each PUBLIC member's bare name, arity, doc and
	// definition. A member the language keeps private is not reported and never gets a path. An error
	// is a module that does not parse or that the language refuses on its own terms.
	Members(text string) ([]MemberDecl, error)
	// Check validates every module of this language against the whole vocabulary, which may hold
	// modules it reads and modules that read it in any registration order, and returns the full
	// signature of each member those modules define, keyed by path. Vocabulary.Check calls it once
	// per state of the vocabulary.
	Check(v *Vocabulary) (map[string][]ArgSig, error)
}

A Language is how a vocabulary learns what a module defines, without parsing anything itself. An engine provides one (jaala/datalog provides "datalog") and a host registers it with AddLanguage before adding modules written in it.

type Layout added in v0.1.8

type Layout func(file string) (module string, ok bool)

A Layout maps a module file, by its path relative to the root AddModulesFS walks, to the module path it registers at. A file it reports false for is not a module and is skipped.

func ByDirectory added in v0.1.8

func ByDirectory(ext string) Layout

ByDirectory is the layout where a directory is a module and each file in it is one module text: a/b/x.dl registers at module a.b, and x.dl at the root. Files without ext are skipped.

func ByFileName added in v0.1.8

func ByFileName(ext string) Layout

ByFileName is the layout where a file's name is its module path: a.b.dl registers at module a.b, wherever it sits under the root. Files without ext are skipped.

type LookupRelations added in v0.1.39

type LookupRelations interface {
	LooksUp(rel string) bool
}

LookupRelations is optionally implemented by a LookupSource that answers lookups for some of its relations and not others, such as a Federation whose members differ (#211). The engine looks up a relation only when LooksUp reports true for it, and reads any other relation whole, once per Base, as it would from a Source without Lookup. A LookupSource that doesn't implement it looks up every relation. The answer for a relation must not change for the life of a Base.

type LookupSource added in v0.1.25

type LookupSource interface {
	Lookup(ctx context.Context, rel string, bound map[int]Value) ([]Tuple, error)
}

LookupSource is optionally implemented by a Source that answers a relation's facts matching some bound arguments from its own index, such as a database table indexed on a column (#126). When a Source implements it, the engine asks Lookup for the facts a call with at least one argument bound needs, instead of reading the relation whole and indexing it in memory. bound maps argument positions, from 0, to the values the call binds them to.

Lookup may return facts that don't match, since the engine checks every one, but it must not leave out one that does, or the answer silently loses it. A bound value is already read as its argument's declared type, and a stored value matches when, read as that type too, it is the same value: two numbers when the numbers are equal (a bound N(1) matches a stored 1.0), two texts when the text is, and a number never text. Read as its type means what the engine does with what Lookup returns: in a number argument text is read as its number, and in a text or entity argument a number as its text, so a pin stored as N(3) matches a bound "3". When the vocabulary folds a Source's units (Vocabulary.FoldSourceUnits, #205, #303), a number's unit is folded as well (Units.Fold): a bound NU(1, "V") matches a stored NU(1000, "mV"), so a source serving prefixed values compares them folded, or returns more. A source whose stored kinds match its declared types, in base units, compares as stored. A source unsure how its index compares can return more.

What Lookup returns is kept for the rest of the Eval that asked, and by the Base for later Evals, up to the Base's LimitLookupCache in tuples (#212), so a repeated question doesn't ask again and a relation the queries only ever probe is held only as far as it was probed. A Versioned Source's version moving drops what was kept, as Forget does. A call with nothing bound still reads the relation whole, through Tuples or TuplesContext, and the Base keeps that read and answers later calls from its own index. Unindexed never calls Lookup. Each call counts one unit of work against the Eval's Budget, and a failed call is wrapped with the relation's name and not kept.

type MemDerivedStore added in v0.1.58

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

MemDerivedStore is an in-memory DerivedStore, for tests and for hosts sharing derived relations between Bases in one process. Its zero value is ready to use.

func (*MemDerivedStore) Derived added in v0.1.58

func (s *MemDerivedStore) Derived(_ context.Context, key DerivedKey) ([]Tuple, bool, error)

Derived returns the tuples kept under key.

func (*MemDerivedStore) KeepDerived added in v0.1.58

func (s *MemDerivedStore) KeepDerived(_ context.Context, key DerivedKey, tuples []Tuple) error

KeepDerived keeps tuples under key, replacing what was there.

func (*MemDerivedStore) Relation added in v0.1.58

func (s *MemDerivedStore) Relation(rel, version string) ([]Tuple, bool)

Relation returns the tuples of the relation named rel kept at version under any rules, and whether exactly one set of rules derived it there. It is how a host reads a derived relation as facts.

type MemSource

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

MemSource is an in-memory Source, for tests and for hosts whose facts are already a handful of tables. Declare a relation, then Add its tuples.

func NewMemSource

func NewMemSource() *MemSource

NewMemSource returns an empty MemSource.

func (*MemSource) Add

func (m *MemSource) Add(rel string, t Tuple) *MemSource

Add appends one tuple to a declared relation. It panics on an undeclared relation or a wrong arity, because either is a programming error in the host rather than a property of the data.

func (*MemSource) Declare

func (m *MemSource) Declare(rel string, labels ...string) *MemSource

Declare adds a relation with the given argument labels; its arity is the number of labels. Declaring a name twice replaces its schema and keeps its tuples.

func (*MemSource) DeclareSchema

func (m *MemSource) DeclareSchema(rel string, s Schema) *MemSource

DeclareSchema adds a relation with an explicit schema, for one that declares Types or a Doc.

func (*MemSource) Relations

func (m *MemSource) Relations() []string

Relations implements Source, listing names in sorted order.

func (*MemSource) Schema

func (m *MemSource) Schema(rel string) (Schema, bool)

Schema implements Source.

func (*MemSource) Tuples

func (m *MemSource) Tuples(rel string) []Tuple

Tuples implements Source.

type Member added in v0.1.39

type Member struct {
	// Name identifies the member in errors and, when set, in citations: each of its tuples' citations
	// reads Name + ":" + citation, so a witness says which store a fact came from. Empty leaves its
	// citations as the Source wrote them.
	Name string
	// Source serves the member's facts.
	Source Source
	// Holds reports whether the member can hold a fact of rel matching the bound arguments (positions
	// from 0, values read as the arguments' declared types, as LookupSource's are). A lookup goes only
	// to the members that can, so a member holding one repo's ids is never asked about another's. It
	// may answer true when unsure, never false for a fact the member holds, or the answer loses it.
	// Binding fewer arguments never answers false where binding more would answer true: a partitioned
	// push asks first with only an atom's constants bound, and skips the member, or the whole
	// conjunction, on false (#307). Nil holds anything. Reading a relation whole always reads every
	// member.
	Holds func(rel string, bound map[int]Value) bool
}

A Member is one Source in a Federation.

type MemberDecl

type MemberDecl struct {
	Name  string // bare: the member's path is the module path plus this
	Arity int
	// Doc is the member's description, for Lookup.
	Doc string
	// Definition is the member's definition in its language's own syntax, one entry per clause, for a
	// host showing a reader how a member is defined.
	Definition []string
}

A MemberDecl is one public member a module defines, as its Language reports it.

type Module

type Module struct {
	Path     string
	Language string
	Text     string
	// Origin says where the text came from, such as the file it was read from, so a host can tell a
	// reader where a member is defined or which file to fix. It is whatever the host passed, and may
	// be empty.
	Origin  string
	Members []MemberDecl
}

A Module is one AddModule call: text in a language, registered at a module path.

type ModuleError added in v0.1.8

type ModuleError struct {
	// Module is the module's index into Modules(), or, for a module AddModule refused, the index it
	// would have had.
	Module int
	Path   string
	Origin string
	Err    error
}

A ModuleError is a failure that one module is responsible for: a module AddModule refused, or a rule of a registered module that Check refused. Several modules may share a path, so Module and Origin are what tell a host which one, through errors.As; Error is the cause's message unchanged.

func (*ModuleError) Error added in v0.1.8

func (e *ModuleError) Error() string

Error returns the cause's message, exactly as it would read without the module attached.

func (*ModuleError) Unwrap added in v0.1.8

func (e *ModuleError) Unwrap() error

Unwrap returns the cause.

type NoVocabularyHinter

type NoVocabularyHinter interface {
	NoVocabularyHint() string
}

NoVocabularyHinter is optionally implemented by a Source to explain an empty vocabulary in the host's terms, such as which import installs its relations. The text follows "; " in an unknown- relation error.

type OverlaySource added in v0.1.79

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

An OverlaySource is a working session's edits over a Source (#288): it serves the base's facts, minus those a change set names, plus those it adds, so a query reads the session's own writes before they are committed, and the base is never changed. Rolling the session back drops the overlay; an undo stack is a stack of Changes composed with Then, each state its own overlay.

A fact the change set names is replaced wherever the base holds it, as Changes.Apply does, and is matched as a Lookup matches, each value read as its argument's declared type, so a removal names a fact by the values the store serves (in the store's own units). An overlay passes on every interface the base implements: whole reads stream when the base streams, a lookup or a batch goes to the base and the added facts join its answer (every one of the relation's, which a lookup may return, since the engine checks each), and a pushed conjunction, a walk or a summary goes to the base only when it reads no relation the session touched, which is otherwise solved literal by literal through lookups.

An overlay is fixed once made and safe for concurrent use as its base is. Its Version is the base's joined with the change set's, so a Base over a session sees a new version whenever an edit makes a new overlay, and drops what it kept; a session's Base and the base's own keep separate caches, and the base's stay valid. An overlay over a TimedSource serves its plain reads, so to edit a version, overlay that version's Source (SourceAt) instead.

func Overlay added in v0.1.79

func Overlay(base Source, c Changes) *OverlaySource

Overlay returns base with c applied. c is copied, so editing it afterwards doesn't change the overlay.

func (*OverlaySource) Base added in v0.1.79

func (o *OverlaySource) Base() Source

Base is the Source the overlay edits.

func (*OverlaySource) Changes added in v0.1.79

func (o *OverlaySource) Changes() Changes

Changes is the change set the overlay applies.

func (*OverlaySource) Effective added in v0.1.79

func (o *OverlaySource) Effective(ctx context.Context) (Changes, error)

Effective is the session's changes that change the base: a removal of a fact the base holds and an addition of one it doesn't, in the order the change set names them. A fact added that the base holds already, with other citations or another ID, isn't a change, as Base.Diff doesn't count one. It is what a host rechecks after an edit, and what a commit adds as a new version. Each fact is looked up with every argument bound when the base looks its relation up, and the relation is read whole once otherwise.

func (*OverlaySource) Indexed added in v0.1.79

func (o *OverlaySource) Indexed(rel string, bound []int) bool

Indexed is the base's answer, and true when the base doesn't say.

func (*OverlaySource) LooksUp added in v0.1.79

func (o *OverlaySource) LooksUp(rel string) bool

LooksUp is whether the base looks rel up.

func (*OverlaySource) Lookup added in v0.1.79

func (o *OverlaySource) Lookup(ctx context.Context, rel string, bound map[int]Value) ([]Tuple, error)

Lookup asks the base, drops the facts the session names, and adds every fact it adds to rel. A base that doesn't look rel up is read whole, which Lookup's contract allows.

func (*OverlaySource) LookupBatch added in v0.1.79

func (o *OverlaySource) LookupBatch(ctx context.Context, rel string, positions []int, values [][]Value) ([][]Tuple, error)

LookupBatch asks the base in one batch when it batches, and one value at a time otherwise, then edits each result as Lookup does.

func (*OverlaySource) NoVocabularyHint added in v0.1.79

func (o *OverlaySource) NoVocabularyHint() string

NoVocabularyHint is the base's, when it gives one.

func (*OverlaySource) Push added in v0.1.79

Push is the base's, for a conjunction Pushes accepted.

func (*OverlaySource) Pushes added in v0.1.79

func (o *OverlaySource) Pushes(c Conjunction) bool

Pushes is the base's answer for a conjunction reading no relation the session touched, and false otherwise or when the base doesn't push.

func (*OverlaySource) PushesFilter added in v0.1.79

func (o *OverlaySource) PushesFilter(name string) bool

PushesFilter is the base's answer, and false when it doesn't say.

func (*OverlaySource) Relations added in v0.1.79

func (o *OverlaySource) Relations() []string

func (*OverlaySource) Schema added in v0.1.79

func (o *OverlaySource) Schema(rel string) (Schema, bool)

func (*OverlaySource) Summarize added in v0.1.79

Summarize is the base's, for a conjunction Summarizes accepted.

func (*OverlaySource) Summarizes added in v0.1.79

func (o *OverlaySource) Summarizes(c Conjunction, s Summary) bool

Summarizes is the base's answer for a conjunction reading no relation the session touched.

func (*OverlaySource) Tuples added in v0.1.79

func (o *OverlaySource) Tuples(rel string) []Tuple

Tuples serves rel with the session's edits applied. A base read failing reads as no facts there, as through the base's own Tuples; the engine reads through TuplesSeq, which reports it.

func (*OverlaySource) TuplesContext added in v0.1.79

func (o *OverlaySource) TuplesContext(ctx context.Context, rel string) ([]Tuple, error)

TuplesContext reads rel from the base as the engine would, and applies the session's edits.

func (*OverlaySource) TuplesSeq added in v0.1.79

func (o *OverlaySource) TuplesSeq(ctx context.Context, rel string) iter.Seq2[Tuple, error]

TuplesSeq streams rel's facts with the session's edits applied: the base's as it hands them over, when it streams, then the facts the session adds.

func (*OverlaySource) Version added in v0.1.79

func (o *OverlaySource) Version() string

Version is the base's version, when it has one, joined with a fingerprint of the change set, which covers each fact's values, ID and citations.

func (*OverlaySource) Walk added in v0.1.79

func (o *OverlaySource) Walk(ctx context.Context, w Walk) iter.Seq2[Tuple, error]

Walk is the base's, for a walk Walks accepted.

func (*OverlaySource) WalkConjunction added in v0.1.79

func (o *OverlaySource) WalkConjunction(ctx context.Context, c Conjunction, in, out int, start []Value) iter.Seq2[[]Tuple, error]

WalkConjunction is the base's, for a walk WalksConjunction accepted.

func (*OverlaySource) Walks added in v0.1.79

func (o *OverlaySource) Walks(rel string, from, to int, bound []int) bool

Walks is the base's answer for a relation the session didn't touch.

func (*OverlaySource) WalksConjunction added in v0.1.79

func (o *OverlaySource) WalksConjunction(c Conjunction, in, out int) bool

WalksConjunction is the base's answer for a conjunction reading no relation the session touched.

type Page added in v0.1.49

type Page struct {
	Columns []int
	Order   []PageKey
	Limit   int
	// After, when set, has one value per Order key: the page starts after them (#254), its rows being
	// those whose values at Order come strictly after After in that order, each key compared in the
	// engine's order and reversed by Desc, as the query's after clause keeps them. The store's first
	// Limit rows are then its first after the cursor.
	After []Value
}

A Page limits a pushed goal to the matches behind its first Limit answer rows. An answer row is a match's values at Columns, and rows are distinct: matches with equal values there make one row. The rows are ordered by Order's keys and then by Columns, each ascending unless a key says Desc, in the engine's order: an absent value first, then numbers by value, then text by its bytes. With no Order the store may take any Limit rows. The store returns every match behind each of the rows it takes, so the engine picks among them as it would in memory; it may return more matches or more rows, never fewer of either. Across stores, the rows the answer needs are among each store's first Limit, which is why a store can answer a page of a federation's answer alone.

type PageKey added in v0.1.49

type PageKey struct {
	Var  int
	Desc bool
}

A PageKey orders a Page by a variable of the Conjunction.

type Path added in v0.1.79

type Path struct {
	Nodes []Value
	Edges []Value
	// HasEdges says the path names its edges, so a path of no steps still writes its (empty) edges.
	HasEdges bool
}

A Path is a walk's route as a value (jaala#280): its nodes in order from where it starts, and, when the relation it walked names its edges (from, edge, to), the edge taken at each step. A path of n steps has n+1 nodes and, with edges, n edges.

A path travels through a query as the text Text writes, so it joins, dedups and orders as any text does, an answer shows it as written, and stdlib's path.* functions read it with ParsePath, with no state held anywhere. A path over a two-argument relation is a JSON list of its nodes, ["a","b","c"]; one with edges is {"nodes":["a","b","c"],"edges":["e1","e2"]}, since a list alternating nodes and edges would read the same as a list of nodes.

func ParsePath added in v0.1.79

func ParsePath(s string) (Path, error)

ParsePath reads a path's value back, its values as ParseList reads a list's. It refuses text Text could not have written, and an object whose edges aren't one fewer than its nodes.

func (Path) Steps added in v0.1.79

func (p Path) Steps() int

Steps is how many steps the path takes.

func (Path) Text added in v0.1.79

func (p Path) Text() string

Text is the path's value: its nodes as a list (ListText), or an object of its nodes and edges, each a list.

type PushArg added in v0.1.46

type PushArg struct {
	Var   int
	Const *Value
}

A PushArg is one argument of a PushAtom or one side of a PushComparison: a constant when Const is set, a variable when Var is (numbered from 1 within the Conjunction, the same number wherever the variable appears, so a variable written twice is a join), and otherwise a wildcard matching anything. A constant is read as its argument's declared type, as a stored value is: a Federation continuing a prefix passes on values as the member that stored them wrote them.

type PushAtom added in v0.1.46

type PushAtom struct {
	Relation string
	Args     []PushArg
}

A PushAtom is one literal of a Conjunction: a relation the Source serves, and an argument per position of its schema.

type PushComparison added in v0.1.46

type PushComparison struct {
	Op          string
	Left, Right PushArg
}

A PushComparison is a comparison the conjunction's rows must pass: Op is one of = != < <= > >=, and each side a variable of the Conjunction or a constant, never a wildcard.

The engine orders values totally: an absent value first, then numbers by value, then text by its bytes. An ordering comparison is false when either side is absent, when one side is a number and the other text, or when both are numbers with different units; a number with no unit compares with a number in any unit. = and != follow equality as Lookup describes it, where two absent values are equal. A store that can't match these exactly for some comparison skips it.

type PushFilter added in v0.1.57

type PushFilter struct {
	Predicate string
	Args      []PushArg
}

A PushFilter is a filter predicate the conjunction's rows must pass: Predicate is its name as the vocabulary registered it (str.glob, str.match), and Args one per argument, each a variable of the Conjunction or a constant, never a wildcard. A store may apply one only when it answers exactly as the predicate does, and otherwise skips it: a row the filter would drop may come back, since the engine checks every row again, but a row it keeps must not be left out. stdlib's str.glob has SQLite GLOB's semantics (whole string, case-sensitive), so a SQLite store can apply it as GLOB.

type PushSource added in v0.1.46

type PushSource interface {
	// Pushes reports whether the store evaluates c. The planner asks while planning, growing a group
	// one literal at a time and offering it with its comparisons and then without, so it must be
	// cheap and do no I/O. The answer for a conjunction must not change for the life of a Base. A
	// store that pushes c also pushes each of its suffixes (the atoms from some k on, and the
	// comparisons) with some variables replaced by constants, which a Federation asks to continue a
	// prefix.
	Pushes(c Conjunction) bool
	// Push answers c: one row per combination of facts satisfying it, each row one Tuple per atom of
	// c, in c.Atoms' order, with the fact's Cites, so an answer keeps its witnesses and citations.
	//
	// As with Lookup, a row may be one that doesn't satisfy c, since the engine checks every row's
	// tuples against the atoms and the comparisons again, but a row that does satisfy it must not be
	// left out, or the answer silently loses it. Values compare as Lookup's do: each read as its
	// argument's declared type, two numbers equal when the numbers are, two texts when the text is,
	// and a number never text. A store may skip any comparison it can't evaluate exactly as the
	// engine does (see PushComparison), or any filter (see PushFilter), and leave it to the engine. A
	// row repeated is two
	// derivations, as a fact a Source serves twice is two facts, so a row is never sent twice.
	//
	// Each row is charged to the Eval's Budget as it arrives, so the engine may stop ranging early
	// (the budget is spent or the query's context ends) and the sequence should then release what
	// it holds. An error yielded stops the push and fails the query, wrapped with the conjunction.
	// What a completed push returned is kept as a Lookup's is (see LookupSource); one that stopped
	// is not kept.
	Push(ctx context.Context, c Conjunction) iter.Seq2[[]Tuple, error]
}

PushSource is optionally implemented by a Source that evaluates a conjunction over its own facts, such as a database turning one into a single statement (#237). When a Source implements it, the planned evaluator hands it a group of a body's base literals joined by shared variables, with the comparisons over them, and solves the rest of the body itself, so a join within the store costs one call and ships only the rows that join rather than every intermediate tuple.

A group bound partway through a body carries the variables bound before it as Inputs (#246). A group is at least two literals, or one with nothing bound and no constant that the store filters better than a whole read: a variable repeated in it, or a comparison going with it (#263). A literal with a constant or a bound variable is a Lookup.

A conjunction's constants, Inputs, Bindings and comparison operands are values as the engine holds them. When it folds a Source's units (Conjunction.Units set, #205, #303) they are in folded units, so a store serving prefixed values compares and joins them folded, as a LookupSource matches them: 1 V meets the 1000 mV it holds, and 500 mV passes ?v > 0.4 V. That goes for a FilterSource's filters and a SummarySource's groups too.

type Schema

type Schema struct {
	// Arity is the number of arguments every tuple of the relation carries.
	Arity int
	// Labels names the arguments for error messages ("ref_des", "net"). Optional, and may be shorter
	// than Arity; an unlabelled argument is simply never named.
	Labels []string
	// Types says what each argument denotes: an entity kind, a scalar type with its unit, and
	// optionally a closed vocabulary (see ArgType). Optional, and may be shorter than Arity; a missing
	// entry is an argument the relation says nothing about. Kinds and owners name other arguments by
	// their Labels, so a relation declaring them labels its arguments.
	//
	// A Domain here is enforced: a CONSTANT outside it is rejected before evaluation rather than
	// silently matching nothing, because an empty answer to a question that was never valid reads as
	// a fact about the data. It is only enforced on a labelled argument, since the error has to name
	// what the argument is. A Type is enforced too: a constant is read as the argument's type, or
	// refused when it cannot be (see ArgType.Type).
	Types []ArgType
	// Doc is a one-line description a host shows when the relation is listed (see Vocabulary.Lookup).
	Doc string
}

A Schema describes one relation a Source serves.

type Session added in v0.1.79

type Session struct {
	Base    string  `json:"base,omitempty"`
	Changes Changes `json:"changes"`
}

A Session is a change set with the version of the facts it was made over (#417), as a host sends it between processes: a browser keeping a session beside its snapshot, a server reading it through an Overlay of its own store, or a commit. Base is the host's name for that version (its Versioned string, a revision id), carried and never read by jaala, so a host can refuse a session made over a version that has since moved, or rebase it. Empty, the session says nothing about its base.

type Source

type Source interface {
	// Schema reports whether the source serves rel, and its shape.
	Schema(rel string) (Schema, bool)
	// Tuples returns every fact of rel. Called at most once per relation per Base, unless the Source
	// is Versioned and its version changes, or the host calls the Base's Forget.
	Tuples(rel string) []Tuple
	// Relations lists every relation name the source serves, in the order a did-you-mean suggestion
	// should prefer on a tie. An EMPTY list means no vocabulary is installed at all, which the engine
	// treats differently from a vocabulary that lacks a name: it cannot call a relation unknown when
	// it knows of none, so it says so instead of guessing at a typo.
	Relations() []string
}

A Source is where the base (extensional) relations come from. The engine asks it for a relation's schema when it meets an atom, and for the relation's tuples the first time it needs them; it indexes and caches from there, so a Source need not.

Tuples are treated as immutable for the life of a Base. Each relation is read once per Base, by one goroutine, even when several Evals on the Base first need it at the same moment; different relations may be read concurrently.

type SourceAt added in v0.1.63

type SourceAt interface {
	TimedSource
	SourceAt(v Version) (Source, error)
}

SourceAt is optionally implemented by a TimedSource that serves each version's facts as a Source of its own (#312): the facts holding in v, with v's citations, through whichever of the interfaces a plain Source may implement it does (LookupSource, PushSource, StreamSource, WalkSource, SummarySource and the rest). An Eval under datalog.At(v) then reads version v as it reads any Source, asking the store for what a query binds rather than reading TimedTuples whole, and never calls TimedTuples. Across reads TimedTuples, or LookupTimed for a bound call (TimedLookupSource), and Diff reads TimedTuples.

The engine calls SourceAt once for each version whose caches it holds (datalog's LimitVersions), and again after it drops them, so a host whose versions live in one store returns a small view of it, the store and v, rather than copying anything. The returned Source serves the TimedSource's relations with the same schemas; one that is Versioned keys its version's kept relations (KeepDerivedIn) by its own version too. An error fails the Eval that asked, and the next Eval at v asks again.

type StreamSource added in v0.1.45

type StreamSource interface {
	TuplesSeq(ctx context.Context, rel string) iter.Seq2[Tuple, error]
}

StreamSource is optionally implemented by a Source that can hand over a relation's facts one at a time, such as one reading a database cursor (#233). When a Source implements it, the engine reads a relation whole through TuplesSeq rather than TuplesContext or Tuples, and charges each tuple to the Eval's Budget as it arrives, so a query over a relation larger than its budget stops having held at most that many tuples rather than after the whole relation is in memory. A Source that returns a slice is read as before, and its read is not charged.

The engine stops ranging when the budget is spent or the query's context ends, so the sequence should release what it holds (close its cursor) when yield returns false. An error yielded stops the read and fails the query, wrapped with the relation's name; a read that stops for any reason is not kept, and the next query needing the relation reads it again. A relation read in full is kept, as Tuples is, except one only the goal reads, which the engine solves as it arrives and doesn't keep (#264), so a limit stops the read; such a relation may be read once per query.

While TuplesSeq yields, the engine is solving the rest of the body for that tuple, so it may call Lookup, LookupBatch or TuplesSeq on this Source before asking for the next tuple (#126, #264). The sequence must not hold anything those calls need across a yield. A store with one database connection that keeps it in an open cursor while it yields waits on itself forever: declaire#370's `calls(?a, ?b), str.prefix(?b, "b"), edge(?b, ?k, ?c) => ?a, ?c limit 2` did, streaming calls and looking edge up. Read a page, release the connection, then yield it. CheckStreamReentrant tests a store for this (#539).

type Summary added in v0.1.49

type Summary struct {
	Group    []int
	Values   []int
	Extremes []int
}

A Summary asks for a conjunction's matches grouped by the values of the variables in Group and in Values. The engine reads Group as an aggregate's group and Values as the values it reduces; a count of bindings needs neither, so a goal counting with no group asks for one row. Extremes are variables only min and max read (#252): rather than group by their values, a row reports, per unit, the smallest and largest of its matches' numbers there (see Extreme), so a min over a column of distinct measurements is a row per group, not per value. A store that can't asks to be sent them as Values, by refusing a Summary with Extremes in Summarizes.

type SummaryRow added in v0.1.49

type SummaryRow struct {
	Group    []Value
	Values   []Value
	Matches  int
	Cites    []string
	Extremes [][]Extreme
}

A SummaryRow is one row of a Summary: the values at its Group and Values variables, in their order, the number of matches with them, those matches' facts' citations, and per Extremes variable, in order, its numbers' extremes by unit.

type SummarySource added in v0.1.49

type SummarySource interface {
	// Summarizes reports whether the store summarizes c as s asks. Like Pushes, it is asked while
	// planning and must be cheap.
	Summarizes(c Conjunction, s Summary) bool
	// Summarize returns c's matches as rows of a Summary: every match in exactly one row, whose Group
	// and Values are the match's values at s.Group and s.Values, Matches how many matches the row
	// covers, and Cites the citations of every fact behind them. Two matches share a row only when
	// their values there are identical, the same text, number and unit, since an aggregate reads each
	// one: 5 V and 5 A are one number but two units, and a sum over them is absent. A store may split
	// matches it could have merged, since the engine merges rows by its own equality, but a match
	// counted twice, or left out, changes the answer. A match is a combination of facts satisfying
	// every atom of c, its constants and joins, which the engine can't check again; c's comparisons the
	// store may skip, since the engine asks for the values they read (in s.Values) and checks them on
	// each row. Each row is charged to the Budget as it arrives.
	Summarize(ctx context.Context, c Conjunction, s Summary) iter.Seq2[SummaryRow, error]
}

SummarySource is optionally implemented by a PushSource that reduces a conjunction's matches itself, such as a database answering GROUP BY (#240). The planned evaluator asks it for a goal that aggregates, and reduces what comes back with its own rules (exact sums, units, NaN, absent over nothing), so a count costs a row per group and store rather than a row per match.

type TimedCites added in v0.1.61

type TimedCites struct {
	Versions VersionSet
	Cites    []string
}

TimedCites are a fact's citations in some of its versions.

type TimedFederation added in v0.1.63

type TimedFederation struct {
	*Federation
}

A TimedFederation is a Federation whose facts hold over versions (#312), so one Base answers At(v) and Across over facts kept in several stores, such as a design's netlist store serving each revision beside a datasheet store that doesn't change between them. Made by Federation.Timed, it is a TimedSource, a SourceAt and a TimedLookupSource, and as a plain Source it is the Federation it was made from.

func (*TimedFederation) LooksUpTimed added in v0.1.64

func (t *TimedFederation) LooksUpTimed(rel string) bool

LooksUpTimed implements TimedLookupRelations: rel is looked up across versions when every member serving it answers such a lookup, a TimedSource member through LookupTimed and any other through Lookup, each as its own LooksUpTimed or LooksUp allows.

func (*TimedFederation) LookupTimed added in v0.1.64

func (t *TimedFederation) LookupTimed(ctx context.Context, rel string, bound map[int]Value) ([]TimedTuple, error)

LookupTimed implements TimedLookupSource, asking each member serving rel whose Holds allows the bound values, in member order, as Lookup does: a TimedSource member through its LookupTimed, and any other through Lookup, its facts holding in every version the federation serves. A member that can't look up (only asked when LooksUpTimed is false, which the engine doesn't do) returns its whole relation. A member's failure fails the lookup, wrapped with the member's name.

func (*TimedFederation) SourceAt added in v0.1.63

func (t *TimedFederation) SourceAt(v Version) (Source, error)

SourceAt implements SourceAt: a Federation over the members at v, with their names and Holds, and partitioned when t is. A TimedSource member is its own SourceAt(v), or its facts at v read from TimedTuples when it has none; any other member is itself.

func (*TimedFederation) TimedTuples added in v0.1.63

func (t *TimedFederation) TimedTuples(ctx context.Context, rel string) ([]TimedTuple, error)

TimedTuples implements TimedSource: the members' facts of rel in member order, a member that isn't a TimedSource holding each of its facts in every version the federation serves. A member's failure fails the read, wrapped with the member's name.

func (*TimedFederation) Versions added in v0.1.63

func (t *TimedFederation) Versions() VersionSet

Versions implements TimedSource: the versions every member that is a TimedSource serves.

type TimedLookupRelations added in v0.1.64

type TimedLookupRelations interface {
	LooksUpTimed(rel string) bool
}

TimedLookupRelations is optionally implemented by a TimedLookupSource that answers LookupTimed for some of its relations and not others, such as a TimedFederation whose members differ. Under Across the engine looks up a relation only when LooksUpTimed reports true for it, and reads any other from TimedTuples whole. A TimedLookupSource that doesn't implement it looks up every relation. The answer for a relation must not change for the life of a Base.

type TimedLookupSource added in v0.1.64

type TimedLookupSource interface {
	TimedSource
	LookupTimed(ctx context.Context, rel string, bound map[int]Value) ([]TimedTuple, error)
}

TimedLookupSource is optionally implemented by a TimedSource that answers a call with bound arguments across versions from its own index (#317), so an Eval under datalog.Across asks it for what a query binds, as an Eval asks a LookupSource, rather than reading the relation's TimedTuples whole. bound maps argument positions, from 0, to values, as Lookup's does, and LookupTimed returns the matching facts as TimedTuples returns them: each once, with the versions it holds in and its citations per version. It is under Lookup's contract otherwise: it may return facts that don't match, which the engine drops, and must not leave out one that does; each call counts one unit of work; a failed call fails the Eval, wrapped with the relation's name, and isn't kept. What it returns is kept for the rest of the Eval that asked, and not by the Base, since Across keeps nothing between Evals. A call with nothing bound still reads TimedTuples. At(v) doesn't call it: a version is read through SourceAt or from TimedTuples.

type TimedMemSource added in v0.1.61

type TimedMemSource struct {
	*MemSource
	// contains filtered or unexported fields
}

TimedMemSource is an in-memory TimedSource, for tests and for hosts whose versions are already a handful of tables. Declare a relation, then Add each fact with its versions. As a plain Source it serves the facts of its last version.

func NewTimedMemSource added in v0.1.61

func NewTimedMemSource(vs VersionSet) *TimedMemSource

NewTimedMemSource returns an empty TimedMemSource serving the versions vs.

func (*TimedMemSource) Add added in v0.1.61

func (m *TimedMemSource) Add(rel string, vs VersionSet, cites []string, vals ...Value) *TimedMemSource

Add adds a fact of rel holding in vs, with cites in every one of them.

func (*TimedMemSource) AddTimed added in v0.1.61

func (m *TimedMemSource) AddTimed(rel string, t TimedTuple) *TimedMemSource

AddTimed adds a fact whose citations differ between its versions.

func (*TimedMemSource) Commit added in v0.1.79

func (m *TimedMemSource) Commit(c Changes, from, to Version) error

Commit adds version to, holding version from's facts with c applied (#288): each fact from holds that c doesn't name holds in to too, with from's citations, each fact c adds holds in to with c's citations, under the ID it already had when the source holds it in another version, and no other fact holds in to, whatever range it was added with. Base.Diff from from to to is then c's changes that change from, as a session's OverlaySource.Effective reports them. A fact is its values, each read as its argument's declared type, as the engine reads it.

A host's own TimedSource commits a session the same way: the new version is the old one's facts with the change set applied, and the facts a version shares with another keep one TimedTuple. Commit refuses a from the source doesn't serve, a to it serves already, and a relation it doesn't declare. It is not safe to call while a Base over the source is evaluating.

func (*TimedMemSource) TimedTuples added in v0.1.61

func (m *TimedMemSource) TimedTuples(_ context.Context, rel string) ([]TimedTuple, error)

func (*TimedMemSource) Tuples added in v0.1.61

func (m *TimedMemSource) Tuples(rel string) []Tuple

Tuples serves rel's facts in the last of the source's versions.

func (*TimedMemSource) Version added in v0.1.79

func (m *TimedMemSource) Version() string

Version moves with each Commit, so a Base over the source reads the committed version's facts.

func (*TimedMemSource) Versions added in v0.1.61

func (m *TimedMemSource) Versions() VersionSet

type TimedSource added in v0.1.61

type TimedSource interface {
	Source
	// Versions are every version the Source serves. An Eval at a version outside it is refused.
	Versions() VersionSet
	// TimedTuples returns every fact of rel in any version, each once, with the versions it holds in.
	TimedTuples(ctx context.Context, rel string) ([]TimedTuple, error)
}

TimedSource is optionally implemented by a Source that serves several versions of its facts, so one Base answers at any of them (#179). An Eval given datalog.At(v) reads the facts of version v; one without reads the Source as any other, through Tuples and the optional interfaces it implements, so a TimedSource serves there whichever facts it wants a plain question to see, such as its latest version's. The schemas are the same in every version.

The engine reads each relation's TimedTuples once per Base, as it reads Tuples, and keeps a version's facts apart from another's, so a question at one version never sees another's caches. A TimedSource that is Versioned too drops all of it when its version moves, such as when a new revision is added.

type TimedTuple added in v0.1.61

type TimedTuple struct {
	Vals     []Value
	Versions VersionSet
	// Cites are the fact's citations per version. A version the fact holds in that no entry names has
	// no citations, and an entry's versions outside Versions are ignored.
	Cites []TimedCites
	// ID is the fact's Tuple.ID, the same in every version it holds in.
	ID string
}

A TimedTuple is a fact with the versions it holds in (#179). A fact is its values: the same values in two versions are one TimedTuple whose Versions hold both, however their citations differ, so a host whose citations change from one export to the next still shares its unchanged facts across versions.

func (TimedTuple) CitesAt added in v0.1.61

func (t TimedTuple) CitesAt(v Version) []string

CitesAt are t's citations in version v, the first entry naming v; nil when none does.

type Tuple

type Tuple struct {
	Vals  []Value
	Cites []string
	// ID is the host's name for this fact, which a query binds with `edge(?a, ?b) as ?r` (#279) and
	// can then return, compare and join on, as Cypher reads a relationship's identity. A store whose
	// facts carry attributes keys them by it, so a query reads them through an ordinary relation of
	// the host's. Two facts with one ID are one fact as far as a query comparing them can tell, so an
	// ID names one fact across every member of a Federation. Empty, the engine names the fact by its
	// relation and values, `edge("a", "b")`, so two facts with the same values share a name.
	ID string
}

A Tuple is one fact of a relation: its values in argument order, plus the citations that justify it. Base facts and derived facts share this shape, so a derived answer stays as verifiable as a looked-up one.

type Unit added in v0.1.37

type Unit struct {
	Scale int
	Dims  map[string]int
	// contains filtered or unexported fields
}

A Unit is a dimension as a scale and symbols with exponents: mV is {Scale: -3, V: 1} and m/s is {m: 1, s: -1} (jaala#5). The scale is a power of ten times an exact factor (Factor), so a host can name min as 60*s or KiB as 1024*B (jaala#303). Multiplying adds exponents and multiplies scales, so a unit nobody named (distance over time) is still a unit, written m/s. A Vocabulary names units through AddUnit, so A*ohm is V once V is defined as A*ohm.

A unit is only symbols to the engine, which never knows what a volt or a metre is: two numbers order and aggregate together when their units are the same symbols, and a symbol nobody defined is a unit of its own, compared by its text.

func (Unit) Div added in v0.1.37

func (u Unit) Div(o Unit) Unit

Div is u over o.

func (Unit) Factor added in v0.1.60

func (u Unit) Factor() (num, den int64)

Factor is the exact factor u's scale has beside its power of ten, as a fraction: 6/1 for min defined as 60*s (with Scale 1), 1/1 for mV. The scale is num/den times ten to the Scale.

func (Unit) IsZero added in v0.1.37

func (u Unit) IsZero() bool

IsZero reports whether u is no unit at all: no symbols and no scale.

func (Unit) Mul added in v0.1.37

func (u Unit) Mul(o Unit) Unit

Mul is u times o: scales multiply and exponents add.

func (Unit) Pow added in v0.1.37

func (u Unit) Pow(n int) Unit

Pow is u to the n.

func (Unit) Same added in v0.1.37

func (u Unit) Same(o Unit) bool

Same reports whether two units have one scale and the same symbols to the same powers.

func (Unit) String added in v0.1.37

func (u Unit) String() string

String writes u with its symbols sorted, the ones with a positive power over the rest, as in A*ohm, m/s, m/(K*s^2) or 1/s, and a scale as a number first (1e3*V, 6e1*s, 1/(6e1*s)). ParseUnit reads it back.

func (Unit) Unscaled added in v0.1.60

func (u Unit) Unscaled() Unit

Unscaled is u's symbols with no scale: mV's is V, and min's (60*s) is s.

type Units added in v0.1.37

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

Units is a vocabulary's unit table: units defined in terms of others, and prefixes. A symbol it doesn't define is a base unit of its own, so a host's data can carry any unit.

func (*Units) Fold added in v0.1.59

func (t *Units) Fold(f float64, unit string) (float64, string, bool)

Fold is a number read from a Source in unit as the engine keeps it, as Normalize writes it (5 in mV is 0.005 in V), and whether that changed anything (jaala#205). A unit that doesn't parse is kept as it is, a unit of its own, so a Source's value is read and never refused. Cached per unit, and safe for concurrent use once the table is built.

func (*Units) FoldValue added in v0.1.59

func (t *Units) FoldValue(v Value) Value

FoldValue is v as the engine holds it once its number's unit is folded (Fold): NU(1000, "mV") is NU(1, "V"). A number whose text only spelled it spells the folded number; text saying more, such as "5 mV", is kept. Anything else, and every value under a nil table, comes back as it is. A store holding prefixed values folds its own with it to compare them with what the engine asks (#205).

func (*Units) Normalize added in v0.1.37

func (t *Units) Normalize(f float64, unit string) (float64, string, error)

Normalize is a number in a unit as the engine keeps it: the scale folded into the number, and the unit written by its name (5 in kohm is 5000 in ohm; 6 in A*ohm is 6 in V). A dimensionless unit leaves no symbol. An empty unit is the number as it is.

func (*Units) ParseUnit added in v0.1.37

func (t *Units) ParseUnit(s string) (Unit, error)

ParseUnit reads a unit as a query writes it: a symbol, a prefixed symbol (kohm, mV), or a product or quotient of them with powers (A*ohm, m/s^2, m/(K*s^2)), expanded through the table's definitions. An unknown symbol is a base unit of its own. A nil table knows no names or prefixes.

func (*Units) SameUnit added in v0.1.37

func (t *Units) SameUnit(a, b string) bool

SameUnit reports whether two units the engine holds are one unit, through the table's names (so ohm and V/A are). An empty unit is no unit.

func (*Units) Write added in v0.1.37

func (t *Units) Write(f float64, u Unit) (float64, string, error)

Write is a number in a unit as the engine keeps it, as Normalize returns it.

type Value

type Value struct {
	S   string
	Num *float64
	// Absent marks a field the source did not state AT ALL, which is different from an empty string
	// and different from zero. A datasheet row stating only a maximum leaves its minimum absent.
	//
	// It is a field rather than something inferred from a nil Num because the two are not the same
	// question: a non-numeric string also has a nil Num, and conflating them means the engine
	// RECONSTRUCTS absence from a coincidence instead of representing it. Before it was
	// representable, an absent field bound to the empty string and ordering fell through to string
	// order, where "" precedes everything and so "passed" every upper-bound test, including against a
	// negative threshold.
	Absent bool
	// BaseUnit is the unit this value's number is expressed in ("V", "A", UnitOhm, "mm"), or "" for a
	// dimensionless value or a non-numeric one.
	//
	// To the engine a unit is a tag: two numbers order, and aggregate together, only when their units
	// are the same text, and an empty unit takes whichever unit it meets (jaala#303). What a unit means
	// (that mV is a thousandth of a V) is the vocabulary's, through its unit table (Vocabulary.AddUnit):
	// a query's constants and num.*'s results are written through it, and a Source's values are read
	// through it only when the vocabulary folds a Source's units (Vocabulary.FoldSourceUnits). Then a
	// Source may serve a prefixed or compound unit ("mV", "kohm", "A*ohm") and the engine folds it as it
	// reads the value (Units.Fold, jaala#205), so 1000 in mV reads as 1 in V and equals, keys, groups
	// and orders with a 1 V the Source also serves, and a Source answering a lookup, a pushed
	// conjunction or a filter is asked by the folded value and has to answer by it. Otherwise the unit
	// is read as served: a host keeping lengths in mm writes a bare threshold in mm.
	//
	// Distinct from the `param.unit` RELATION, which reports what the vendor PRINTED ("mV") for a
	// human checking a citation. This says what the number IS in, for a machine comparing it.
	BaseUnit string
}

A Value is a scalar fact value. A fact carries a string and, when numeric, a number, so a bound term keeps both: string equality and numeric comparison both work with no re-parse.

func Absent

func Absent() Value

Absent is the value of an argument the source did not state at all.

func N

func N(f float64) Value

N builds a numeric value; its string form is the canonical rendering of the number.

func NU

func NU(f float64, unit string) Value

NU builds a numeric value carrying a base-unit tag.

func ParseList added in v0.1.79

func ParseList(s string) ([]Value, error)

ParseList reads a list's value back: a JSON string is text, a number a number, {"num", "unit"} a number in that unit, null absent. It refuses text ListText could not have written.

func S

func S(s string) Value

S builds a string value.

type Version added in v0.1.61

type Version uint32

A Version names one version of a TimedSource's facts, such as a revision of a design or a commit of a repo (#179). The host numbers its versions; the engine only compares and collects them. Linear history numbers them in order, so a fact that holds from one revision on is one range. History that branches numbers them however it likes and uses a BitSet.

const Open Version = math.MaxUint32

Open ends a range that still holds: [v, Open) is v and every version after it. It is never a version itself.

func VersionOf added in v0.1.61

func VersionOf(ctx context.Context) (Version, bool)

VersionOf is the version ctx carries (see WithVersion), and false when it carries none: the Eval reads the Source as a plain one.

type VersionRange added in v0.1.61

type VersionRange struct{ From, To Version }

A VersionRange is the versions from From up to, but not including, To. To is Open for a range that still holds.

type VersionSet added in v0.1.61

type VersionSet interface {
	// Contains reports whether v is in the set. It is false for Open.
	Contains(v Version) bool
	// Empty reports whether the set holds no version.
	Empty() bool
	// Ranges are the set's versions as ranges, ascending, none empty, and none touching the next: two
	// ranges that meet are reported as one.
	Ranges() iter.Seq[VersionRange]
	Intersect(o VersionSet) VersionSet
	Union(o VersionSet) VersionSet
	// Minus is the versions of the set that aren't in o.
	Minus(o VersionSet) VersionSet
}

A VersionSet is the versions a fact holds in. Two implementations come with ns, IntervalSet for linear history and BitSet for history that branches, and either combines with the other: an operation returns the receiver's kind, reading the other through Ranges.

type Versioned added in v0.1.23

type Versioned interface {
	Version() string
}

Versioned is optionally implemented by a Source whose facts can change while a Base over it is kept. A Base caches what it reads, the base relations and their indexes and the derived relations a query evaluated in full, on the promise that a Source's facts are fixed for the Base's life. Version lets a Source withdraw that promise: each Eval reads it once before reading anything else, and when it differs from the version the caches were built at, they are dropped and the relations read again, so Tuples may then be called again for a relation. Any string works, as long as it changes whenever the facts do. A Source that doesn't implement it is taken as fixed, and a host that changes one anyway calls the Base's Forget.

type Vocabulary

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

A Vocabulary is the namespace tree a query's names resolve in. Every callable name lives at a PATH, its segments separated by ".": `edge`, `str.contains`, `acme.power.rail_budget`. A path's last segment is a member; the segments before it name the module holding it, and the root module ("") holds the members with no prefix.

A member is one of three kinds: a base relation (a Schema, whose tuples a Source serves), a predicate (a Builtin the host computes), or a derived relation defined by a module written in a registered Language (see AddModule).

Two rules keep a path unambiguous, and the vocabulary enforces both when a member is added:

  • A segment is a module or a member, never both. `pin` beside `pin.net` is refused, because a reader of `pin.net(...)` could not tell a member of module `pin` from a relation named with a dot.
  • One definer per path. Registering a path twice is an error naming both definitions, whatever their kinds, so a host predicate cannot silently shadow a base relation or the reverse.

A Vocabulary holds names, never data. An engine pairs it with a Source per query (in jaala/datalog, NewBase(v, src)), so a host composes its vocabulary once, checks it at load, and binds each dataset as it reads it. It is not safe for concurrent registration, but once built it may be read by any number of engines and queries at once.

func MustVocabulary

func MustVocabulary(src Source) *Vocabulary

MustVocabulary is NewVocabulary for a Source known to be well formed, such as a test fixture. It panics on the error NewVocabulary would return.

func NewVocabulary

func NewVocabulary(src Source) (*Vocabulary, error)

NewVocabulary returns a vocabulary holding every relation src serves, each as a base relation at the path it is named by. src's relations and schemas are read once, here; its tuples never are. A nil src gives an empty vocabulary, which a host fills with AddRelation.

It fails when two of the Source's own names break the tree's rules, such as `pin` beside `pin.net`, because a query could not name both.

func (*Vocabulary) AddLanguage

func (v *Vocabulary) AddLanguage(l Language) error

AddLanguage makes a language available to AddModule. Registering a second language under one name is refused.

func (*Vocabulary) AddModule

func (v *Vocabulary) AddModule(path, lang, text, origin string) error

AddModule registers text written in lang at module path ("" for the root), recording origin as where it came from (see Module.Origin; "" for nothing). The language reports the public members the text defines, and each is entered at path.name under the tree's rules, exactly as a relation or predicate would be: a member colliding with another path, or breaking module-or-member, is refused here, and nothing is registered when anything is refused. Every refusal is a *ModuleError.

A language nobody registered is refused with its name. What a module's rules READ is not checked here, since what they read may be registered later; Check does that.

Several modules may register at one module path, provided each member path has one definer, which is how a host's standard library and a project's own definitions share a module.

func (*Vocabulary) AddModulesFS added in v0.1.8

func (v *Vocabulary) AddModulesFS(fsys fs.FS, root, lang string, layout Layout) error

AddModulesFS registers every module file under root in fsys, written in lang, at the module path layout gives it, one AddModule per file in lexical order, each with its file (root/file) as its origin. So a member knows the file defining it (Entry.Origin), and a refusal names the file (ModuleError.Origin).

It is all or nothing: if any file is refused, or a file's module path cannot be spelled, the vocabulary is left exactly as it was. Like AddModule, it does not check what the modules read; Check does, once everything is registered.

func (*Vocabulary) AddPredicate

func (v *Vocabulary) AddPredicate(path string, b Builtin) error

AddPredicate registers a computed predicate at path: a filter (Holds set) or a generator (Gen set), exactly one. It fails on a builtin that is neither or both, on a filter with arity below one, on a generator without Modes or with a mode of the wrong length, on Aliased set for a filter, of the wrong length or required by a mode, and on a path the tree's rules refuse (see Vocabulary).

func (*Vocabulary) AddRelation

func (v *Vocabulary) AddRelation(path string, s Schema) error

AddRelation registers a base relation at path with the given schema. Its tuples come from whichever Source a query is run over, asked for by the same path.

func (*Vocabulary) AddUnit added in v0.1.37

func (v *Vocabulary) AddUnit(name, def string) error

AddUnit names a unit or a prefix. def is "" for a base unit, a number for a prefix ("1e3" for k, "1e-3" for m, "1024" for Ki), or a unit expression over units already known, such as "A*ohm" or "V/A" or "m/s^2", which may carry a number as a factor: "60*s" for min, "1024*B" for KiB (jaala#303). A number is a positive decimal with an optional exponent, kept exact. A unit's first name is how answers write it: once V is A*ohm, a product of amps and ohms is written V. Later names for the same unit (Ω for ohm) are read but not written.

func (*Vocabulary) BaseRelations

func (v *Vocabulary) BaseRelations() []string

BaseRelations returns the base relation paths in registration order. A vocabulary with none cannot call a name unknown, because it cannot tell a typo from a vocabulary nobody installed yet, and an engine stands its unknown-name checks down until there are some.

func (*Vocabulary) Check

func (v *Vocabulary) Check() error

Check validates every module, by asking each language that has modules to check them, and keeps the members' signatures for Lookup and Signature. It runs once per state of the vocabulary and is shared by every engine and query over it; a host calls it at load to report a broken library before any query runs.

func (*Vocabulary) Clone

func (v *Vocabulary) Clone() *Vocabulary

Clone returns an independent copy, so a caller can register more without changing the vocabulary it copied. A test adding a predicate uses it to leave a shared vocabulary as it found it.

func (*Vocabulary) DefiningModule

func (v *Vocabulary) DefiningModule(path string) (int, bool)

DefiningModule returns the index, into Modules, of the module defining the derived relation at path.

func (*Vocabulary) FoldSourceUnits added in v0.1.60

func (v *Vocabulary) FoldSourceUnits()

FoldSourceUnits has the engine fold a Source's numbers through the unit table as it reads them (jaala#205; opt-in since jaala#303): served as 1000 in mV, a value reads as 1 in V and equals, keys, groups and orders with the 1 V a query or another Source writes. Without it, a Source's unit is a tag compared by its text, as a host serving lengths in mm wants: 0.08 in mm stays 0.08 in mm, and a bare 0.1 compares with it in mm. With it, the engine also asks a store by folded values, in a lookup, a pushed conjunction (Conjunction.Units) and a walk, and a Federation folds what it carries from one member to the next. Call it before the vocabulary is used.

func (*Vocabulary) FoldsSourceUnits added in v0.1.60

func (v *Vocabulary) FoldsSourceUnits() bool

FoldsSourceUnits reports whether FoldSourceUnits was called on v.

func (*Vocabulary) Has

func (v *Vocabulary) Has(path string) bool

Has reports whether a member of any kind is registered at path.

func (*Vocabulary) Hint

func (v *Vocabulary) Hint(name string) string

Hint is the text after the name in an unknown-name error: `; did you mean "X"?` when a registered name is a plausible typo, an explanation when no relation is registered at all, and "" otherwise.

A bare name is most often a member typed without its module (`rail` for `net.rail`), so a member elsewhere whose last segment IS the name comes first; when several do, they are all listed, since picking one would be a guess. Only then does a typo of a root name count, and only then a module path spelled with "_" or "-" for "." (`net_pin_count` for `net.pin_count`). Every case is a hint: the name still does not resolve.

When no base relation is registered it says that instead of guessing, because every name is unknown in that state and a typo hint would send the reader hunting a spelling mistake they did not make. A host that forgot to install its relations still runs; this is the one moment the omission is visible.

func (*Vocabulary) IsModule

func (v *Vocabulary) IsModule(path string) bool

IsModule reports whether anything is registered beneath path.

func (*Vocabulary) Lookup

func (v *Vocabulary) Lookup(path string) (Entry, error)

Lookup answers what is at path: a module (its members) or a member (its signature, kind, doc, and for a derived member its definition). "" is the root module. It runs Check first, since a derived member's signature is only known once every module has been resolved, and returns Check's error when the modules do not check. An unknown path is an error worded as the engine words it in a query, suggestion included.

func (*Vocabulary) Members

func (v *Vocabulary) Members(module string) ([]Entry, error)

Members lists what a module holds, one Entry per direct child, sorted by path. "" is the root.

func (*Vocabulary) Memo

func (v *Vocabulary) Memo(key any, build func() (any, error)) (any, error)

Memo returns build's result for key, computing it once per state of the vocabulary: any registration discards every memoized result. It is how an engine keeps work that depends only on the vocabulary (resolved modules, say) shared by every query over it. Concurrent callers of one key wait for a single computation. Use a key of an unexported type, as with context values, so engines cannot collide.

func (*Vocabulary) Modules

func (v *Vocabulary) Modules() []Module

Modules returns every registered module, in registration order. DefiningModule indexes into it.

func (*Vocabulary) Predicate

func (v *Vocabulary) Predicate(path string) (Builtin, bool)

Predicate returns the builtin registered at path.

func (*Vocabulary) Related added in v0.1.66

func (v *Vocabulary) Related(name string, arity int) []string

Related lists, for a name the vocabulary doesn't hold and nothing plausibly misspells, the members a caller might have meant instead (#336): those taking arity arguments (any, when arity is negative), relations before predicates, and among them first the ones whose path or doc shares a word with name, at most four. It reads only what was registered, never Check, so an engine may call it while resolving modules.

func (*Vocabulary) Schema

func (v *Vocabulary) Schema(path string) (Schema, bool)

Schema returns the schema of the base relation at path.

func (*Vocabulary) Signature

func (v *Vocabulary) Signature(path string) ([]ArgSig, bool)

Signature returns the full signature of the derived relation at path, declared or inferred, as its language's Check worked it out. It runs Check when it has not run, and reports false when the path is not a derived relation or the modules do not check.

func (*Vocabulary) Units added in v0.1.37

func (v *Vocabulary) Units() *Units

Units is the vocabulary's unit table, nil when it names none. A query's constants and num.*'s results are always written through it; a Source's values are read through it only after FoldSourceUnits.

func (*Vocabulary) Unknown

func (v *Vocabulary) Unknown(name string) string

Unknown describes a name the vocabulary does not hold, for an error that follows "query: ". It names what is missing and adds a hint, so the most common newcomer error, a mistyped or half-remembered name, is answered with the vocabulary at the moment it is needed:

unknown relation "egde"; did you mean "edge"?
unknown module "nett" in "nett.pin_count"; did you mean "net.pin_count"?
"str" is a module, not a relation; it holds contains, distance, glob, match, prefix, suffix
"pin" is a module, not a relation; it holds name, net; did you mean "component.pin"?

A missing module is named as such because "unknown relation" would send the reader hunting a typo in the last segment when the first one is wrong.

func (*Vocabulary) WriteBaseThrough added in v0.1.59

func (v *Vocabulary) WriteBaseThrough(base, unit string) error

WriteBaseThrough lets answers write the base unit base through unit, a unit defined with base to the first power: stdlib writes kg through V, so that once V is kg*m^2/(A*s^3) an electrical unit is still written in volts (V/m, not kg*m/(A*s^3)). A unit is spelled both with base and through unit, and the shorter is written, the one through unit on a tie. It changes no unit's value, only how one with no name of its own is written.

type Walk added in v0.1.48

type Walk struct {
	Relation string
	From, To int
	Bound    map[int]Value
	Start    []Value
	// Units is the table the engine folds a Source's values by, as a Conjunction's (#205), nil when the
	// vocabulary doesn't fold them (#303): a Federation folds by it a value one member reached before
	// walking it in another. Nil folds nothing.
	Units *Units
	// MaxDepth bounds the walk at that many steps from a start, 0 for no bound (#396): a graph.closure
	// or graph.paths with a max asks for no more than it reads. The store need return only the facts of
	// values reached in fewer than MaxDepth steps, and the engine takes a value reached in exactly
	// MaxDepth as unwalked, so it never files that value's facts as complete. A store that ignores it
	// walks further and returns more, which costs fetches, never answers.
	MaxDepth int
}

A Walk asks a WalkSource for the facts of Relation reached from Start: each fact whose value at From is a start value or the value at To of a fact reached, and whose values at Bound's positions are those constants.

type WalkSource added in v0.1.48

type WalkSource interface {
	// Walks reports whether the store walks rel from position from to position to, with the positions
	// in bound fixed to constants. The planner asks while planning, so it must be cheap and do no I/O,
	// and the answer must not change for the life of a Base.
	Walks(rel string, from, to int, bound []int) bool
	// Walk returns every fact of w.Relation matching w.Bound whose value at w.From is reached: one of
	// w.Start, or the value at w.To of a fact it returns. Values compare as Lookup's do, each read as
	// its argument's declared type. Like Lookup, it may return facts that don't match or aren't
	// reached, but must not leave out one that is: the engine treats what it returns for a reached
	// value as every fact the value has, and asks the store nothing more about it.
	//
	// Each fact is charged to the Eval's Budget as it arrives, and the engine may stop ranging early.
	// An error yielded stops the walk and fails the query. What a completed walk returned is kept as
	// lookups' results are (see LookupSource); a walk that stopped is not kept.
	Walk(ctx context.Context, w Walk) iter.Seq2[Tuple, error]
}

WalkSource is optionally implemented by a Source that follows a relation's facts from value to value itself, such as a database answering SQLite's WITH RECURSIVE (#239). A recursive rule that probes a relation with the values its own results produce, as walk(?a, ?c) :- walk(?a, ?b), next(?b, ?c) probes next by each ?b it derived, otherwise costs a call per round of its fixpoint, since a round's values aren't known before the last round's answer. The planned evaluator asks a WalkSource for every fact the walk will reach in one call instead, files them as the lookups the rounds would have made, and derives the relation from them as it would have, so an answer, its citations and its witnesses are the same.

Jump to

Keyboard shortcuts

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