Documentation
¶
Overview ¶
Package vm compiles ClassAd expressions to a linear instruction stream and interprets them against a scope, replacing per-query AST walks.
Parity with the tree-walking evaluator is the overriding requirement: the interpreter routes every value operation through the exported hooks in the classad package (ApplyBinaryOp/ApplyUnaryOp/ResolveRef/ShortCircuit) and delegates any node type it does not natively compile back to the evaluator via an EvalNode instruction. It therefore cannot diverge from classad.Eval by construction; the differential fuzz test enforces this.
Example (Script) ¶
Example_script builds and runs a ClassAd script: local bindings, a branch, and a result.
A script is the statement language over the same engine an expression compiles to -- it exists for the things that are awkward as one expression. There is no parser yet, so a script is built through this API rather than written down.
The binding rule is Python's. A bare name that has been bound is the local; anything else is an attribute. So `want = want` on the first line reads the ATTRIBUTE and binds the LOCAL, and every later mention of want is the local. A scoped reference (MY.want) always means the attribute.
must := func(src string) ast.Expr {
e, err := parser.ParseExpr(src)
if err != nil {
panic(err)
}
return e
}
// The effective memory request: whatever the ad asks for, with a default and a floor.
sp, err := NewScript().
Let("want", must("RequestMemory")).
If(must("want is undefined"),
func(s *Script) { s.Let("want", must("2048")) },
nil).
If(must("want < 512"),
func(s *Script) { s.Let("want", must("512")) },
nil).
Result(must("want")).
Compile()
if err != nil {
panic(err)
}
for _, src := range []string{
`[ RequestMemory = 4096 ]`,
`[ RequestMemory = 100 ]`,
`[ Other = 1 ]`,
} {
ad, perr := classad.Parse(src)
if perr != nil {
panic(perr)
}
fmt.Printf("%-26s %s\n", src, sp.Run(ad).String())
}
Output: [ RequestMemory = 4096 ] 4096 [ RequestMemory = 100 ] 512 [ Other = 1 ] 2048
Example (ScriptDelegatedLocals) ¶
Example_scriptDelegatedLocals shows what a delegated construct sees of a script's locals.
A select and a lazy built-in are evaluated by the tree-walking evaluator rather than compiled, and they run with the script's locals overlaid on the ad. So a bare bound name there is the local, exactly as it is in a compiled position such as a ternary -- and MY.x is still the attribute, which is how a script says it meant the ad, in either kind of position.
The ad below defines x as well, with a different value, so each line's answer says which one was read.
const ad = `[ x = 0; Cpus = 4; Nested = [ tier = "gold" ] ]`
scripts := map[string]string{
"ternary over the local": "x = Cpus + 1\nresult = x ? \"local\" : \"attribute\"\n",
"ternary over MY.x": "x = Cpus + 1\nresult = MY.x ? \"local\" : \"attribute\"\n",
"rebinding": "x = x + 1\nresult = x ? x : -1\n",
"select over a local": "n = Nested\nresult = n.tier\n",
"lazy built-in": "tag = \"job-\"\nresult = strcat(tag, Cpus)\n",
}
for _, name := range []string{
"ternary over the local", "ternary over MY.x", "rebinding",
"select over a local", "lazy built-in",
} {
sp, err := ParseScript(scripts[name])
if err != nil {
panic(err)
}
scope, perr := classad.Parse(ad)
if perr != nil {
panic(perr)
}
fmt.Printf("%-22s %s\n", name, sp.Run(scope))
}
// A list literal is the one shape that cannot read a local: its elements are evaluated on
// demand, in a scope captured when the list was built, which may be long after the script has
// finished. That is refused rather than quietly read from the ad.
_, err := ParseScript("x = Cpus\nresult = {x, 1}\n")
fmt.Println(err != nil)
Output: ternary over the local "local" ternary over MY.x "attribute" rebinding 1 select over a local "gold" lazy built-in "job-4" true
Example (ScriptFunction) ¶
A function names a rule the script applies more than once.
The body is function-scoped: a bare name in it is a parameter, a name the body binds, or an attribute of the ad. `requested` and `cap` are parameters, while `Optimistic` is neither -- so it is read from the ad, and a function with no parameters at all would still be a function of the ad.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
def fits(requested, cap):
if requested is undefined:
return Optimistic
return requested <= cap
result = fits(MY.RequestMemory, 8192) && fits(MY.RequestCpus, 16)
`)
if err != nil {
panic(err)
}
for _, src := range []string{
`[ RequestMemory = 4096; RequestCpus = 4 ]`,
`[ RequestMemory = 99999; RequestCpus = 4 ]`,
`[ RequestCpus = 4; Optimistic = true ]`,
`[ RequestCpus = 4 ]`,
} {
ad, perr := classad.Parse(src)
if perr != nil {
panic(perr)
}
fmt.Printf("%-44s %s\n", src, sp.Run(ad).String())
}
}
Output: [ RequestMemory = 4096; RequestCpus = 4 ] true [ RequestMemory = 99999; RequestCpus = 4 ] false [ RequestCpus = 4; Optimistic = true ] true [ RequestCpus = 4 ] undefined
Index ¶
- Constants
- Variables
- func CompareIntsPlane(op string, vals []int64, lit int64, n int, lo []uint64) bool
- func CompareRawPlane(op string, raw []byte, width int, unsigned bool, lit int64, n int, lo []uint64) bool
- func MaskWords(n int) int
- func MaxLive(rp *RegProgram) int
- func PopCountMasked(a, b []uint64) int
- func RawColumnUseful(width int, unsigned bool) bool
- func Run(p *Program, scope *classad.ClassAd) (result classad.Value)
- func RunLimited(p *Program, scope *classad.ClassAd, budget int) (result classad.Value, ok bool)
- func RunRegisters(rp *RegProgram, scope *classad.ClassAd) (result classad.Value)
- func RunRegistersLimited(rp *RegProgram, scope *classad.ClassAd, budget int) (result classad.Value, ok bool)
- func SelfRefs(expr ast.Expr) []string
- func SelfRefsSafe(expr ast.Expr) (refs []string, partialSafe bool)
- type AliasRef
- type ColumnSource
- type DictResolver
- type Fault
- type FaultCause
- type FaultClass
- type Instr
- type ListColumn
- type ListColumnSource
- type LocalCaptureError
- type Matcher
- func (m *Matcher) Eval(scope *classad.ClassAd) (result classad.Value)
- func (m *Matcher) EvalAliased(resolve func(alias int, name string) classad.Value, ...) (result classad.Value, ok bool)
- func (m *Matcher) EvalResolved(resolver func(name string, scope ast.AttributeScope) classad.Value) (result classad.Value)
- func (m *Matcher) Matches(scope *classad.ClassAd) bool
- type Opcode
- type OptPasses
- type Probe
- type ProbeGroup
- type Program
- type Query
- func (q *Query) AliasNative() bool
- func (q *Query) AliasRefs() []AliasRef
- func (q *Query) Aliased() bool
- func (q *Query) And(e ast.Expr) *Query
- func (q *Query) Conjuncts() []*Query
- func (q *Query) Eval(scope *classad.ClassAd) classad.Value
- func (q *Query) ExactProbes() (probes []Probe, exact bool)
- func (q *Query) Expr() ast.Expr
- func (q *Query) Folded() *Query
- func (q *Query) Hiding(hide func(name string) bool) *Query
- func (q *Query) Matcher() *Matcher
- func (q *Query) Matches(scope *classad.ClassAd) bool
- func (q *Query) Native() bool
- func (q *Query) ProbePlan() []ProbeGroup
- func (q *Query) Probes() []Probe
- func (q *Query) Program() *Program
- func (q *Query) ReadAttrs() []string
- func (q *Query) ReadPlan() ReadPlan
- func (q *Query) ReadsCurrentTime() bool
- func (q *Query) VecEval(src ColumnSource, n int, scratch *VecScratch) (*Vec, bool)
- type ReadPlan
- type RegInstr
- type RegOp
- type RegProgram
- type Script
- func (s *Script) Break() *Script
- func (s *Script) Compile() (*ScriptProgram, error)
- func (s *Script) Continue() *Script
- func (s *Script) For(name string, seq ast.Expr, body func(*Script)) *Script
- func (s *Script) Func(name string, params []string, body func(*Script)) *Script
- func (s *Script) If(cond ast.Expr, then, els func(*Script)) *Script
- func (s *Script) Let(name string, expr ast.Expr) *Script
- func (s *Script) Result(expr ast.Expr) *Script
- func (s *Script) Return(expr ast.Expr) *Script
- func (s *Script) While(cond ast.Expr, body func(*Script)) *Script
- type ScriptCallCaptureError
- type ScriptFunc
- type ScriptModule
- type ScriptProgram
- func (sp *ScriptProgram) Locals() []string
- func (sp *ScriptProgram) Program() *Program
- func (sp *ScriptProgram) RegProgram() *RegProgram
- func (sp *ScriptProgram) Run(scope *classad.ClassAd) classad.Value
- func (sp *ScriptProgram) RunLimited(scope *classad.ClassAd, budget int) (classad.Value, bool)
- func (sp *ScriptProgram) RunWithFault(scope *classad.ClassAd) (result classad.Value, ok bool, fault *Fault)
- func (sp *ScriptProgram) String() string
- func (sp *ScriptProgram) VecEval(src ColumnSource, n int, scratch *VecScratch) (*Vec, bool)
- type ScriptSyntaxError
- type Vec
- func (v *Vec) Cell(i int) (st uint8, num int64, str string)
- func (v *Vec) CopyElem(i int, src *Vec, j int) bool
- func (v *Vec) CountTrue(live []uint64) int
- func (v *Vec) Float(i int) float64
- func (v *Vec) IsTrue(i int) bool
- func (v *Vec) Len() int
- func (v *Vec) SetBool(i int, b bool)
- func (v Vec) SetInt(i int, x int64)
- func (v Vec) SetReal(i int, f float64)
- func (v *Vec) SetString(i int, s string)
- type VecScratch
Examples ¶
Constants ¶
const ( VsInt uint8 = iota // I[i] is the integer VsReal // I[i] is math.Float64bits of the real VsBool // I[i] is 0 or 1 VsUndef // UNDEFINED VsError // ERROR VsString // S[i] is the string VsDictCode // I[i] is a code into Vec.Dict: a dictionary-encoded STRING )
Element states. A vector carries one per element, which is how three-valued logic and ERROR survive vectorization, and how int and real stay distinguishable -- 7/2 is not 7.0/2.0.
const DefaultStepBudget = 1 << 22
DefaultStepBudget bounds how many CHARGED STEPS one execution may run. A step is a value operation; step.go says which instructions those are and why the line is drawn there.
A bound is not optional once a program can loop: `while true: x = x` has no answer, and the evaluator's contract is that evaluation returns. It is counted in work rather than in wall clock on purpose -- a time limit makes the same script succeed or fail depending on what else the machine is doing, which is not reproducible, and a fault nobody can reproduce cannot be debugged or differentially tested.
It used to count every instruction. The same number now permits somewhat more of them, because moves and jumps are no longer billed; that is a deliberate loosening, and the bound still holds because every loop iteration passes through a condition expression and so is charged at least one step (TestEveryLoopIterationIsCharged).
The value is large enough that no terminating script written by hand will reach it and small enough to stop a runaway quickly.
Variables ¶
var ErrNoFunctions = errors.New("vm: script module defines no functions")
ErrNoFunctions is returned by ParseScriptModule for source that defines nothing. An empty module is almost always a mistake about which entry point was meant to be built, and registering nothing silently is a start-up that looks successful and leaves every expression calling a name that does not exist.
var ErrNoResult = errors.New("vm: script has no result expression")
ErrNoResult is returned by Compile when the script has no result expression.
var ErrReadsAd = errors.New("vm: script function reaches the ad and cannot be registered")
ErrReadsAd is returned when a script function cannot be registered because it reaches the subject ad. See checkPure for what that covers and why each part of it is refused.
var ListFusedCalls atomic.Int64
ListFusedCalls counts calls served from a list column, so a test can see the path ran.
Functions ¶
func CompareIntsPlane ¶ added in v0.32.1
CompareIntsPlane writes one bit per record into lo from an already-widened column, with the bits past n left clear. It always answers for one of the six scalar comparisons.
This is the kernel the production build runs: without GOEXPERIMENT=simd there is no engine, so every width lands here. It is still a bitplane rather than a bool per record, and that is not only for the SIMD build's benefit -- assembling a word of results and intersecting it with one AND is fewer stores and fewer branches than writing and re-reading a byte per record, whatever compares them.
func CompareRawPlane ¶ added in v0.32.1
func CompareRawPlane(op string, raw []byte, width int, unsigned bool, lit int64, n int, lo []uint64) bool
CompareRawPlane writes one bit per record into lo: 1 where the column's STORED value satisfies op against lit, 0 otherwise, with the bits past n left clear.
ok=false when no engine on this build and this CPU has lanes for the column's width, or op is not one of the six scalar comparisons. The caller then widens the column itself and uses CompareIntsPlane -- which is why this does NOT fall back the way simdCompareRaw does: a caller holding a raw column has not necessarily widened it, and widening inside here would hide the cost of doing so.
func MaskWords ¶ added in v0.27.0
MaskWords returns the number of uint64 words a mask plane needs for n records. Exported so a caller that builds its own visibility mask sizes it the same way the executor does.
func MaxLive ¶ added in v0.35.0
func MaxLive(rp *RegProgram) int
MaxLive returns the greatest number of registers simultaneously live at any point, which is the quantity a vector register allocator minimizes: at 8192 records each one is about 200 KiB in data form, so this number times that is the program's peak working set.
It counts live-in sets, so a value defined and immediately consumed by the next instruction is not counted twice.
func PopCountMasked ¶ added in v0.27.0
PopCountMasked counts set bits of a & b, for a caller combining its own bitmaps.
func RawColumnUseful ¶ added in v0.27.0
RawColumnUseful reports whether handing a column of this width to the executor in its STORED form can pay off -- that is, whether an engine on this build and this CPU has lanes for it.
A source should gate on this rather than always supplying a raw column. Without an engine the raw form is not free: every non-comparison path has to widen it, and doing that measured 0.87x to 0.89x of a scan on the arithmetic shapes, where both operands widen. There is no point paying that for lanes nobody has.
func Run ¶
Run executes p against scope and returns the resulting Value. It produces the same value that classad evaluation of the source expression would: value operations are delegated to the classad evaluator hooks, and a cyclic reference resolves to an error value (as at the tree-walker's entry points).
Known limitation: for a self-referential cyclic lazy list (e.g. A = {a} where "a" case-folds to "A"), the value both engines produce is a list nested to the evaluator's depth limit terminating in an error element. The tree-walker folds the source expression's nesting depth into the list's captured depth, whereas this flat interpreter does not, so the two bottom out at slightly different nesting depths. Only such cyclic lists are affected; every non-cyclic expression is bit-identical to the tree-walker (enforced by FuzzDifferential).
func RunLimited ¶ added in v0.35.0
RunLimited is Run with an explicit step budget. ok=false means the budget ran out, in which case the value is ERROR.
The two are distinguishable because they are different kinds of thing: ERROR is an answer the program computed, while exhausting the budget means it did not finish.
func RunRegisters ¶ added in v0.34.1
func RunRegisters(rp *RegProgram, scope *classad.ClassAd) (result classad.Value)
RunRegisters executes rp against scope and returns the resulting Value.
It produces the same value Run produces for the Program rp was lowered from, which is the property FuzzRegisterParity exists to enforce. Every value operation goes through the same classad hooks the stack interpreter uses, so neither form has its own copy of any semantics.
func RunRegistersLimited ¶ added in v0.35.0
func RunRegistersLimited(rp *RegProgram, scope *classad.ClassAd, budget int) (result classad.Value, ok bool)
RunRegistersLimited is RunRegisters with an explicit step budget. ok=false means the budget ran out, in which case the value is ERROR.
The two are distinguishable because they are different kinds of thing: ERROR is an answer the script computed, while exhausting the budget means it did not finish. The design keeps that distinction for the vector case, where a runaway costs one record and a budget overrun abandons the whole batch; here the single record is the whole result, so both end the script and only the caller's report differs.
func SelfRefs ¶
SelfRefs returns the self-scoped attribute names expr reads from the ad it is evaluated against — unscoped or MY-scoped references, and the member of every `.`-path select — for the store to expand the transitive read set as it decodes attribute expressions. A nested record literal's members are walked too: an unscoped name inside one resolves against the enclosing ad when the record does not bind it.
func SelfRefsSafe ¶ added in v0.6.0
SelfRefsSafe is SelfRefs plus whether partial decode is sound for expr: partialSafe is false when expr calls eval(), whose referenced attributes cannot be determined statically, so a closure built from the static refs could miss one. A caller building a partial ad must fall back to a full decode when this is false.
Types ¶
type AliasRef ¶ added in v0.37.0
AliasRef is one qualified reference a compiled program makes to a join side: which side, by its index in the alias list the program was compiled with, and which attribute on it.
type ColumnSource ¶ added in v0.27.0
type ColumnSource interface {
LoadColumn(name string, scope ast.AttributeScope, dst *Vec) bool
}
ColumnSource supplies a batch of values for an attribute reference. The collections package implements it over a columnar block; anything that can produce n values per attribute can.
ok=false means the reference cannot be served as a vector -- a string column, or an attribute whose values are expressions -- and the evaluation declines as a whole.
PURITY, per batch: within one batch, two LoadColumn calls for the same (name, scope) must fill dst with equal contents, and the call must have no effect a later call can observe except through dst. An implementation may cache, since caching is not observable through this interface. A pass that deduplicates loads needs this, and blockVecSource satisfies it -- it reads a fixed block through a block cache and writes only dst. It is NOT sufficient on its own: see THE KERNEL CONTRACT above, because a deduplicated load is a SHARED vector and the kernels destroy what they are given.
type DictResolver ¶ added in v0.27.0
type DictResolver interface {
Range(lit string) (lo, hi int, ok bool)
At(code int) (string, bool)
Len() int
}
DictResolver resolves a dictionary-encoded string column for one block.
Range is what makes a comparison an integer test: because the dictionary is sorted by the evaluator's fold comparison, the entries that compare EQUAL to a literal are contiguous, so a match is `lo <= code < hi` and an ordering comparison is a test against one boundary. lo == hi means the literal is absent, and the caller can conclude that no record matches without reading a code.
type Fault ¶ added in v0.35.0
type Fault struct {
Class FaultClass
// Cause is what the condition held, which the class alone does not say.
Cause FaultCause
// Where names the construct, e.g. `if #2 condition`. It is a diagnostic string and not a
// structured position, because there are no positions until there is a parser.
Where string
}
Fault is what a faulted run reports.
func RunRegistersFault ¶ added in v0.35.0
func RunRegistersFault(rp *RegProgram, scope *classad.ClassAd, budget int) (result classad.Value, ok bool, fault *Fault)
RunRegistersFault is RunRegistersLimited plus the fault report: which construct stopped the script and why, or nil if none did.
It is a separate entry point rather than a wider return on the existing ones because the report is a diagnostic, and the two existing signatures are what every caller in the tree uses.
type FaultCause ¶ added in v0.38.0
type FaultCause uint8
FaultCause says what an unreadable condition actually held.
The class says a condition could not be read; the cause says what it held, and the three are different mistakes with different fixes. UNDEFINED is almost always a misspelled attribute or one the ad does not carry. ERROR is an expression that went wrong further down -- a string compared to a number, a division by zero. A value with no truthiness at all is a condition that was never boolean to begin with, like naming a string attribute where a comparison was meant. Reporting all three as "neither true nor false" is accurate and tells the author nothing they did not know.
const ( // CauseUnknown is the zero value: no fault, or a fault whose condition was not recorded. CauseUnknown FaultCause = iota // CauseUndefined is an UNDEFINED condition. CauseUndefined // CauseError is an ERROR condition. CauseError // CauseNotBoolean is a condition with no truthiness: a string, a list or an ad. Numbers are not // here -- ClassAd reads a number's truthiness, so `if 0` is false and faults nothing. CauseNotBoolean )
type FaultClass ¶ added in v0.35.0
type FaultClass uint8
FaultClass is why a fault happened. The numbering follows the design's F1..F4.
const ( // FaultNone is the zero value: no fault. FaultNone FaultClass = iota // FaultCondition (F1) is an if/while condition that is not boolean-equivalent: UNDEFINED, ERROR, // or a value no truthiness rule covers such as a string, list or ad. FaultCondition )
func (FaultClass) String ¶ added in v0.35.0
func (c FaultClass) String() string
String names the class for a diagnostic.
type Instr ¶
Instr is one instruction: an opcode and a single integer argument whose meaning depends on the opcode (a pool index or an absolute jump target).
type ListColumn ¶ added in v0.38.0
type ListColumn struct {
N int
// Present has bit k set when record k holds a list this column carries; a clear bit means the record
// lacks the attribute (UNDEFINED). A source must not serve a batch in which a record holds the
// attribute as anything else.
Present []byte
// Offs holds N+1 little-endian uint32 offsets: record k's elements are child[Offs[k]:Offs[k+1]].
Offs []byte
// Kind is the elements' kind: VsInt, VsReal, VsBool or VsString.
Kind uint8
// Fixed holds VsInt and VsReal elements, 8 bytes little-endian each (a real as math.Float64bits).
Fixed []byte
// Bits holds VsBool elements, one bit each.
Bits []byte
// Dict and Codes hold VsString elements: Codes is CodeWidth bytes little-endian per element, each an
// index into Dict.
Dict []string
Codes []byte
CodeWidth int
// Valid has bit i set when element i is defined; nil when every element is. An undefined element is
// the UNDEFINED literal in the list.
Valid []byte
// Except holds, by record, the value of the attribute for the records that hold it as something the
// column cannot carry -- a list mixing kinds, a scalar where the others hold lists -- evaluated alone,
// as the per-record path evaluates it. Their Present bit is clear and their offsets are flat. The
// call over such a record is computed by the reference.
Except map[int]classad.Value
// Other, when non-nil, has bit k set for each record in Except. For the source's use.
Other []byte
}
ListColumn is one batch of a list-valued attribute in the Arrow list layout: per record an offsets pair into one child array of every element of every record, back to back.
func (*ListColumn) Bounds ¶ added in v0.38.0
func (lc *ListColumn) Bounds(k int) (lo, hi int)
Bounds returns record k's element range in the child array.
func (*ListColumn) Elem ¶ added in v0.38.0
func (lc *ListColumn) Elem(i int) classad.Value
Elem returns element i as a value.
func (*ListColumn) Has ¶ added in v0.38.0
func (lc *ListColumn) Has(k int) bool
Has reports whether record k holds a list.
type ListColumnSource ¶ added in v0.38.0
type ListColumnSource interface {
LoadListColumn(name string, scope ast.AttributeScope) (*ListColumn, bool)
}
ListColumnSource is a ColumnSource that can also serve a list-valued attribute as a ListColumn. ok=false means it cannot for this batch, and the executor takes the ordinary path.
type LocalCaptureError ¶ added in v0.38.0
type LocalCaptureError struct {
Local string // the local the subtree reads, as the script spelled it
Expr string // the delegated subtree, unparsed
}
LocalCaptureError reports a script expression that reads a local from a position no overlay can reach: inside a list literal, an ad literal, or the first argument of countMatches or evalInEachContext, each of which is evaluated in an evaluator of its own. See compiler.delegate.
func (*LocalCaptureError) Error ¶ added in v0.38.0
func (e *LocalCaptureError) Error() string
type Matcher ¶
type Matcher struct {
// contains filtered or unexported fields
}
Matcher evaluates one compiled Query against many ads while reusing its evaluator and value stack, so a table scan pays the per-ad cost of the ClassAd evaluation itself but not a fresh evaluator + stack allocation per ad. It is semantically identical to calling Query.Eval / Query.Matches for each ad; it only removes allocations.
A Matcher holds mutable state (the reused evaluator and stack) and is NOT safe for concurrent use. A parallel scan should use one Matcher per goroutine.
func (*Matcher) Eval ¶
Eval evaluates the query against scope and returns the raw Value, reusing the Matcher's evaluator and stack. The result equals Query.Eval(scope); a cyclic reference resolves to an error value.
func (*Matcher) EvalAliased ¶ added in v0.36.0
func (m *Matcher) EvalAliased(resolve func(alias int, name string) classad.Value, refResolve func(name string, scope ast.AttributeScope) classad.Value) (result classad.Value, ok bool)
EvalAliased evaluates the query with resolve answering its qualified references, reusing the Matcher's evaluator and stack. resolve(alias, name) is given the alias's INDEX in the list the query was compiled with, and returns the attribute's value or undefined when that side does not define it -- which is also how an ABSENT side reads, as a LEFT JOIN's null-extended row needs.
Unqualified references are resolved through refResolve, or undefined when it is nil; a join condition over a joined row has none, but a WHERE conjunct may.
ok is false when the query is not AliasNative, and then NOTHING is evaluated: the caller must build the row and evaluate against it instead. That is a return value rather than a documented precondition, because the failure is otherwise invisible -- a delegated subtree evaluated against the nil scope this installs does not fail, it quietly reads undefined, and a condition that reads undefined does not error, it just stops matching. A join would silently return too few rows. Every caller must have a fallback, so every caller is made to say what it is.
func (*Matcher) EvalResolved ¶
func (m *Matcher) EvalResolved(resolver func(name string, scope ast.AttributeScope) classad.Value) (result classad.Value)
EvalResolved evaluates the query using a custom attribute resolver instead of a ClassAd scope, reusing the Matcher's evaluator and stack. resolver(name, scope) returns the value of an attribute reference; it lets the query run against an alternate backing (e.g. an encoded ad) with no ClassAd materialized.
The query must be Native. The result equals evaluating the same query against a ClassAd whose attributes return the same values; a cyclic reference resolves to an error value.
type Opcode ¶
type Opcode uint8
Opcode identifies an instruction. The program is a flat []Instr slice (a struct-of-op-and-arg IR); packing it to a dense byte stream is a future optimization that does not affect semantics.
const ( // OpPushConst pushes consts[A]. OpPushConst Opcode = iota // OpPushTrue/False/Undef/Error push the corresponding literal (no arg). OpPushTrue OpPushFalse OpPushUndef OpPushError // OpLoadRef resolves refs[A] (name+scope) in the scope and pushes the result. OpLoadRef // OpBinop pops right,left and pushes ApplyBinaryOp(ops[A], left, right). // Used for all non-short-circuiting binary operators. OpBinop // OpUnop pops v and pushes ApplyUnaryOp(ops[A], v). OpUnop // OpShortAnd/OpShortOr peek the left operand already on the stack. If it // short-circuits the logical operator, they replace it with the operator's // result and jump to A; otherwise they leave it on the stack and fall // through to the compiled right operand. OpShortAnd OpShortOr // OpCombineAnd/OpCombineOr pop right,left and push the combined logical value // (reached only when the right operand was evaluated). OpCombineAnd OpCombineOr // OpJmpIfNotUndef implements the Elvis operator: peek top; if it is NOT // undefined, jump to A leaving it on the stack (the result); otherwise pop it // and fall through to the compiled fallback expression. OpJmpIfNotUndef // OpStrListMember applies stringListMember over the constant list strLists[A] to the value on // top of the stack, replacing it with the result. // // Only the case-sensitive variant over a LITERAL list compiles this way; see strlist.go for why // stringListIMember does not. OpStrListMember // OpJmp jumps unconditionally to A. Emitted only by a conditional, to leave a taken branch. OpJmp // OpBranchCond pops the condition and dispatches on classad.ConditionState using the target // triple conds[A]: CondTrue falls through to the following instruction, and CondFalse, CondUndef // and CondError jump to onFalse, onUndef and onError. // // This is what makes ifThenElse native. It cannot be a call, however strict-looking: it // evaluates only the branch it selects, so an eager call would evaluate both -- and a branch is // allowed to be a cyclic self-reference that must never be reached. A branch, not a call, is also // why the UNDEFINED and ERROR cases get their own targets rather than a shared one: they produce // a value without evaluating either branch, which only control flow can express. // // Note it does NOT lower the ternary `c ? t : f`, whose semantics differ in exactly one place: an // UNDEFINED condition still evaluates BOTH branches, so no arrangement of four blocks that each // produce a value can serve it. The ternary has its own triple of opcodes, which share the two // arms between the three outcomes that reach them; see OpTernBranch. OpBranchCond // OpCallFunc calls funcs[A], a STRICT built-in: it pops the function's argc // argument values (arg0 deepest), applies classad.ApplyFunction to them and // pushes the result. // // Only built-ins that classad.StrictFunction accepts are compiled to this. // A lazy one (ifThenElse, strcat), one needing the scope or the raw AST // (eval, unparse, countMatches, evalInEachContext), a nondeterministic one // (random, time, formatTime), an unknown name and a wrong argument count all // stay OpEvalNode -- see StrictFunction's comment for why each must. // // The point of compiling a call natively is not call speed. It is that a // program containing one stays Native(), and Native() is what the columnar // accelerators gate on: with the call delegated, a single substr() or // regexp() in a constraint takes the whole query off the index probes, the // column prefilter and the vector executor and onto the per-record path. OpCallFunc // OpEvalNode delegates nodes[A] (an ast.Expr subtree) to the tree-walking // evaluator and pushes its value. The escape hatch for node types the // compiler does not lower to native instructions. OpEvalNode // OpMember replaces the top of the stack (member's or identicalMember's // first argument) with the call's value against members[A], a list of // constants compiled to sets. See member.go. OpMember // OpLoadLocal pushes the value bound to locals[A] by an earlier statement of a script. // // A script's locals are NOT attributes: `x = Cpus + 1` binds a name that later statements read // without the scope ever seeing it, so a reference to x must not compile to OpLoadRef and must // not be shadowed by -- or shadow -- an attribute of the same name. The compiler decides which // a reference is, because only the compiler knows what is bound at that point. // // It appears only in a script program, and the register lowering resolves it to the local's // register, so it never reaches a running program in stack form. The stack interpreter therefore // does not implement it; see ScriptProgram. OpLoadLocal // OpStoreLocal pops the top of the stack and binds it to locals[A]. // // A local is a PLACE, not a value: it has one register for the whole script, written here and // read by OpLoadLocal. That is what lets a binding made on one path of a branch and read after // the merge be the same register either way, with no phi to construct -- which a model that gave // each binding a fresh register could not express, and is why that model was replaced. // // Popping is what makes a statement stack-neutral, so the next one starts clean. OpStoreLocal // OpBranchVoid pops the condition and dispatches on classad.ConditionState using conds[A], like // OpBranchCond -- but it produces NO value and has no join. // // The two cannot be the same opcode. OpBranchCond is an expression: each of its paths leaves a // value and they converge on one register. A statement branch's paths leave nothing, and what // converges is the LOCALS they wrote, each of which is already a single register. There is // nothing to join, and a lowering that tried to would be looking for values that are not there. OpBranchVoid // OpJmpVoid jumps unconditionally to A, carrying no value. OpJmp is its expression counterpart // and moves the path's value into the conditional's destination first. OpJmpVoid // OpFault ends the script with ERROR. // // It is reached when a condition is neither true nor false -- UNDEFINED, or a type that cannot // be one, such as a string or a list. That is a FAULT rather than a branch not taken, because // the alternative is to treat "I could not tell" as "no", which is how a misspelled attribute // silently turns a script into one that does nothing. // // In the scalar context a fault ends the script, which is the degenerate case of faulting the // one record being evaluated. OpFault // OpLoadAlias resolves aliasRefs[A] -- a QUALIFIED reference `alias.Attr`, where alias // names one side of a join -- through the evaluator's alias resolver, and pushes the // result. With no alias resolver installed it evaluates the original select expression // against the scope instead, which is what the reference compiled to before this opcode // existed; so a program carrying one is correct either way and the opcode is purely an // optimization of the case where the sides are not in one record. OpLoadAlias // OpShortSubscript peeks the container already on the stack. If it is UNDEFINED or ERROR it // jumps to A, leaving the container in place as the subscript's value; otherwise it falls // through to the compiled index expression and the OpSubscript that follows. // // THE JUMP IS WHY THIS OPCODE EXISTS, and it is not an optimization. An undefined or error // container settles the result whatever the index is, so an eager form would compute the same // value -- but the tree-walking evaluator does not evaluate the index at all in that case, and // evaluating an expression can PANIC on a cyclic reference, which the interpreter turns into // ERROR for the whole program. So `Missing[Cyc]`, with Cyc self-referential, is UNDEFINED when // the index is skipped and ERROR when it is not. Skipping it is the only lowering that agrees // with classad.Eval. // // Leaving the container in place needs no write: the result for an undefined container IS // undefined, and for an error container IS error. OpShortSubscript // OpSubscript pops index,container and pushes ApplySubscript(container, index) -- the element // of a list at an integer index, the attribute of an ad at a string key, and ERROR for every // other shape, exactly as the evaluator's subscript does. It is reached only by falling through // OpShortSubscript, so the container is neither UNDEFINED nor ERROR. // // Compiling a subscript rather than delegating it is what lets a SCRIPT index one of its own // locals: a delegated subtree is evaluated against the ad, which has never heard of a local, // so `x = SomeList` followed by `x[0]` is refused when the subscript is delegated. It is also // what `for` desugars onto, and what lets a registered script function contain one. OpSubscript // OpTernBranch opens the ternary `c ? t : f`. The condition is already on the stack and STAYS // there for the whole construct, because all three of these instructions dispatch on it; // conds[A] holds where the false arm begins (onFalse), where the true arm ends (trueEnd) and // where the construct converges (end). // // CondTrue, CondUndef fall through to the true arm // CondFalse jump to onFalse, the false arm // anything else replace the condition with ERROR and jump to end // // TRUE AND UNDEFINED SHARE THE FALL-THROUGH, which is the whole difference from OpBranchCond. // An undefined condition yields UNDEFINED, but the reference engine evaluates BOTH arms first // and discards their values, so the arms are reached on three of the four outcomes rather than // one. Running them is observable even though their values are not: an error VALUE in an arm is // absorbed, while a cyclic self-reference is a hard failure that propagates. So // `undefined ? 1 : error` is UNDEFINED and `undefined ? {} : A0` -- A0 being the attribute // being evaluated -- is ERROR, and only an engine that evaluates the arms can tell them apart. // // A non-coercible condition (a string, a list, an ad, an error) is ERROR and evaluates NEITHER // arm, which is why it leaves by a jump rather than through the arms. OpTernBranch // OpTernTrue closes the ternary's true arm, with the arm's value on top of the stack and the // condition beneath it. conds[A] is the construct's target triple, as for OpTernBranch. // // CondTrue the arm's value IS the result: drop the condition under it and jump to end // CondUndef discard the arm's value and fall through into the false arm, which runs next // // No other state reaches it, because OpTernBranch sent them elsewhere. OpTernTrue // OpTernFalse closes the ternary's false arm and produces the result: it pops the arm's value // and the condition and pushes the arm's value for a false condition, or UNDEFINED for an // undefined one, both arms having run by then. // // EACH ARM IS EMITTED ONCE, which is what this triple buys over a branch with one block per // outcome. The undefined outcome needs both arms, so a four-block lowering would have to emit // each arm a second time, and a ternary nested in a ternary would double again -- while a chain // of ternaries is how ClassAd spells a lookup table. Here the undefined outcome walks the same // two blocks the true and false outcomes walk, and the construct's size is the sum of its parts. OpTernFalse // OpMakeList pops A values (element 0 deepest) and pushes the list holding them. // // IT IS EAGER, AND EVERY OTHER LIST IN THIS LANGUAGE IS LAZY. A list literal evaluated against an // ad keeps its element EXPRESSIONS and the scope to evaluate them in, which is observable in // exactly one place: string coercion unparses the source, so `string({1, 2+3})` is "{ 1,2 + 3 }" // and not "{ 1,5 }". Every other built-in that consumes a list -- size, sum, avg, min, max, join, // member, a subscript, a select -- materializes the elements first and cannot tell the two apart. // // So this opcode is emitted ONLY where there is no ad: a module function compiled for // registration (see compiler.noAd). There the lazy form is not merely equivalent, it is // unreachable -- a list literal in such a function is a delegated subtree, which checkPure // refuses outright, and its elements could not read a parameter even if it did not. Emitting it // in a script would change what `string({1, 2+3})` means, which is why the gate is not a // preference. // // The element count is the instruction's argument rather than a pool index, which is the one // place in this instruction set where A is a literal number. OpMakeList )
type OptPasses ¶ added in v0.35.0
type OptPasses struct {
// CopyProp replaces reads of a copied register with the original and removes the copy.
CopyProp bool
// DeadCode removes instructions whose destination is never read, where removing them is
// provably unobservable. See removable.
DeadCode bool
}
OptPasses selects which passes run. The zero value runs none, which is the unoptimized program and the oracle every pass is checked against.
type Probe ¶
type Probe struct {
Attr string
Op string
Vals []classad.Value
// Path is the components of a NESTED attribute path (`Res.Mem` -> {"Res","Mem"}), and is
// nil for a plain attribute. Attr is then the components joined with ".", which is how the
// query spells it and how an index on it is configured.
//
// It is a separate field rather than something a consumer could read off Attr because the
// two are not the same constraint: an ad may carry an attribute literally NAMED "Res.Mem"
// (nothing stops a writer setting one), and answering a path probe from that attribute's
// postings -- or the reverse -- would hand back a candidate set missing records that match.
// A consumer that cannot resolve a path must therefore decline on Nested() rather than fall
// through to its flat lookup, which costs selectivity and never correctness.
Path []string
}
Probe is an index-satisfiable constraint extracted from a query: a self-scoped attribute -- or a self-scoped nested path, `Res.Mem` (see Path) -- named by Attr and related by Op to one or more literal values. Op is one of "==","!=","<","<=",">=",">" (a single Val), "!<","!<=","!>","!>=" (a NEGATED ordering comparison, which is not the flipped one -- see negOrdering), "in" (a set of Vals: the attribute is == to one of them, from an OR-of-equalities or a member() call over a constant list), "is"/"isnt" (=?=/=!= exact identity), "prefix" (the attribute's string value begins with the single Val, from an anchored regexp -- see regexpPrefixProbe), or "present"/"absent" (is/isnt undefined). A store matches Probes against its configured indexes to build a candidate set; because the store still re-verifies the full query, any Probe the planner omits only costs selectivity, never correctness.
A query that reads CurrentTime has its probes computed with CurrentTime folded to the query's pinned time (see Compile), so `CompletionDate > CurrentTime - 86400` yields a range probe. Those probes describe only the ads that do not define CurrentTime; HTCondor does not store it in job or history ads. ExactProbes reports such a query as inexact, since a count computed from the probes alone would be wrong for an ad that does.
func ProbeOf ¶ added in v0.6.0
ProbeOf returns the index probe a single (already slot-rewritten) expression yields, or ok=false if it is not a recognizable Attr-OP-literal / presence / OR-of-equalities. Callers use it to tell an already-probeable leaf from an opaque one (e.g. before finite-domain materialization).
It carries no join aliases, so `a.b` reads as a select into a nested record. The expression a caller hands it is one leaf of a predicate already rewritten into a single ad's frame, where that is what a select means.
type ProbeGroup ¶ added in v0.6.0
type ProbeGroup struct {
Probes []Probe
}
ProbeGroup is a conjunction of index probes -- a candidate matches the group when it satisfies ALL of them. An empty Probes means the group is unconstrained (that disjunct can match anything), so a plan containing one cannot prune.
type Program ¶
type Program struct {
// contains filtered or unexported fields
}
Program is a compiled expression: a flat instruction stream plus the constant pools its instructions index into.
func CompileProgram ¶
CompileProgram lowers a ClassAd expression to a Program. Node types with subtle scope/laziness semantics (list, record, select) are emitted as OpEvalNode and delegated to the tree-walking evaluator at run time; the rest are native instructions.
A function call is native when classad.StrictFunction accepts it -- the built-in is a pure function of its argument values -- and delegated otherwise. That split is what keeps a program containing substr() or regexp() Native(), and so keeps it eligible for the columnar accelerators. member/identicalMember over a list of constants is compiled to its own specialized OpMember, which is preferred over the generic call when it applies.
type Query ¶
type Query struct {
// contains filtered or unexported fields
}
Query is a compiled boolean constraint over ads (a compiled Program plus the convenience of a match predicate). The store uses ReadAttrs for planning.
func Compile ¶
Compile compiles an already-parsed expression into a Query.
When the expression references CurrentTime, Compile reads the clock once and pins it: a CurrentTime the ad does not define evaluates to that time on every evaluation, so the program and its index probes share a single "now" instead of the program re-reading the clock per ad. An ad that defines CurrentTime supplies its own value, as it does to the evaluator; the expression itself is compiled unchanged.
func CompileAliases ¶ added in v0.36.0
CompileAliases compiles expr with aliases known to name the sides of a join, so a qualified reference `alias.Attr` to one of them compiles to a native load rather than a delegated select. The result is evaluated with Matcher.EvalAliased; evaluated any other way it behaves exactly as the same expression compiled with Compile.
An alias the expression does not use costs nothing, and a qualified reference naming something that is NOT in aliases is left delegated -- it may be a genuine select over a nested record, which only the scope can answer.
func ParseAliases ¶ added in v0.36.0
ParseAliases is CompileAliases on expression text.
func (*Query) AliasNative ¶ added in v0.36.0
AliasNative reports whether the query compiled entirely to native instructions, counting OpLoadAlias as native. It is the EvalAliased counterpart of Native: a query with qualified references is not Native (EvalResolved has no way to answer them), but it is AliasNative, and only an AliasNative query can be evaluated with EvalAliased.
func (*Query) AliasRefs ¶ added in v0.37.0
AliasRefs lists the qualified references the program makes, as written and with duplicates, in compilation order.
It is only an ANSWER for an AliasNative program, and a caller must check that first. A delegated node holds an arbitrary expression evaluated against the whole scope, which can reach a side in ways no list of attribute names describes -- `h` passed to a function, a select through a nested record, a reference the compiler never saw because the subtree was handed over whole. So a caller deciding what to READ from a side must treat a program that is not AliasNative as needing the entire ad, not as making the references it happens to list here.
func (*Query) Aliased ¶ added in v0.36.0
Aliased reports whether the query carries qualified references, i.e. whether EvalAliased would resolve anything that Eval would have to select.
func (*Query) And ¶ added in v0.32.1
And returns the query `(q) && (e)`, compiled with q's pinned time, so a CurrentTime both read means the same instant. A caller that refines a query it has already run -- a top-K pass that adds the cutoff it computed -- needs that: recompiling from text would pin a later time and could select a different set.
func (*Query) Conjuncts ¶ added in v0.33.3
Conjuncts returns one query per top-level `&&` conjunct of q (parentheses unwrapped), each compiled as `(conjunct) && true` with q's pinned time. It is nil when q has fewer than two.
They exist to REJECT, never to accept. A ClassAd `&&` is TRUE only when both of its operands are logically true -- the boolean true, or a nonzero number -- so q cannot match an ad on which any one conjunct is not. The trailing `&& true` is what makes that test exact: it maps the conjunct through the operator's own truth table, so a conjunct query matches precisely when the conjunct is logically true, and isTrueValue need not reimplement the operator. Evaluating a conjunct on its own gives the value it has inside q, since evaluation has no side effects and the pinned time is shared.
func (*Query) ExactProbes ¶ added in v0.27.0
ExactProbes returns the query's probes together with whether they are EXACTLY equivalent to the query: the top-level expression is a conjunction and EVERY conjunct was recognized as a probe.
Probes and ProbePlan are deliberate OVER-APPROXIMATIONS, built for index pruning where the store re-verifies every candidate, so an omitted conjunct only costs selectivity. A consumer that answers from the probes ALONE -- a columnar COUNT/MIN/MAX that never re-verifies -- needs the opposite guarantee, and using Probes for that silently over-counts: `ProcId >= 5 && ClusterId != ProcId` compiles natively and yields ONE probe, because an attribute-to-attribute comparison is not `Attr OP literal`, so counting from that probe alone answers `ProcId >= 5` instead of the query.
exact=false means "do not answer from these probes"; they remain a sound candidate filter.
func (*Query) Expr ¶ added in v0.6.0
Expr returns the source expression the query was compiled from (nil if empty).
func (*Query) Folded ¶ added in v0.32.1
Folded returns the query with its unscoped and MY CurrentTime references folded to the pinned time and its constants folded (classad.FoldConstantsAt), compiled as a query of its own. It is nil when the query does not read CurrentTime that way, or when the fold leaves such a reference behind.
The folded query evaluates exactly as q does on an ad that does not define CurrentTime (neither it nor a chained parent), at the same pinned time: that is FoldConstantsAt's contract. On an ad that defines CurrentTime it may not. So a store may evaluate it, and answer from its probes (ExactProbes), only over records it has proven lack the attribute; everywhere else it must evaluate q. Any CurrentTime reference the fold keeps (TARGET, PARENT, a select) is pinned to the same time as in q.
func (*Query) Hiding ¶ added in v0.35.0
Hiding returns q with every reference to an attribute hide reports replaced by the literal undefined, compiled with q's pinned time, or q itself when it references none.
It is how a store serves a reader that may not see some attributes WHATEVER form their values are stored in. Such a reader evaluates a sealed value as undefined, because it holds no key; a value of the same attribute written in the clear, before the attribute was sealed, has to read the same way, and the planner must not be able to tell the two apart either. Replacing the reference before planning does both at once: zone maps, indexes and column tiers never see the attribute, so none of them can prune, match or count on a value the reader is not entitled to, and the per-record evaluation reads undefined exactly where a sealed value would have.
A reference and the literal agree in every context: an attribute whose value is undefined and an absent one both evaluate to undefined, under every operator and function, and `is`/`isnt` compare that value. Every scope is replaced, TARGET included -- a collection ad has no target, so a TARGET reference is undefined already. A reference inside a record literal that defines the same name refers to the record's own attribute and is left alone. A name computed at run time (eval of a non-constant) is not visible here; the store resolves those through the same rule at evaluation.
func (*Query) Matcher ¶
Matcher returns a reusable Matcher for the query. Create one per scanning goroutine.
func (*Query) Matches ¶
Matches reports whether the query evaluates to boolean true against scope. Undefined, error, and non-boolean results are treated as non-matches, matching how a ClassAd requirement/constraint is applied.
func (*Query) Native ¶
Native reports whether the query compiled entirely to native instructions, with no delegated (OpEvalNode) subtrees. Only native queries can be evaluated with EvalResolved, because a delegated subtree needs a real ClassAd scope for its function/select/list semantics.
A query carrying QUALIFIED references (CompileAliases) is not Native however it compiled: EvalResolved's resolver is given a name and a scope, and has no way to say which side of a join a name belongs to. Those are evaluated with EvalAliased instead, which AliasNative gates.
func (*Query) ProbePlan ¶ added in v0.6.0
func (q *Query) ProbePlan() []ProbeGroup
ProbePlan describes the query's index-satisfiable structure as a disjunction of conjunctive groups (DNF over the top-level `||` spine): a candidate satisfies the plan when it satisfies every probe of ANY group. A purely conjunctive query is a single group -- identical to Probes(). A disjunctive query like `(A && B) || C` yields one group per disjunct, which the planner executes as a union of intersections. Because each group is an over-approximation of its disjunct and the store re-verifies, the union is a sound candidate superset; a group with no probes makes the plan un-prunable (the caller then full-scans).
The result is computed once and shared by every caller, which must not modify it.
func (*Query) Probes ¶
Probes extracts the query's index-satisfiable conjuncts. It constant-folds the source expression (so `Memory > 2048*1024` normalizes), then flattens the top-level && spine and classifies each conjunct, pushing `!` into comparisons where that is identity under ClassAd three-valued logic. Conjuncts that are not a recognizable `Attr OP literal` (or OR-of-equalities on one attr) are omitted. The result is memoized and SHARED: callers read it, none may modify it.
func (*Query) ReadAttrs ¶
ReadAttrs returns the distinct unscoped attribute names the query may read.
func (*Query) ReadsCurrentTime ¶ added in v0.32.0
ReadsCurrentTime reports whether the query reads the magic CurrentTime attribute unscoped or as MY.CurrentTime, so its probes assume the ads do not define CurrentTime (see Probe). TARGET.CurrentTime and a select of CurrentTime are pinned but not folded.
func (*Query) VecEval ¶ added in v0.27.0
func (q *Query) VecEval(src ColumnSource, n int, scratch *VecScratch) (*Vec, bool)
VecEval executes the query over a batch of n records and returns the result vector. A record matches a constraint when its element is VsBool with I == 1; see Vec.IsTrue.
ok=false when the program uses something this executor does not implement. It never returns a partial answer.
type ReadPlan ¶
type ReadPlan struct {
// Seeds are the distinct attribute names the query reads directly from the
// current ad — unscoped and MY-scoped references (TARGET references read the
// match target, which is absent during a collection scan), plus the member of
// every `.`-path select, which resolves against this ad whenever the selected
// record does not define it. Resolving these may pull in further attributes they
// reference; the store expands the set transitively while decoding.
Seeds []string
// PartialSafe is true when the query contains no construct that reads an
// attribute whose name is not statically visible — specifically eval(), which
// parses a runtime string into an arbitrary expression. When false, a partial
// decode could miss an attribute, so the store must fully decode the ad.
PartialSafe bool
}
ReadPlan describes what a query reads from an ad, so a store can evaluate the query against a partially-decoded ad (only the needed attributes) instead of decoding every attribute of every ad.
type RegInstr ¶ added in v0.34.1
RegInstr is one register-form instruction. Dst, A and B are register numbers; Imm is an index into one of the source Program's pools; Args indexes RegProgram.args; T is an absolute instruction index. Which fields are meaningful depends on Op.
type RegOp ¶ added in v0.34.1
type RegOp uint8
RegOp identifies a register-form instruction.
Every entry corresponds to exactly one stack Opcode, except RMove (which has no stack counterpart because the stack form expresses a join by leaving a value in place) and RNop.
const ( // RNop does nothing. Emitted only as a jump landing pad at the end of a program. RNop RegOp = iota // RConst sets Dst to src.consts[Imm]; RTrue/RFalse/RUndef/RError to the corresponding literal. RConst RTrue RFalse RUndef RError // RLoadRef resolves src.refs[Imm] and sets Dst to the result. RLoadRef // RBinop sets Dst to ApplyBinaryOp(src.ops[Imm], A, B). RUnop sets Dst to // ApplyUnaryOp(src.ops[Imm], A). RBinop RUnop // RCombineAnd/RCombineOr set Dst to ApplyBinaryOp("&&"/"||", A, B) for a logical operator whose // right operand was evaluated. // // The operator is in the opcode rather than in a pool index, exactly as it is in the stack form // (OpCombineAnd/OpCombineOr carry no argument). That is not only symmetry: a pool index would // have to be manufactured here, and appending one to the source Program's operator pool would // mutate a structure that program.go documents as read-only after compilation so that one // Program can be evaluated concurrently. RCombineAnd RCombineOr // RCallFunc sets Dst to ApplyFunction(src.funcs[Imm], args) where args are the registers listed // in RegProgram.args[Args]. // // The arguments are an explicit list rather than a contiguous register window. The window is // what a register ALLOCATOR should produce -- callFuncVec's convention depends on it -- but // requiring it of the IR before any allocator exists would mean inserting moves here to // manufacture adjacency that nothing yet benefits from. RCallFunc // RMember sets Dst to src.members[Imm].eval(A). RMember // RStrListMember sets Dst to src.strLists[Imm].eval(A). RStrListMember // REvalNode sets Dst to the tree-walking evaluation of src.nodes[Imm]. REvalNode // RMove sets Dst to A. Emitted at an Elvis join, and by nothing else. RMove // RShortAnd/RShortOr are the short-circuit half of a logical operator: if ShortCircuit settles // the operator from A alone, they set Dst to that result and jump to T; otherwise they fall // through to the right operand's code, which ends in the matching combine writing the same Dst. RShortAnd RShortOr // RJump jumps unconditionally to T. RJump // RFault ends execution with ERROR. See OpFault. RFault // RBranchCond dispatches on classad.ConditionState(A) using the register-form target triple // RegProgram.conds[Imm]: CondTrue falls through, the rest jump. Dst is the register every path of // the conditional writes, so the value is in one place at the join whichever path ran. RBranchCond // RJmpIfDefined is the Elvis test: if A is not UNDEFINED it sets Dst to A and jumps to T; // otherwise it falls through to the fallback, which ends in an RMove into the same Dst. RJmpIfDefined // RShortSubscript is the subscript's container test: if A is UNDEFINED or ERROR it sets Dst to // A and jumps to T; otherwise it falls through to the index's code, which ends in an RSubscript // writing the same Dst. See OpShortSubscript for why the index must be skipped. // // Unlike the Elvis join, the fall-through needs no RMove: RSubscript computes straight into Dst. RShortSubscript // RSubscript sets Dst to ApplySubscript(A, B) -- the container indexed by the index. RSubscript // RTernBranch, RTernTrue and RTernFalse are the ternary, one for one with the stack form's // OpTernBranch/OpTernTrue/OpTernFalse. A holds the condition in all three; B holds the arm's // value in the two that close an arm; T is the construct's join. All three write the same Dst, // which is what the ternary needs instead of a join move: the register form's phi is resolved by // construction here as it is for a logical operator, except that there are three writers rather // than two and no path that leaves the value where it already was. // // RTernBranch uses RegProgram.conds[Imm] for the false arm's start. The other two need no target // table: RTernTrue's only jump is to the join, and RTernFalse falls through to it. RTernBranch RTernTrue RTernFalse // RMakeList sets Dst to the list holding the values in the registers listed by args[Args], in // element order. The register-form twin of OpMakeList, and eager for the reason stated there. RMakeList )
type RegProgram ¶ added in v0.34.1
type RegProgram struct {
// contains filtered or unexported fields
}
RegProgram is a compiled expression in register form.
It owns no pools. src is the stack-form Program every pool index refers to, which is what keeps the two forms from being able to disagree about what a constant or an operator is.
func LowerToRegisters ¶ added in v0.34.1
func LowerToRegisters(p *Program) *RegProgram
LowerToRegisters converts a compiled expression from stack form to register form.
It accepts every Program compile.go can produce, including one delegated wholesale to the evaluator, and it never fails on valid input: the stack form is well-formed by construction (the compiler emits balanced pushes and pops, and jumps only within the two patterns above), so there is no expression for which this can get stuck.
It panics rather than degrades on input that cannot occur -- a stack underflow, a combine with no matching short-circuit, or an opcode it has not been taught. Each is a compiler bug, and each would otherwise produce a register program that quietly disagrees with the stack one. The last is the one that will actually happen: adding an opcode without extending this conversion. LowerToRegisters converts a compiled expression -- or a script -- from stack form to register form.
A SCRIPT's locals get one register each, allocated before any code and initialized to UNDEFINED. That is what makes a local a place rather than a value: OpStoreLocal writes the register and OpLoadLocal reads it, so a binding made on one path of a branch and read after the merge is the same register either way, and no phi has to be constructed to say so.
Initializing them matters for the same reason. A local read on a path that never bound it would otherwise read a register nothing wrote; UNDEFINED is the answer ClassAd already has for "no value here", and it keeps the register defined on every path, which the optimizer's liveness depends on.
func Optimize ¶ added in v0.35.0
func Optimize(rp *RegProgram, passes OptPasses) *RegProgram
Optimize returns an optimized copy of rp. rp is not modified, so the unoptimized program stays available as the oracle for the optimized one.
func (*RegProgram) Len ¶ added in v0.34.1
func (rp *RegProgram) Len() int
Len returns the instruction count (for tests and benchmarks).
func (*RegProgram) NumRegs ¶ added in v0.34.1
func (rp *RegProgram) NumRegs() int
NumRegs returns how many virtual registers the program defines.
Each definition gets a fresh register: there is no reuse, so this is also the number of definitions and, for now, the peak live count. Making it smaller is the register allocator's job and is deliberately not done here -- an unoptimized form that is obviously correct is what the optimizer gets validated against.
func (*RegProgram) Source ¶ added in v0.34.1
func (rp *RegProgram) Source() *Program
Source returns the stack-form Program this was lowered from.
type Script ¶ added in v0.35.0
type Script struct {
// contains filtered or unexported fields
}
Script accumulates statements. The zero value is not usable; call NewScript.
func ParseScriptBuilder ¶ added in v0.38.0
ParseScriptBuilder parses source into an uncompiled Script, for a caller that wants to inspect or extend it before compiling.
func (*Script) Break ¶ added in v0.38.0
Break leaves the innermost enclosing While and continues after it.
It is a jump to the address a false condition goes to, so a loop that breaks on its first iteration terminates for the same reason one whose condition is false terminates: there is no back edge on that path.
A BREAK IS BOUND BY A LOOP IN THE SAME FUNCTION BODY. A call is expanded where it is written, so a function called from inside a loop sits, instruction for instruction, inside that loop -- and a Break in its body would leave the CALLER's loop. That would make a function mean one thing at one call site and something else at another, and the same body legal in one place and nonsense in another. So a body starts with no enclosing loop, whatever the call site is inside, and a Break with nothing to name is refused.
Outside a loop altogether it is refused for the same reason: there is nothing to leave.
func (*Script) Compile ¶ added in v0.35.0
func (s *Script) Compile() (*ScriptProgram, error)
Compile lowers the script to a single register program.
func (*Script) Continue ¶ added in v0.38.0
Continue starts the innermost enclosing While's next iteration.
It jumps to the loop's HEADER, which is the condition, so the next iteration re-tests it exactly as falling off the end of the body does. It is bound by the same rule as Break.
func (*Script) For ¶ added in v0.38.0
For runs body once for each element of seq, with name bound to that element.
name is an ordinary script local: it is function-scoped like any other, it is still bound after the loop (holding the last element visited), and it is UNDEFINED if the loop ran zero times and nothing else bound it.
A seq that is not a list faults the script. An empty list is not a fault: the body runs zero times.
func (*Script) Func ¶ added in v0.38.0
Func defines a function callable from anywhere in the script, including from statements written BEFORE this call: a definition is recorded as soon as Func runs, while statements are not compiled until Compile.
The body is a block, exactly as If's and While's are, and it ends its value with Return.
func (*Script) If ¶ added in v0.35.0
If runs then when cond is true and els when it is false. Either block may be nil.
A condition that is NEITHER true nor false -- UNDEFINED, or a type that cannot be one, such as a string or a list -- is a FAULT: the script ends with ERROR. It is not a branch not taken. Treating "I could not tell" as "no" is how a misspelled attribute silently turns a script into one that quietly does nothing, and a script runs once, so there is no second record to notice.
A local bound inside a branch is the same local as everywhere else -- one register -- so a read after the If sees whatever path ran. Where no path bound it, it reads UNDEFINED, because the lowering can see that no store reaches that read.
func (*Script) Let ¶ added in v0.35.0
Let binds name to expr's value. A name already bound is REBOUND: later references see the new value and the old one stays live only for the statements that already read it, which is what `x = x + 1` has to mean.
func (*Script) Result ¶ added in v0.35.0
Result sets the script's value. It must be called last and exactly once.
func (*Script) Return ¶ added in v0.38.0
Return ends the enclosing function body with expr's value. A nil expr returns UNDEFINED, which is also what falling off the end of a body does.
A return of a call to the function being expanded is a TAIL CALL: the next activation's arguments are computed, the parameters are overwritten and control goes back to the body's first instruction. It is the only recursive call a script may make, and the only one that needs neither a second expansion nor a frame. See tailSelfCall for exactly which returns qualify.
func (*Script) While ¶ added in v0.35.0
While runs body for as long as cond is true.
The back edge is the only thing here that the lowering had not seen before, and it works because a statement leaves the stack as it found it: the value stack at the loop header is identical on every iteration, so there is nothing to reconcile between them. Locals are places, so a value carried across iterations is just a register written each time round -- no phi, and no loop-carried analysis to get wrong.
A condition that is neither true nor false faults, exactly as in If.
TERMINATION is not the loop's problem to solve but the interpreter's: `while true: x = x` has no answer, and nothing the compiler can check would tell it apart from a loop that happens to run a long time. The step budget in RunRegistersLimited is what bounds it.
type ScriptCallCaptureError ¶ added in v0.38.0
type ScriptCallCaptureError struct {
Func string // the function the subtree calls, as the script spelled it
Expr string // the delegated subtree, unparsed
}
ScriptCallCaptureError reports a call to a script function from inside a construct the compiler evaluates against the ad, where the function does not exist. The sibling of LocalCaptureError, and refused for the same reason: the tree-walking evaluator resolves the name against the built-ins and the UDF registry, finds nothing, and returns ERROR for a call the script can see perfectly well.
func (*ScriptCallCaptureError) Error ¶ added in v0.38.0
func (e *ScriptCallCaptureError) Error() string
type ScriptFunc ¶ added in v0.38.0
type ScriptFunc struct {
// contains filtered or unexported fields
}
ScriptFunc is one of a module's functions, compiled on its own and callable with argument values.
It is READ-ONLY once compiled and safe to call from any number of goroutines at once, which is not a convenience: a UDF is called from the parallel scan and from the vector executor, and `*classad.ClassAd` is explicitly not safe to share between goroutines. Nothing shared is written here -- each call allocates its own register file and its own evaluator, and the program, its constant pools and the parameter register list are written once at compile time.
func (*ScriptFunc) Arity ¶ added in v0.38.0
func (f *ScriptFunc) Arity() int
Arity returns the number of parameters the `def` declares.
It is the minimum AND the maximum: a `def` states its own arity, so unlike a Go or wasm registration there is no range for a caller to supply and get wrong.
func (*ScriptFunc) Call ¶ added in v0.38.0
func (f *ScriptFunc) Call(args []classad.Value) classad.Value
Call applies the function to argument values.
It returns a Value and never an error, because that is the shape a ClassAd function has: UNDEFINED and ERROR are values in this language and choosing between them is the function's job. The cases this function decides rather than the script are the two it can see and the script cannot:
- WRONG ARGUMENT COUNT is ERROR. A registration states its arity, so the engine rejects a call of the wrong shape before reaching here; this covers a caller invoking Call directly.
- A STEP BUDGET THAT RUNS OUT is ERROR. A script may loop, so a registered function may loop, and a registered function that hung would hang a scan over every record in a store rather than fail one expression. There is no way to report "did not finish" through a Value, and ERROR is the answer that propagates like any other failure.
func (*ScriptFunc) Func ¶ added in v0.38.0
func (f *ScriptFunc) Func() classad.Func
Func returns the function as a classad.Func, ready to register. It mirrors wasmudf's UDF.Func, so the two kinds of module reach the registry through the same shape.
func (*ScriptFunc) Name ¶ added in v0.38.0
func (f *ScriptFunc) Name() string
Name returns the function's name as the module spelled it.
func (*ScriptFunc) Program ¶ added in v0.38.0
func (f *ScriptFunc) Program() *Program
Program returns the compiled program, for tests and diagnostics.
type ScriptModule ¶ added in v0.38.0
type ScriptModule struct {
// contains filtered or unexported fields
}
ScriptModule is parsed module source: a set of named functions, each compilable on its own.
Parsing does not compile. A module whose functions include one that cannot be registered is still a usable module, because the refusal belongs to the function being registered and not to its siblings -- and because which functions a caller wants is the caller's business.
func ParseScriptModule ¶ added in v0.38.0
func ParseScriptModule(src string) (*ScriptModule, error)
ParseScriptModule parses ClassAd Script source that defines functions and produces no value.
The language is the one ParseScript parses, restricted to `def` at the top level. Inside a body nothing changes at all: the same statements, the same expressions, the same parser.
func (*ScriptModule) Compile ¶ added in v0.38.0
func (m *ScriptModule) Compile(name string) (*ScriptFunc, error)
Compile compiles one of the module's functions into a form that can be called with argument values. The name folds case, as a call does.
The function may call the module's other functions; the inliner expands those exactly as it does inside a script, so recursion is treated here exactly as it is treated there: a call to itself in tail position is a jump back to the entry, and every other cycle is refused by naming it.
It also applies the purity gate. A function that reaches the ad is refused HERE rather than at registration because the compiled form has no ad to reach: there is no subject, so an attribute read has no answer that could be right. Registration is where that refusal matters, and it is not where it is discovered.
func (*ScriptModule) Functions ¶ added in v0.38.0
func (m *ScriptModule) Functions() []string
Functions returns the module's exported function names, as written, in source order.
type ScriptProgram ¶ added in v0.35.0
type ScriptProgram struct {
// contains filtered or unexported fields
}
ScriptProgram is a compiled script.
func ParseScript ¶ added in v0.38.0
func ParseScript(src string) (*ScriptProgram, error)
ParseScript parses ClassAd Script source and compiles it.
The returned program is the same thing NewScript()...Compile() returns and runs identically; there is no second execution path for parsed scripts, and no part of the compiler knows which way a script arrived.
Example ¶
A script written down rather than built: three statements that give an absent request a default and clamp it to a floor. The expressions are ordinary ClassAd expressions -- `is` is `=?=` -- and the statements around them are the part a single expression cannot say.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
# Effective memory request, with a floor and an explicit absence case.
want = MY.RequestMemory
if want is undefined:
want = 2048
if want < 512:
want = 512
result = want
`)
if err != nil {
fmt.Println(err)
return
}
for _, src := range []string{
`[RequestMemory = 4096]`,
`[RequestMemory = 64]`,
`[Owner = "alice"]`,
} {
ad, err := classad.Parse(src)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%-24s -> %s\n", src, sp.Run(ad))
}
}
Output: [RequestMemory = 4096] -> 4096 [RequestMemory = 64] -> 512 [Owner = "alice"] -> 2048
Example (BreakAndContinue) ¶
`break` leaves the innermost enclosing `while`, and `continue` starts its next iteration. Here the loop walks the powers of two looking for the first one over the request; `continue` skips the sizes the machine cannot hold, and `break` stops the walk as soon as one fits.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
# The smallest power of two that holds the request and fits the machine.
size = 1
chosen = 0
while size <= 65536:
size = size * 2
if size > MY.MachineMemory:
continue
if size < MY.RequestMemory:
continue
chosen = size
break
result = chosen
`)
if err != nil {
fmt.Println(err)
return
}
for _, src := range []string{
`[RequestMemory = 3000; MachineMemory = 65536]`,
`[RequestMemory = 100; MachineMemory = 65536]`,
`[RequestMemory = 3000; MachineMemory = 2048]`,
} {
ad, err := classad.Parse(src)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%-45s -> %s\n", src, sp.Run(ad))
}
}
Output: [RequestMemory = 3000; MachineMemory = 65536] -> 4096 [RequestMemory = 100; MachineMemory = 65536] -> 128 [RequestMemory = 3000; MachineMemory = 2048] -> 0
Example (For) ¶
A loop over a list, and a local indexed by the loop's own variable.
The sequence is evaluated once, before the first trip. A sequence that is not a list is a fault: the script ends with ERROR rather than running the body zero times, so a misspelled attribute says so instead of quietly computing the identity.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
# The largest request in a list, and how many of them exceed the cap.
largest = 0
over = 0
for request in MY.Requests:
if request > largest:
largest = request
if request > MY.Cap:
over += 1
result = largest * 1000 + over
`)
if err != nil {
fmt.Println(err)
return
}
for _, src := range []string{
`[Cap = 4096; Requests = {1024, 8192, 2048}]`,
`[Cap = 4096; Requests = {}]`,
`[Cap = 4096]`,
} {
ad, err := classad.Parse(src)
if err != nil {
fmt.Println(err)
return
}
value, _, fault := sp.RunWithFault(ad)
if fault != nil {
fmt.Printf("%-42s -> %s\n", src, fault)
continue
}
fmt.Printf("%-42s -> %s\n", src, value)
}
}
Output: [Cap = 4096; Requests = {1024, 8192, 2048}] -> 8192001 [Cap = 4096; Requests = {}] -> 0 [Cap = 4096] -> condition fault at for #1 condition: the condition was an error value
Example (Loop) ¶
A loop, which is the shape no single ClassAd expression has: the number of trips depends on the value being computed.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
# How many halvings fit the request under the cap.
size = MY.RequestMemory
steps = 0
while size > MY.Cap:
size = size / 2
steps += 1
result = steps
`)
if err != nil {
fmt.Println(err)
return
}
ad, err := classad.Parse(`[RequestMemory = 32768; Cap = 1024]`)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(sp.Run(ad))
}
Output: 5
Example (Subscript) ¶
A script local can be indexed, which is what the element load is for: `seq[0]` reads the local's own value rather than an attribute named seq.
An index past the end of a list is ERROR, not UNDEFINED -- that is the reference engine's answer and the compiled one is the same -- so `?:`, which defaults only an UNDEFINED, does not catch it.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/classad"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
sp, err := vm.ParseScript(`
# The first two elements of a list the ad supplies, defaulted elementwise.
seq = MY.Sizes
result = (seq[0] ?: 0) + (seq[1] ?: 0)
`)
if err != nil {
fmt.Println(err)
return
}
for _, src := range []string{
`[Sizes = {10, 20, 30}]`,
`[Sizes = {10}]`,
`[]`,
} {
ad, err := classad.Parse(src)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%-24s -> %s\n", src, sp.Run(ad))
}
}
Output: [Sizes = {10, 20, 30}] -> 30 [Sizes = {10}] -> error [] -> 0
Example (SyntaxError) ¶
A syntax error names the line, the column and what was expected, and renders with the offending line under it.
package main
import (
"fmt"
"github.com/PelicanPlatform/classad/collections/vm"
)
func main() {
_, err := vm.ParseScript("want = MY.RequestMemory\nif want < 512\n want = 512\nresult = want\n")
fmt.Println(err)
}
Output: line 2, column 14: expected ':' at the end of the 'if' header if want < 512 ^
func (*ScriptProgram) Locals ¶ added in v0.35.0
func (sp *ScriptProgram) Locals() []string
Locals returns the local names in binding order.
func (*ScriptProgram) Program ¶ added in v0.35.0
func (sp *ScriptProgram) Program() *Program
Program returns the underlying stack-form program.
A script with statement-level control flow -- an If, a While, a fault site -- is NOT runnable by the stack interpreter, which has no implementation for a statement jump. A straight-line script is, local bindings and all, which is what lets the two interpreters be checked against each other on the same program. It is exposed for the planner's read set and for tests that inspect the compiled shape.
func (*ScriptProgram) RegProgram ¶ added in v0.35.0
func (sp *ScriptProgram) RegProgram() *RegProgram
RegProgram returns the compiled register program.
func (*ScriptProgram) Run ¶ added in v0.35.0
func (sp *ScriptProgram) Run(scope *classad.ClassAd) classad.Value
Run evaluates the script against scope and returns its result, under the default instruction budget.
func (*ScriptProgram) RunLimited ¶ added in v0.35.0
RunLimited is Run with an explicit step budget. ok=false means the script did not finish within it, which is a different report from a script that finished and computed ERROR.
func (*ScriptProgram) RunWithFault ¶ added in v0.35.0
func (sp *ScriptProgram) RunWithFault(scope *classad.ClassAd) (result classad.Value, ok bool, fault *Fault)
RunWithFault evaluates the script and reports the fault that stopped it, if one did.
fault is nil when the script completed, whatever value it produced -- including ERROR, which an expression can produce on purpose. That distinction is the reason this method exists: the value alone cannot tell "the script decided the answer is ERROR" from "an if had no branch to take".
ok=false means the step budget ran out, which is not a fault: the script did not finish, so there is no site to blame. See RunRegistersLimited.
func (*ScriptProgram) String ¶ added in v0.35.0
func (sp *ScriptProgram) String() string
String renders the script's registers for diagnostics.
func (*ScriptProgram) VecEval ¶ added in v0.35.0
func (sp *ScriptProgram) VecEval(src ColumnSource, n int, scratch *VecScratch) (*Vec, bool)
VecEval runs the script over a batch of n records, returning one result element per record.
ok=false when the script uses something the vector executor does not implement. Control flow is not in that set: an If runs both arms under a live mask and a While runs its iterations in lockstep, letting the live set shrink as records finish. What declines is a delegated subtree, which needs a real per-record scope, and a `break` or `continue`, which leaves a loop from a point the lockstep walk has no region for.
A DECLINE IS NOT A WRONG ANSWER. The caller falls back to running the script per record, which is the same arrangement the expression executor has had since it was written.
type ScriptSyntaxError ¶ added in v0.38.0
type ScriptSyntaxError struct {
Line int // 1-based
Column int // 1-based, counted in runes
Msg string // what went wrong, and where possible what was expected instead
Source string // the text of Line, for the caret
}
ScriptSyntaxError is a syntax error with the position of the thing that caused it.
It carries the offending source line so a caller that prints the error gets the caret for free. A parser whose errors say only "syntax error" is a parser people route around, and the script is a place where the mistake is usually an indent or a stray colon -- exactly the mistakes a column pins down and a prose message does not.
func (*ScriptSyntaxError) Error ¶ added in v0.38.0
func (e *ScriptSyntaxError) Error() string
type Vec ¶ added in v0.27.0
type Vec struct {
// DATA form: one element per record.
I []int64
S []string
St []uint8
// MASK form: three-valued logic as two bitplanes, two bits per record. See vecmask.go.
Hi, Lo []uint64
// Raw, when non-nil, is the column in its STORED form: n values of RawWidth bytes, contiguous, as the
// block holds them. I is NOT populated while it is set.
//
// It exists for one reason: lanes come from width. A column fitted to two bytes is 8 lanes of a 128-bit
// vector against 2 as int64, and widening it at load throws that away before any kernel sees it. So a
// comparison against a literal can run width-native (see simdCompareRaw) and everything else calls
// ensureInts, which widens exactly as loadIntBatch used to and clears Raw. A transient optimization that
// collapses to the ordinary representation on first non-specialized use.
Raw []byte
RawWidth int
RawUnsigned bool
RawReal bool // a real's slot holds math.Float64bits, so widening it yields VsReal rather than VsInt
// Dict, when non-nil, resolves VsDictCode elements: the column is a dictionary-encoded string, so I[i]
// holds a code rather than a value and S[i] is not populated.
//
// A comparison against a string LITERAL specializes on this and becomes an integer range test, which is
// the whole point -- the dictionary is fold-ordered, so the entries matching a literal are contiguous.
// Everything else stays correct without knowing about it, because valueData resolves a code to its
// string and the parity hook takes it from there.
Dict DictResolver
// Const marks a vector every record of which holds the SAME value, kept once in element 0 with the
// rest left as garbage. A literal in an expression is the dominant case, and materializing one across
// a block cost 9.8% of a scan in the profile -- nine bytes per record written per block, to say the
// same thing 1000 times.
//
// Every consumer must either specialize on it (compareVec does, which also tightens its loop by
// reading a scalar instead of a second array) or call materialize first. valueData and IsTrue read
// element 0 when it is set, so the parity-hook path and the counters are safe without either.
Const bool
// Mask selects which form holds this vector's value. A comparison consumes data and produces a
// mask; a logical operator consumes and produces masks; arithmetic consumes and produces data.
// Conversion in either direction is available (toMask/toData) but only happens where an operator
// genuinely needs the other form.
Mask bool
// contains filtered or unexported fields
}
Vec is one batch of values. The payload is a single int64 slice because that is how both classad.Value and the columnar block already store a real (as IEEE-754 bits), so loading a column into a vector is a copy rather than a conversion, and no precision is lost for integers above 2^53.
func NewColumnVec ¶ added in v0.37.0
NewColumnVec allocates a vector that can receive a loaded COLUMN, mask planes included.
NewVec is for a caller building values element by element and leaves Hi and Lo nil, which is right for it and wrong here: a boolean column with no escape is delivered as a MASK, so a vector without planes takes none of its bits and then reads past the end of a nil slice on the way out.
func NewVec ¶ added in v0.28.0
NewVec allocates a data-form vector of n elements, every one UNDEFINED.
For a caller outside this package that materializes a column the loaders cannot produce -- one that exists for only SOME records, so it has to be presented at full length with the rest undefined. Undefined rather than zero is the safe start: an element nothing writes then reads as "no value here" instead of as the integer 0.
func (*Vec) Cell ¶ added in v0.37.0
Cell reads element i in the form the vector holds it, without boxing it into a classad.Value.
It exists for a VALUE producer rather than for a predicate. Every other reader of a vector is deciding a comparison, so it specializes on Raw, Const and Dict and never needs the element itself; valueData is the one that does need it and it boxes, which for a producer is an allocation per cell to undo immediately. A producer needs the element, needs it typed, and must not become the fourth place in this package that knows a real is stored as its bits.
st is never VsDictCode: a code is RESOLVED here, because the dictionary is per block and a caller holding the cell past that block has nothing left to resolve it against. str is empty unless st is VsString, and num is meaningful only for VsInt, VsReal (as math.Float64bits) and VsBool (0 or 1).
Total by construction: every state, both forms, and an unresolvable code all map to some cell, because a producer that met an unexpected shape and dropped the row would lose a record rather than report an odd value for it.
func (*Vec) CopyElem ¶ added in v0.28.0
CopyElem copies element j of src into element i of v, preserving its state -- int stays int, real stays real, a dictionary code stays a code. Returns false if either index is out of range.
This is the scatter primitive. Boxing through classad.Value would work and is what a caller without it must do, but it allocates for strings and loses the dictionary encoding, turning a code copy into a string materialization per record.
A src in RAW form is widened first: raw is a stored-width column, and an element of it means nothing once separated from its width and signedness.
func (*Vec) CountTrue ¶ added in v0.27.0
CountTrue counts records that are TRUE and whose bit is set in live.
In mask form that is one popcount per 64 records. In data form -- a constraint whose value is a number or a string, which never matches -- it walks elements, because such a constraint is rare and being right about it matters more than being quick.
func (*Vec) Float ¶ added in v0.27.0
Float returns element i as a float64 whatever its numeric state.
func (*Vec) IsTrue ¶ added in v0.27.0
IsTrue reports whether element i is TRUE, which is what counting matches needs. UNDEFINED and ERROR are not matches. IsTrue reports whether element i is strictly boolean TRUE, which is what counting matches needs.
This is NOT the truthiness used for a logical OPERAND. A constraint whose value is the number 42 does not match -- the store's isTrueValue takes a boolean or nothing -- while `42 && true` is TRUE because numbers are truthy as operands. Two different notions of truth, and conflating them is a silent wrong-answer bug, so they are separate functions: this one, and dataStateToMask.
type VecScratch ¶ added in v0.27.0
type VecScratch struct {
// contains filtered or unexported fields
}
VecScratch holds the vector stack and the evaluator so a scan reuses both across batches instead of allocating per block.
func (*VecScratch) Release ¶ added in v0.27.0
func (s *VecScratch) Release()
Release drops the vector stack's references to string payloads and returns the scratch to a state safe to keep in a pool.
A string element aliases a block's decompressed string region rather than copying it, so a pooled stack would otherwise pin whichever region it last read -- for as long as the pool holds it, and even if the table it came from has since been dropped. The regions are heap buffers, so this is a retention question rather than the use-after-munmap hazard aliasing mmap'd memory would create, but a few thousand pointer writes per query is a cheap way not to have the question at all.
Source Files
¶
- alias.go
- cfg.go
- compile.go
- delegated.go
- fault.go
- hide.go
- interp.go
- liveness.go
- matcher.go
- member.go
- opcode.go
- optimize.go
- plan.go
- probe.go
- probeprefix.go
- program.go
- query.go
- regir.go
- script.go
- scriptfor.go
- scriptfunc.go
- scriptlex.go
- scriptmodule.go
- scriptparse.go
- simdcompare.go
- simdengine_off.go
- step.go
- strlist.go
- veccell.go
- veccolcache.go
- vecexec.go
- veclist.go
- vecloop.go
- vecmask.go
- vecpath.go
- vecpred.go
- wirematch.go