Documentation
¶
Overview ¶
Package wasmudf runs user-defined ClassAd functions compiled to WebAssembly.
It is a separate Go module so the wazero dependency is opt-in: a program that imports classad but never wants a sandboxed UDF does not link a wasm compiler.
Integrating a module -- loading it, choosing its sandbox, deciding whether to trust it -- is documented in docs/user-defined-functions.md at the repository root, which covers all four ways to extend this engine and treats wasm as one of them.
Writing a guest module is documented in prose, for someone who is not reading this code and may not write Go, in docs/wasm-udf-abi.md at the repository root. It covers both calling conventions, the ownership and lifetime rules, and what is stable across versions. The comments here and in abivec.go explain why the host is built the way it is; that file explains what a module author has to do.
What a UDF is here ¶
Exactly what classad's registry says it is: a pure function of its argument VALUES. It receives no evaluator, so it cannot reach the calling scope, cannot resolve an attribute, and cannot materialize a lazy list -- those are structural consequences of the registry's signature rather than rules this package enforces, which is why they cannot be worked around from inside a guest.
That purity is what makes a UDF safe to COMPILE INTO a query: StrictFunction answers "can this call be lowered to a call on pre-evaluated argument values", and the answer for a registered UDF is yes for the same reason it is yes for pow(). A UDF that could see its caller's scope would have to be delegated to the tree-walking evaluator on every record, which is the cost this design is built to avoid.
The ABI ¶
One call passes argument values in and takes one value out, through the guest's linear memory. A VALUE SLOT is 16 bytes, little-endian, naturally aligned:
offset 0 u32 tag offset 4 u32 byte length (strings only; zero otherwise) offset 8 u64 payload tag 0 UNDEFINED payload unused tag 1 ERROR payload unused tag 2 boolean payload 0 or 1, and nothing else tag 3 integer payload is the int64, two's complement tag 4 real payload is the float64's IEEE-754 bits tag 5 string payload is a u32 offset in its LOW word, length at +4
A guest exports:
(memory (export "memory") ...) (func (export "classad_udf_abi_version") (result i32)) (func (export "classad_udf_call") (param i32 i32 i32) (result i32))
and classad_udf_call(argsPtr, argc, resultPtr) returns 0 when it has written a value to the result slot, or any nonzero value to say it could not.
Fixed-width tagged slots, rather than a packed or self-describing encoding, because the guest must be able to reach argument k at a constant offset (argsPtr + k*16). That removes the parsing loop from every guest -- the place where a hand-written module is most likely to be wrong -- and it means the host writes a call frame with no per-argument branching beyond the tag switch it already needs. The cost is 16 bytes per argument for values that would pack into 9; at one call per record that is a memory write that never leaves L1.
UNDEFINED and ERROR have TAGS, not out-of-band signalling, because in ClassAd they are values: isUndefined(f(x)) is a question a UDF's caller is entitled to ask, and a UDF handed UNDEFINED must be able to decide for itself whether its answer is UNDEFINED, ERROR or a number. A host that mapped them onto a status code would make them failures of the call instead, and the distinction between "this argument was missing" and "this function broke" would be gone.
The status return is NOT how a guest reports ERROR -- it can encode ERROR in the slot. It exists so the host knows whether the slot was WRITTEN at all. The host poisons the result slot with an impossible tag before every call, so a guest that returns 0 without writing produces a defined failure instead of the PREVIOUS record's answer. Those two halves (poison plus status) are what make a forgetful guest loud rather than silently wrong.
The call frame and where it lives ¶
The host owns a region of the guest's linear memory and lays each call out in it: argc slots, then the result slot, then an arena holding the bytes of any string arguments.
The region is placed in pages the host ADDS to the memory, after instantiation, with memory.grow. Those pages cannot overlap anything the guest already has: its data segments and stack live below the initial memory size, and a guest that grows memory later gets pages above the host's. So the host needs no allocator export from the guest and no convention about free addresses -- the placement is a consequence of how wasm memory grows. (A guest is of course free to scribble on the region; the worst it achieves is a wrong value for its own call, which the result validation turns into ERROR.)
String bytes the host writes are valid only for the duration of the call. A string the GUEST returns may point anywhere in its own memory, including at the host's arena; the host validates the pointer and copies the bytes out, so no guest address outlives the call either.
What this refuses ¶
Lists and nested ads are not in the tag space, as arguments or as results. A list argument is refused before the guest runs: the registry hands a UDF values it cannot materialize a lazy list from, and an ABI that flattened one would be re-introducing the materialization the registry's signature exists to prevent. Nested ads would need the scope machinery a UDF deliberately does not get.
No I/O, no clock, no randomness, no WASI. This is not a policy applied to guests, it is the absence of anything to call: the host offers exactly one import (the step counter below), so a module wanting more cannot be instantiated and is rejected at load, naming what it asked for. A UDF that could read the clock would also not be a pure function of its arguments, and could not be compiled into a query at all -- see classad's nonStrictFunctions, where time and random sit for exactly this reason.
Two entry points ¶
A module always exports the SCALAR entry point, called once per record. It may also export a VECTOR entry point, called once per batch, which is what gets a UDF into the vector engine's hot loop instead of pulling the whole query off it. CallBatch uses the vector one and falls back to the scalar one for anything it cannot do; see Batch and abivec.go for the batch representation and the escape hatch by which a vectorized guest declines individual records.
Requiring the scalar one is what makes the escape hatch unconditional: there is no module shape in which a declined record has nowhere to go.
The measured difference, on an Apple M2 Pro, per element, for a UDF that doubles a number:
scalar, untrusted 782 ns scalar, trusted 106 ns batch of 4096, untrusted 27.9 ns batch of 4096, trusted 6.3 ns
Batching is worth 28x on its own and 17x on top of trust, so the two are not substitutes: trust removes a per-call cost, batching removes a per-call cost AND amortizes the marshalling, and what is left at 6.3 ns is the work.
Trust ¶
An admin may label a module trusted (LoadOptions.Trusted). A trusted module is compiled into a runtime that cannot be interrupted and runs with no wall-clock deadline, which is where almost all of the scalar path's overhead was.
It does NOT relax the deterministic step budget, the memory cap, the poisoned result slot, the validation of what a guest returns, or discarding an instance that trapped. The measurement is why: the budget is not where the time goes, and it is the only bound whose failures are reproducible, so relaxing it would buy nothing and cost the one property that makes a trusted module and an untrusted one comparable on the same input.
Trust is CONFIGURATION. Nothing in a module is consulted -- not an export, not a custom section, not a name -- and there is deliberately no ABI through which a guest could ask, because a capability a module can assert is a request rather than a capability. What a trusted module gives up is liveness: one that loops forever hangs its goroutine with nothing able to stop it, which is precisely why the decision belongs to the party that configured the pool.
Bounds ¶
Memory is capped by the runtime (a hard bound; the guest's grow simply fails).
Run length is bounded two ways, and the difference between them matters:
A STEP BUDGET, in units the guest declares by calling the one import this host offers, classad_udf.fuel(cost). It is deterministic: the same arguments exhaust it at the same point on a loaded machine and an idle one, which is what makes a UDF that hits the limit reproducible and therefore differentially testable against a non-wasm implementation of the same function. It is also COOPERATIVE -- a module that never calls fuel is never charged -- so it bounds instrumented guests and nothing else.
A WALL-CLOCK deadline, enforced by the runtime against any guest at all. This is the one that stops a bare `(loop (br 0))`.
The step budget is the contract and the deadline is the backstop, in that order and not the other way around, because a limit measured in wall clock makes the same input succeed on one machine and fail on another: the fault is not reproducible, so it cannot be tested against anything. The deadline exists only because the step budget cannot be made involuntary without rewriting the guest's bytecode to inject the charges, which this increment does not do. The two failures are reported as different reasons (ReasonStepLimit, ReasonTimeout) so a test can assert that a given module only ever hits the deterministic one.
The deadline is set up ONCE per CallBatch, covering the vector call and every record escalated out of it, rather than once per record. That is the right scope as well as the cheap one: the engine's unit of work is the batch, so a deadline per record would let a batch of 4096 run for 4096 times the configured limit.
Aggregates ¶
A guest can also supply an AGGREGATE, which the database engine reduces with exactly as it reduces with SUM. It is a separate export set under its own version -- a module is one or the other -- because the two have nothing in common at the boundary except the value slot above.
(memory (export "memory") ...) (func (export "classad_udaf_abi_version") (result i32)) (func (export "classad_udaf_init") (param i32 i32) (result i32)) (func (export "classad_udaf_fold") (param i32 i32 i32 i32 i32 i32) (result i32)) (func (export "classad_udaf_merge") (param i32 i32 i32 i32 i32 i32) (result i32)) (func (export "classad_udaf_result") (param i32 i32 i32) (result i32))
Four operations: produce the identity state, fold a batch of value slots into a state, merge two states, render a state as one value slot. init and fold and merge return the length of the state they wrote, or a negative number to refuse; result returns a status like a scalar call.
THE STATE IS BYTES THE HOST HOLDS, not a handle into guest memory, and the reason is lifetime rather than speed. An accumulator holding a handle would pin the instance that minted it, and the engine's accumulator interface has no close -- worse, when the columnar pass declines, every worker's accumulator is dropped with neither merge nor result ever called, so there is no moment at which guest memory could even be inferred to be free. With the state in the host, an accumulator is an ordinary Go value, instances are borrowed per call as the scalar path borrows them, and merging two states works whichever instances they were folded in. The copy that costs is amortized by folding a BATCH of values per call.
MERGE IS NOT DECORATION. The engine's columnar aggregate pass fans out across segment windows: one state per worker, folded once every worker has returned. Which worker draws which segment is a race, so merge must be associative and commutative and the aggregate must not depend on the order values arrive in. A guest that gets this wrong is wrong only sometimes, and plausibly.
The OPTIONAL export classad_udaf_fold_num, with fold's signature and slot layout, is how a guest says it may be fed from a column: that its answer does not depend on arrival order, and that it does not count what it was never offered -- the column pass yields only a column's numeric values, so a record whose argument is absent or a string is not offered at all. A guest for which both hold exports the same function under both names. Without it the aggregate is served from the record scan, which is correct and slower, never wrong. db.CheckAggregate tests all of it against a real sample.
Failures ¶
Everything a FUNCTION guest can do wrong is either a load error or the ClassAd value ERROR. Nothing becomes a panic: a daemon evaluating an expression runs no top-level recover, so a panic escaping here would reach the process, and a UDF in a Requirements expression would take the daemon down one match at a time. See Reason for the full list and UDF.Call for the classification.
AN AGGREGATE IS THE OPPOSITE, deliberately. It reports a failure by panicking with an *AggError, because containment for an aggregate is per query rather than per row: a record evaluating to ERROR says nothing about the others, where a state that stopped being updated part-way is a wrong answer indistinguishable from a right one. The engine's aggregate pass recovers it -- on the calling goroutine, even for a panic raised on a worker -- and fails the query naming the aggregate. Nothing here is left for a caller of this package to recover.
Example (AggregateModule) ¶
Example_aggregateModule loads a WebAssembly aggregate and reduces with it.
An aggregate is a different module rather than a different function: four exports under their own ABI version, over a state the host holds as bytes. A module is one or the other.
ctx := context.Background()
l, err := NewLoader(ctx, Options{})
if err != nil {
panic(err)
}
defer l.Close(ctx) //nolint:errcheck // an example, not a daemon
wasm, err := os.ReadFile("testdata/examplemean.wasm")
if err != nil {
panic(err)
}
a, err := l.LoadAggregate(ctx, "wasmMean", wasm)
if err != nil {
panic(err)
}
// Columnar reports whether the module exported the optional numeric fold -- that is, whether
// it declared it may be fed from a column instead of from decoded records.
fmt.Println("columnar:", a.Columnar())
// CheckAggregate runs the merge laws over a sample of the caller's choosing. It is not a
// proof -- the laws are universally quantified and this is one finite sample -- but an
// order-sensitive merge is exactly the mistake it finds, and the mistake an author's own
// tests do not, because an author tests the order their own code produces.
samples := []classad.Value{
classad.NewIntValue(2),
classad.NewIntValue(4),
classad.NewRealValue(9.0),
classad.NewIntValue(1),
classad.NewStringValue("not a number"),
classad.NewUndefinedValue(),
}
fmt.Println("laws:", db.CheckAggregate(a.Aggregate(), samples))
// Reducing by hand, as the engine does: one accumulator per group, merged, then rendered.
agg := a.Aggregate()
left, right := agg.NewAccumulator(), agg.NewAccumulator()
for _, v := range samples[:2] {
left.Add(v)
}
for _, v := range samples[2:] {
right.Add(v)
}
left.Merge(right)
fmt.Println("mean:", left.Result().String())
fmt.Println("empty group:", agg.NewAccumulator().Result().String())
Output: columnar: true laws: <nil> mean: 4 empty group: undefined
Example (ScalarModule) ¶
Example_scalarModule loads a WebAssembly module and makes it callable from an ordinary ClassAd expression. From the expression's side there is nothing to see: a guest is reached through the same registry a Go function is, so pctUsed below could be either and the expression cannot tell.
ctx := context.Background()
// The Options are the sandbox, and they are the admin's, not the module's. A module cannot
// ask for more: the host offers it exactly one import, so a guest wanting a clock or a file
// is refused at load naming what it asked for.
l, err := NewLoader(ctx, Options{
MemoryLimitPages: 16, // 1 MiB of linear memory
Steps: 1 << 20, // the deterministic budget, in units the guest charges itself
Timeout: 100 * time.Millisecond, // the backstop for a guest that charges nothing
})
if err != nil {
panic(err)
}
defer l.Close(ctx) //nolint:errcheck // an example, not a daemon
wasm, err := os.ReadFile("testdata/examplepct.wasm")
if err != nil {
panic(err)
}
// Loading comes first and registration second, so a name is only ever registered against a
// module that compiled, exports what it must, speaks this ABI, and has been called once.
// Neither registry has an unregister, so registering something unproven cannot be undone.
u, err := Register(ctx, l, ClassAdRegistry(), "pctUsed", 2, 2, wasm)
if err != nil {
panic(err)
}
ad, err := classad.Parse(`[ Used = 3; Total = 8; Label = "eight" ]`)
if err != nil {
panic(err)
}
for _, src := range []string{
`pctUsed(Used, Total)`,
`pctUsed(Used, Absent)`,
`pctUsed(Used, Label)`,
} {
expr, perr := classad.ParseExpr(src)
if perr != nil {
panic(perr)
}
fmt.Printf("%-24s %s\n", src, expr.Eval(ad).String())
}
// What the module did is counted, which is how an operator sees a guest that is quietly
// failing every call rather than answering.
s := u.Stats()
fmt.Printf("calls=%d failures=%d vectored=%v trusted=%v\n", s.Calls, s.Failures, u.Vectored(), u.Trusted())
Output: pctUsed(Used, Total) 37.5 pctUsed(Used, Absent) undefined pctUsed(Used, Label) error calls=3 failures=0 vectored=false trusted=false
Index ¶
- Variables
- type AggError
- type AggStats
- type AggregateRegistry
- type Batch
- type LoadOptions
- type Loader
- func (l *Loader) Close(ctx context.Context) error
- func (l *Loader) Load(ctx context.Context, name string, minArgs, maxArgs int, wasm []byte) (*UDF, error)
- func (l *Loader) LoadAggregate(ctx context.Context, name string, wasm []byte) (*UDAF, error)
- func (l *Loader) LoadAggregateWith(ctx context.Context, name string, wasm []byte, lo LoadOptions) (*UDAF, error)
- func (l *Loader) LoadWith(ctx context.Context, name string, minArgs, maxArgs int, wasm []byte, ...) (*UDF, error)
- func (l *Loader) Lookup(name string) (*UDF, bool)
- func (l *Loader) LookupAggregate(name string) (*UDAF, bool)
- type Options
- type Reason
- type Registry
- type Stats
- type UDAF
- type UDF
- func (u *UDF) Arity() (minArgs, maxArgs int)
- func (u *UDF) Call(args []classad.Value) classad.Value
- func (u *UDF) CallBatch(args []Batch, out *Batch) bool
- func (u *UDF) Func() func(args []classad.Value) classad.Value
- func (u *UDF) Name() string
- func (u *UDF) Stats() Stats
- func (u *UDF) Trusted() bool
- func (u *UDF) Vectored() bool
Examples ¶
Constants ¶
This section is empty.
Variables ¶
ErrRegistryUnavailable was returned by the classad registry adapter while classad.RegisterFunction did not yet exist.
Deprecated: it exists, and ClassAdRegistry calls it. Nothing returns this any more. It is kept because it is exported and a caller may still be testing for it -- a caller that does will now simply never see it, where deleting it would stop that caller compiling.
Functions ¶
This section is empty.
Types ¶
type AggError ¶ added in v0.37.0
AggError is what a failed aggregate operation reports.
It names the aggregate, because the engine turns it into a failed query and the one thing an operator needs from that is whose code did it.
type AggStats ¶ added in v0.37.0
type AggStats struct {
Accumulators uint64
Folds uint64
Merges uint64
Results uint64
Values uint64
Failures uint64
Instances uint64
ByReason map[Reason]uint64
}
AggStats is a snapshot of one aggregate's counters.
Accumulators is the one an operator reads first: it is how many per-worker states a query made, so a value above one is the fan-out reaching the aggregate. A test asserting a fan-out happened has nothing else to assert on, since a pass that quietly stopped fanning out gives the same answers.
type AggregateRegistry ¶ added in v0.37.0
AggregateRegistry is the part of db's aggregate registry this package needs.
It is an interface for the reason the scalar Registry is one: a test can hand RegisterAggregate a registry it can inspect, which is the only way to assert that loading registers the right name against the right aggregate without writing to the process-wide table every other test in this package shares.
Unlike the scalar case there is no adapter waiting on a function that does not exist yet: db.RegisterAggregate is here today, and DBRegistry calls it.
func DBRegistry ¶ added in v0.37.0
func DBRegistry() AggregateRegistry
DBRegistry returns the process-wide aggregate registry in package db.
type Batch ¶
type Batch struct {
// N is the element count. For a Const batch only element 0 is meaningful,
// but N is still the record count, because that is what the result has to be.
N int
// Mask selects the form. False: St and I hold the values, one element each.
// True: Hi and Lo are the two bitplanes, two bits per record.
Mask bool
// Const marks a batch every record of which holds the same value, kept once
// in element 0 with the rest left as garbage.
//
// It is passed THROUGH to the guest as a flag rather than materialized. A
// literal argument is the dominant case, and writing nine identical bytes per
// record to say the same thing n times is the cost Vec.Const was introduced
// to remove -- 9.8% of a scan in the profile that found it. Re-materializing
// it at the ABI boundary would put that straight back.
Const bool
// St and I are the DATA form: a state code per element and an int64 payload
// per element. A real's payload is its IEEE-754 bits, which is how both
// classad.Value and the columnar block already store one.
St []uint8
I []int64
// Hi and Lo are the MASK form: three-valued logic as two bitplanes.
Hi, Lo []uint64
// Uniform asserts that every one of the N elements is in state State, so the
// host does not have to look. It is a DECLARATION, not a hint: nothing
// verifies it, and a batch that sets it wrongly hands the guest a column
// described as something it is not.
//
// It is here because for the columns that matter the answer is already known
// rather than discoverable. A numeric column loaded from a columnar block with
// no escaped values has its state written across it by the loader, from the
// field's declared kind; a boolean one arrives as a mask. Proving afterwards
// what the loader just did would be the only pass over the column the whole
// call makes.
//
// Left false, the host scans, which is a pass it was making anyway on the
// version 1 path to find strings. So this buys the scan back, it does not
// unlock the form.
Uniform bool
// State is the state every element is in when Uniform is set, using the same
// codes as St. Ignored otherwise.
State uint8
}
Batch is one column of values in the vector engine's own representation.
Its fields are named and shaped to match collections/vm's Vec field for field, so an adapter on that side is an assignment and not a conversion:
Batch{N: v.Len(), Mask: v.Mask, Const: v.Const, St: v.St, I: v.I, Hi: v.Hi, Lo: v.Lo}
The slices ALIAS the engine's vectors; nothing here copies them, and nothing here retains them past the call. That is the point. The engine pools its vectors across batches and queries precisely so a scan does not allocate per block, and an ABI that took a copy of every column on the way in would hand that back.
It is declared here rather than imported from collections/vm because the dependency can only run one way: collections imports classad, this module imports classad, and the engine is the CALLER. An import of collections/vm here would be a cycle the moment the engine called into this package. The cost is that the two declarations have to agree, which TestVectorStatesMatchEngine turns from a convention into a test.
NOT REPRESENTED, deliberately:
Raw (a column in its stored width). It is a transient load-time optimization whose shape -- 2, 4 or 8 bytes, signed or unsigned, integer bits or float bits -- is a property of the block on disk. Exposing it would put four code paths in every guest and break them all the next time the block format changes. The engine already collapses Raw to I on the first use that is not specialized for it, and a call into a guest is one; the cost is the widening pass loadIntBatch used to do unconditionally, paid now only by columns that reach a UDF.
Dict (dictionary codes plus a block-wide entry list). Carrying it would mean serializing a dictionary into guest memory per batch to keep the codes meaningful; materializing it instead means a string per record, which is what the dictionary exists to avoid. Both are real costs and neither is obviously right, so this increment carries neither: a dictionary-coded or plain-string argument DECLINES the batch and the engine's elementwise path serves it. Declining up front rather than per record is not a shortcut -- a string column is strings for every record, so escalating them one at a time would be the elementwise path with a vector call in front of it.
There is no "absent" or "not present" state, here or in the engine. An attribute a record does not have arrives as UNDEFINED -- that is what LoadColumn writes for a non-member of a group schema, and what the mask form's mUndef means. Adding a third bitplane to say "absent" would be inventing a distinction the evaluator does not make.
type LoadOptions ¶
type LoadOptions struct {
// Trusted runs the module without the wall-clock backstop and on wazero's
// non-interruptible code path: ~15ns per call against ~350ns, which is the
// whole reason the label exists (BenchmarkRawGuestInterruptible).
//
// It does NOT relax the deterministic step budget, the memory cap, the result
// validation, the poisoned result slot, or discarding an instance that
// trapped. Those are not the expensive part -- the measurement is unambiguous
// that the cost is wazero's interruptibility and the per-call deadline
// context, not the budget, which costs nothing at all for a guest that
// declares no steps. And the budget is the only bound whose failures are
// reproducible, so dropping it would mean a trusted module and an untrusted
// one could not be run against each other on the same input and compared.
//
// What it does give up is liveness: a trusted module that loops forever hangs
// its goroutine, with nothing able to stop it. That is the trade, and it is
// why this is the admin's decision and not the module's.
//
// TRUST IS NOT SOMETHING A MODULE CAN CLAIM. This field is the only input.
// Nothing in the wasm -- an export, a custom section, a name, a start
// section -- is consulted, and there is deliberately no ABI through which a
// guest could ask. A module arrives trusted because configuration said so,
// which is the only party in a position to know.
Trusted bool
}
LoadOptions are the per-module decisions an ADMIN makes about a module, as distinct from the per-process ones in Options.
type Loader ¶
type Loader struct {
// contains filtered or unexported fields
}
Loader owns a wasm runtime and the UDFs compiled into it.
LIFETIME. One Loader per process is the intended shape. A module is compiled ONCE, by Load, and every later call instantiates from the compiled form -- a compile is milliseconds and machine-code-generating, so compiling per query would cost more than any query it could speed up, and compiling per record is not a thing that could work at all. The compiled code lives as long as the Loader; Close releases it along with every instance.
CONCURRENCY. Safe for concurrent use, which it has to be: evaluation is concurrent, so one registered UDF is called from many goroutines at once. Load serializes against itself and against Close. Calls do not serialize against each other -- what they share is the compiled module, which wazero documents as safe to instantiate concurrently, and each gets an INSTANCE of its own from a pool. An instance is never shared by two calls in flight: it has one linear memory, so two concurrent calls would be writing each other's call frames, and its guest may keep state there besides.
func (*Loader) Close ¶
Close releases the runtime, every compiled module and every instance. Calls in flight fail; calls after it return ERROR with ReasonInstance rather than panicking, since a registered UDF outlives the Loader in the registry (the registry is append-only, so there is no way to withdraw it) and a closed Loader must therefore stay callable without crashing.
func (*Loader) Load ¶
func (l *Loader) Load(ctx context.Context, name string, minArgs, maxArgs int, wasm []byte) (*UDF, error)
Load compiles wasm and returns the UDF it defines, accepting minArgs..maxArgs arguments (maxArgs < 0 meaning variadic), under the name it will be registered as.
Everything checkable is checked HERE, because the alternative is one ERROR per record with no message anywhere: a missing or mistyped export, an ABI version this host does not speak, an import the host does not offer, a memory that cannot hold the call frame, and a start section that traps. Load instantiates the module once to do it, and keeps that instance as the first pooled one, so the checks cost nothing extra.
A returned error means nothing was loaded and nothing registered.
func (*Loader) LoadAggregate ¶ added in v0.37.0
LoadAggregate compiles wasm as an aggregate named name.
Everything checkable is checked here, as for a scalar UDF and for the same reason -- but an aggregate has one more thing worth proving at load, and it is proven: init is CALLED, so a module whose identity state does not fit MaxStateBytes, or that refuses to produce one at all, is a load error naming the problem rather than a query that fails later for every caller.
func (*Loader) LoadAggregateWith ¶ added in v0.37.0
func (l *Loader) LoadAggregateWith(ctx context.Context, name string, wasm []byte, lo LoadOptions) (*UDAF, error)
LoadAggregateWith is LoadAggregate with the per-module options an admin sets. An aggregate is exactly as untrusted as a function: same step budget, same memory cap, same wall-clock backstop, same meaning for Trusted.
func (*Loader) LoadWith ¶
func (l *Loader) LoadWith(ctx context.Context, name string, minArgs, maxArgs int, wasm []byte, lo LoadOptions) (*UDF, error)
LoadWith is Load with the per-module options an admin sets. See LoadOptions.
type Options ¶
type Options struct {
// MemoryLimitPages caps each guest's linear memory, in 64 KiB pages. The cap
// is hard: the guest's own memory.grow fails rather than the host noticing
// afterwards. Default 128 pages (8 MiB) -- generous for a scalar function,
// and a scalar function that needs more is doing something else.
MemoryLimitPages uint32
// Steps is the per-call budget charged through the classad_udf.fuel import.
// Default 10,000,000, which a straight-line scalar function never approaches
// and a runaway loop reaches in milliseconds. Deterministic; see the package
// comment for why that is the point and what it does not cover.
Steps uint64
// Timeout is the wall-clock backstop, the only bound that applies to a guest
// which never calls fuel. Default one second. It is deliberately far looser
// than Steps: it is there to stop a hang, not to shape semantics, and every
// millisecond of slack is a millisecond in which the reproducible limit gets
// to fire first. Zero means the default.
//
// A NEGATIVE value disables it, and disables the runtime's interruption
// support with it -- there being no deadline left to deliver. That is the
// difference between ~800ns and ~170ns per call, and it leaves an
// uninstrumented runaway able to hang its goroutine forever. It is right
// only where every loaded module is known to terminate, or under an external
// watchdog that can kill the process.
Timeout time.Duration
// RegionBytes is the host-owned window in each guest's memory holding the
// call frame: the slots plus the string arena. Default 128 KiB. Rounded up to
// whole pages, since that is the unit memory.grow works in.
RegionBytes int
// MaxResultBytes caps a string the guest returns. Default 64 KiB. A longer
// result is ERROR rather than a truncation, because a truncated string is a
// wrong answer and this is a value-producing API.
MaxResultBytes int
// MaxBatch is the largest vector batch a UDF with a vector entry point will
// be handed, and so how much of its memory the host reserves for the call
// frame. Default 4096, matching the row-group scale the engine scans at.
//
// A batch larger than this declines, which is correct (the engine falls back
// to calling per record) and slow, so the counter for it exists -- see
// ReasonBatchTooLarge.
MaxBatch int
// MaxBatchArgs sizes the vector call frame for a VARIADIC UDF, which has no
// declared maximum arity to compute from. Default 4. A UDF with a declared
// maximum ignores this and is sized from that instead, exactly.
MaxBatchArgs int
// MaxStateBytes caps one aggregate accumulator's serialized state. Default
// 16 KiB, which holds a counter set or a sketch of a few thousand bytes; an
// aggregate needing more says so here rather than being truncated, since a
// truncated state is a wrong answer.
//
// The region reserves THREE buffers this size in every aggregate instance --
// two inputs to a merge and one output -- so raising it costs three times
// what it looks like, per instance.
MaxStateBytes int
// AggBatch is how many values an accumulator buffers before one fold call.
// Default 1024.
//
// It exists because the state crosses the boundary per call: at one value per
// call the copy would dominate everything, and at 1024 it is amortized to
// nothing. Larger is not better without limit -- the values wait in host
// memory, and a batch is also the granularity at which a trap loses work.
AggBatch int
// MaxInstances bounds how many instances of one UDF exist at once, and so how
// many calls to it run concurrently; a caller past the bound waits. Default
// GOMAXPROCS, on the grounds that a UDF is CPU-bound and an instance beyond a
// core buys queueing rather than throughput. Each instance costs its guest's
// memory, so this times MemoryLimitPages is the worst case per UDF.
MaxInstances int
// OnFailure, if set, is called for every call that produced ERROR for a
// reason other than the guest's own ERROR value, with the error wazero
// reported where there was one.
//
// The counters in Stats say how often; only this says which trap. Without it
// a UDF that fails on every record is a column of ERRORs and a number, which
// is enough to know something is wrong and not enough to find it. It is
// called on the calling goroutine, so an implementation that blocks blocks a
// record.
OnFailure func(name string, r Reason, err error)
}
Options configure a Loader. A zero Options is usable: every field falls back to the default named on it.
These are per-LOADER, not per-UDF, and MemoryLimitPages could not be otherwise: wazero's memory cap is a property of the runtime, so a per-UDF limit would mean a runtime per UDF. The step and time limits could be per-UDF and are not yet; a caller needing two policies runs two Loaders, which costs one wasm runtime and shares nothing it should not.
type Reason ¶
type Reason uint8
Reason says why a call produced ERROR instead of the guest's answer.
It exists because "the UDF returned ERROR" is not one event. A trap, a step budget, a wall-clock deadline and a malformed result slot are four different problems with four different fixes, and collapsing them into one value would leave an operator with a Requirements expression that is always ERROR and nothing to look at. Keeping them apart is also what lets a test assert that a particular module hits the DETERMINISTIC limit and never the clock -- an assertion that is impossible if both arrive as the same ERROR.
A guest that deliberately returns the ClassAd value ERROR is NOT a failure and carries ReasonNone: it computed its answer, and its answer is ERROR.
const ( ReasonNone Reason = iota // ReasonArity -- argc outside the registered range. The registry checks // arity before evaluating arguments, so reaching here means a caller bypassed // it; the check is kept anyway because Call is exported. ReasonArity // ReasonUnsupportedArg -- an argument the ABI has no tag for: a list or a // nested ad. Detected before the guest runs. ReasonUnsupportedArg // ReasonArgsTooLarge -- the slots plus the string bytes do not fit the // region. ReasonArgsTooLarge // ReasonInstance -- no instance could be created (memory limit, or a start // section that traps on a later instantiation than the one load checked). ReasonInstance // ReasonTrap -- the guest trapped: unreachable, an out-of-bounds access, an // integer divide by zero, a stack overflow, a bad indirect call. ReasonTrap // ReasonStepLimit -- the guest spent its declared step budget. Deterministic. ReasonStepLimit // ReasonTimeout -- the wall-clock backstop fired. NOT deterministic, and its // separation from ReasonStepLimit is deliberate; see the package comment. ReasonTimeout // ReasonStatus -- the guest returned a nonzero status, meaning it declined to // produce a value. ReasonStatus // ReasonBadResult -- the guest reported success and left something that is // not a value: the poison tag (it never wrote the slot), an unknown tag, a // boolean payload above 1, a string pointer outside linear memory or with // bits above 32, or a string over the cap. ReasonBadResult // ReasonPanic -- something in the host call path panicked. Unreachable by // design; counted rather than assumed away, because the alternative to // counting it is a daemon dying of a bug in this package. ReasonPanic // ReasonBatchTooLarge -- the batch has more records, or more arguments, than // the region was sized for at load. Raise Options.MaxBatch or MaxBatchArgs. ReasonBatchTooLarge // ReasonBatchStrings -- an argument column holds strings or dictionary codes, // which the vector ABI does not carry. See Batch. ReasonBatchStrings // ReasonBatchShape -- the columns do not agree on a record count, a column is // shorter than it claims, the result column is not in the data form, or the // argument count is outside the registered arity. ReasonBatchShape // ReasonAggState -- an aggregate's serialized state does not fit the buffer // it was given: either the host holds one longer than MaxStateBytes, or the // guest reported writing more than the capacity it was handed. It is kept // apart from ReasonStatus, which is the guest DECLINING, because one is a // module asking for more room and the other is a module refusing the input. ReasonAggState )
The failure classes. Appending is fine; renumbering is not, because Stats snapshots are keyed by these.
type Registry ¶
type Registry interface {
RegisterFunction(name string, minArgs, maxArgs int, fn func(args []classad.Value) classad.Value) error
}
Registry is the part of classad's user-defined function registry this package needs: register a name, an arity range, and a pure function of argument values.
It is an interface for two reasons. The registry lands in package classad independently of this one, so the wiring has to compile and be testable before it exists; and a test can hand Register a registry it can inspect, which is the only way to assert that loading registers the right name with the right arity without depending on a process-wide table it cannot reset.
The method takes an UNNAMED func type so that it is satisfied by a method declared over classad.Func too -- a conversion between the two is allowed in either direction, and nothing here needs to name the registry's own type.
func ClassAdRegistry ¶
func ClassAdRegistry() Registry
ClassAdRegistry returns the process-wide registry in package classad, which is what makes a loaded module reachable from an expression: after registering through it, an expression calling the module's name gets the guest.
Use it for anything other than a test. The interface exists so a test can pass a registry it can inspect, since classad's registry is process-wide and append-only and a test cannot undo a registration in it.
type Stats ¶
type Stats struct {
// Calls counts scalar calls, INCLUDING the ones made to serve records a
// vector call declined. Batches counts vector calls, and Escalated counts the
// records inside them that went through the escape hatch.
//
// Escalated against Batches times the batch size is the number that says
// whether a vectorized UDF is earning its vector entry point: a guest
// declining most of its records is the scalar path with a vector call in
// front of it, which is slower than not having one.
Calls uint64
Batches uint64
Escalated uint64
Failures uint64
Instances uint64
ByReason map[Reason]uint64
}
Stats is a snapshot of one UDF's counters.
type UDAF ¶ added in v0.37.0
type UDAF struct {
// contains filtered or unexported fields
}
UDAF is one loaded wasm aggregate.
It is a separate type from UDF rather than a mode of it because the two share no entry point, and a module exports one set or the other. Merging them would mean every UDF carrying five nil function pointers and every load check branching on which kind it was looking at.
func RegisterAggregate ¶ added in v0.37.0
func RegisterAggregate(ctx context.Context, l *Loader, reg AggregateRegistry, name string, wasm []byte) (*UDAF, error)
RegisterAggregate loads wasm as name and registers it, so a query naming name as a user-defined aggregate reduces with the guest.
Loading comes first and registration second, which is the order that matters: every static problem with the module is a returned error here, and a name is only ever registered against a module that compiled, exports what it must, speaks this ABI, instantiated, and produced an identity state that fits. db's registry does take a withdrawal, but a name registered against an unproven module is one queries reduce with until somebody withdraws it, which is a window this order does not open.
On a registration error the aggregate stays loaded in the Loader, reachable through LookupAggregate, for the same reason a scalar UDF does: the usual cause is that the name is taken, and discarding a compiled module on the way out makes a retry under another name recompile for no reason.
func RegisterAggregateWith ¶ added in v0.37.0
func RegisterAggregateWith(ctx context.Context, l *Loader, reg AggregateRegistry, name string, wasm []byte, lo LoadOptions) (*UDAF, error)
RegisterAggregateWith is RegisterAggregate with the per-module options an admin sets. The trust label arrives HERE, from configuration, and reaches the Loader as a Go value; there is no path by which the module could influence it. An aggregate is at least as untrusted as a function and runs under the same step budget, memory cap and wall-clock backstop.
func (*UDAF) Aggregate ¶ added in v0.37.0
Aggregate returns the loaded aggregate as a db.Aggregate, ready for db.RegisterAggregate.
Its accumulators take column values -- that is, they implement db.ColumnAccumulator and the engine's columnar aggregate pass will serve them -- if and only if the module exports the numeric fold. An aggregate without it is served from the record scan, which is correct and slower, never wrong.
func (*UDAF) Columnar ¶ added in v0.37.0
Columnar reports whether the module exports the numeric fold entry point, and so whether its accumulators can be fed from a column. See AggregateOf.
type UDF ¶
type UDF struct {
// contains filtered or unexported fields
}
UDF is one loaded wasm function.
func Register ¶
func Register(ctx context.Context, l *Loader, reg Registry, name string, minArgs, maxArgs int, wasm []byte) (*UDF, error)
Register loads wasm as name and registers it, so an expression calling name gets the guest.
Loading comes first and registration second, which is the order that matters: every static problem with the module is a returned error here, and a name is only ever registered against a module that compiled, exports what it must, speaks this ABI, and has been instantiated and called once. A registration is not withdrawable -- compiled programs capture the strict/delegated decision for a name, so a name that has been seen cannot stop existing -- so registering something unproven is not a mistake that can be taken back.
On a registration error the UDF stays loaded in the Loader, reachable through Lookup. It is not unloaded, because the usual reason for the error is that the name is taken, and silently discarding a compiled module on the way out of a failed call makes a retry under another name recompile for no reason.
func RegisterWith ¶
func RegisterWith(ctx context.Context, l *Loader, reg Registry, name string, minArgs, maxArgs int, wasm []byte, lo LoadOptions) (*UDF, error)
RegisterWith is Register with the per-module options an admin sets.
It is a separate function rather than a changed signature because the registry is append-only and so is this API: a caller already registering UDFs keeps compiling. The trust label arrives HERE, from configuration, and reaches the Loader as a Go value -- there is no path by which the module being registered could influence it.
func (*UDF) Call ¶
Call runs the UDF.
It returns a ClassAd value, always, for every input and every way a guest can misbehave. The classification:
the guest wrote a value that value, including its own UNDEFINED/ERROR a list or nested-ad argument ERROR, before the guest runs arguments too large for the region ERROR, before the guest runs a trap ERROR, and the instance is discarded the step budget ERROR, and the instance is discarded the wall-clock deadline ERROR, and the instance is discarded a nonzero status ERROR a result slot that is not a value ERROR a panic anywhere in this path ERROR, and the instance is discarded
No input makes it panic and no input makes it return an invalid value. That is not politeness: a UDF is called from inside expression evaluation, which a daemon runs with no top-level recover, so a panic here would be a daemon dying one match at a time -- and an invalid value would be a wrong answer, which is worse than an ERROR an operator can see.
func (*UDF) CallBatch ¶
CallBatch runs the UDF over a whole batch of records at once.
args are the argument columns, out is the column to fill. Every column is N elements long, or one element with Const set. out must be in the data form and its St/I must already be allocated: it is the engine's own result vector, and allocating a replacement here would take it out of the pool it is recycled from.
ok=false means DECLINED, not failed: the caller should fall back to calling Call once per record, which is what the engine does for any built-in it cannot vectorize. A decline is not an error and no record gets a value from it. The reasons are a module with no vector entry point, a batch wider than the frame the region was sized for, a batch containing strings (see Batch), and a malformed batch. Each is counted, because "the vector path is off" otherwise shows up only as a query being slower than it should be.
A declined batch may have left SOME elements of out written. That matches the engine's own rule for a call it cannot complete -- ok=false declines the whole evaluation and the vector is discarded, never read as a partial answer -- so there is nothing to clean up, but a caller that kept reading out after a false would be reading a mixture of two answers.
ok=true means every element of out holds a value, with no exceptions:
- records the guest computed hold what the guest computed
- records the guest DECLINED hold what the scalar entry point computed for them, one at a time, through exactly the path Call uses
- if the vector call itself failed -- a trap, the step budget, a bad result slot -- every record holds ERROR
That last case does NOT fall back to the scalar path, deliberately. A guest that trapped halfway through a batch would otherwise produce an answer on the retry and an ERROR without it, so the same input would give different results depending on a failure the caller cannot see. And the decline mask a dead guest left behind means nothing, so there is no honest way to know which records it claimed.
func (*UDF) Func ¶
Func returns the UDF as the registry's function type: a pure function of its argument values, with no evaluator and no error return, because every failure it can have is already a ClassAd value.
func (*UDF) Stats ¶
Stats snapshots the counters. The fields are read independently, so a snapshot taken while calls are in flight can be internally inconsistent by a call or two; it is for operators and tests, not for accounting.