UDFs, WASM & Custom Aggregates
Scalar and table-valued functions, deterministic sandboxed WebAssembly modules (LANGUAGE wasm), and parallel user-defined aggregates.
SpydDB evaluates user-defined logic directly inside the query engine so transformations, scoring formulas, table generators, and custom aggregations run adjacent to MVCC storage with zero round-trip serialization overhead.
All four extension mechanisms share unified schema persistence, polymorphic overloading by parameter signature, and transactional rollback on CREATE / DROP.
1. Scalar User-Defined Functions (CREATE FUNCTION)#
Scalar functions accept typed inputs and return a single typed scalar value (or null). They can be authored in three forms: SpydQL expression functions, SpydQL procedural blocks, or PostgreSQL SQL / PL/pgSQL functions.
Expression & Procedural SpydQL Functions#
Inside SpydQL UDF bodies, read parameters and declared local variables using $name:
-- Single-expression scalar function
create or replace function net_total(subtotal: decimal(12, 2), tax_rate: f64) -> f64
as cast($subtotal as f64) * (1.0 + $tax_rate);
-- Multi-statement procedural block function with locals and early return
create or replace function tier_discount_bps(spend: i64, vip: bool) -> i32 as {
if $vip and $spend >= 100000 {
return 1500;
} else if $spend >= 50000 {
return 750;
}
return 0;
};PostgreSQL Dialect (LANGUAGE sql & LANGUAGE plpgsql)#
Clients connecting over PostgreSQL Wire, SpydWire, or HTTP can also declare functions using standard PostgreSQL dollar-quoted DDL:
CREATE OR REPLACE FUNCTION clamp_score(val double precision, lo double precision, hi double precision)
RETURNS double precision
LANGUAGE plpgsql
AS $$
BEGIN
IF val < lo THEN
RETURN lo;
ELSIF val > hi THEN
RETURN hi;
END IF;
RETURN val;
END;
$$;Polymorphic Overloading & Recursion Guards#
- Overloading: Multiple functions can share a name as long as their parameter arity or parameter types differ (for example
normalize(x: i64)andnormalize(x: text)). - Recursion cap: Recursive scalar UDF invocation is bounded by an engine call-depth ceiling of 64 frames to prevent stack exhaustion on cyclic inputs.
- Purity constraint: Scalar UDFs reject table mutations and transaction control statements at DDL creation time.
2. Table-Valued Functions (RETURNS TABLE)#
Table-Valued Functions (TVFs) emit a relational stream of typed rows that can appear directly as the source of a SpydQL pipeline or in a SQL FROM clause.
Query-Backed & Procedural SpydQL TVFs#
-- Direct pipeline-backed TVF (no outer parentheses around the pipeline)
create or replace function recent_tenant_orders(tid: string, min_total: i64)
-> table(id: i64, customer: text, total: i64) as
orders
| where tenant_id == $tid and total >= $min_total
| sort created_at desc
| pick id, customer, total
| take 100;
-- Procedural block TVF emitting rows via return query
create or replace function match_orders(min_amt: f64)
-> table(oid: i64, cust: text) as {
return query orders | where amount >= $min_amt | sort id | pick id, customer;
};
-- Call as a pipeline root
recent_tenant_orders("acme", 5000) | sort id asc;Procedural Row-Generating TVFs (RETURN NEXT / RETURN QUERY)#
Use comma-separated expressions with RETURN NEXT (no outer tuple parentheses) or stream a SQL query with RETURN QUERY inside LANGUAGE plpgsql:
CREATE OR REPLACE FUNCTION generate_buckets(start_n integer, count_n integer)
RETURNS TABLE(bucket_id integer, bucket_label text)
LANGUAGE plpgsql
AS $$
DECLARE
i integer := 0;
BEGIN
WHILE i < count_n LOOP
RETURN NEXT start_n + i, 'b-' || (start_n + i)::text;
i := i + 1;
END LOOP;
RETURN;
END;
$$;
-- Query via SQL or SpydQL
SELECT * FROM generate_buckets(10, 4);Note: Table-valued functions are strictly read-only. Attempted
INSERT,UPDATE,DELETE,MERGE, orCALLmutations inside a TVF body are rejected at execution time; use a stored procedure when transactional side effects are required.
3. Sandboxed WebAssembly UDFs (LANGUAGE wasm)#
For compute-intensive kernels—custom hashing, financial pricing models, bitpacking, scoring math, or domain codecs—SpydDB embeds a zero-dependency WebAssembly 1.0 MVP virtual machine. Compiled modules run in an isolated sandbox with deterministic fuel metering.
Defining a WASM Function#
Provide the compiled .wasm binary payload encoded as hexadecimal (0x... or \x...) or Base64 (whitespace inside multi-line string literals is ignored). In SpydQL, add entry "<export_name>" to bind any exported symbol name; in PostgreSQL SQL syntax, the exported WASM symbol matches the function name:
-- SpydQL syntax with explicit exported WASM symbol name
create or replace function w_calc(a: i64, b: i64) -> i64
language wasm entry "calc" as "0x0061736d01000000...";
-- PostgreSQL SQL syntax (exports function matching `w_quad`)
CREATE OR REPLACE FUNCTION w_quad(y double precision)
RETURNS double precision
LANGUAGE wasm
AS 'AGFzbQEAAAABBwFgAXwBAXwDAgEABwoBAXdfcXVhZAAACg0BCwAgACAAQgAA...';Exact Type ABI Mapping#
| SpydDB Type | WASM Value Type | Encoding Convention |
|---|---|---|
bool, u8, u16, i8, i16, i32 | i32 | Two's-complement / unsigned integer (bool: non-zero → true) |
u32, u64, i64 | i64 | 64-bit integer bits |
date | i64 | Signed days since Unix epoch (1970-01-01) |
timestamp | i64 | Signed microseconds since Unix epoch (1970-01-01T00:00:00Z) |
f32 | f32 | IEEE-754 single-precision float |
f64 | f64 | IEEE-754 double-precision float |
Null short-circuiting: If any argument evaluates to null, the runtime returns null directly without entering the WebAssembly VM.
Authoring in Rust for SpydDB WASM UDFs#
Compile pure numeric kernels with #[no_mangle] and target wasm32-unknown-unknown:
// Compile with: rustc --target wasm32-unknown-unknown --crate-type cdylib -O risk.rs
#[no_mangle]
pub extern "C" fn calc(a: i64, b: i64) -> i64 {
a.saturating_mul(2).saturating_add(b)
}Deterministic Sandbox Limits#
| Constraint | Limit | Rationale |
|---|---|---|
| WASM specification | WebAssembly 1.0 MVP (\0asm\x01\0\0\0) + bulk memory, sign-extension, saturating float-to-int | Single-pass validation and bounded decode without JIT overhead |
Host imports (Section 2) | Forbidden (0 allowed) | Zero filesystem, network, clock, or syscalls |
| Start section | Forbidden | No implicit execution during module load |
| Max module / bundle size | 1 MiB inline UDF (1,048,576 bytes); 4 MiB module inside .spydext bundles (4 MiB + 128 KiB max bundle, 64 KiB manifest) | Bounded catalog storage and parse cost |
| Max linear memory | 256 pages (16 MiB) (64 KiB / page); 512 MiB default aggregate budget across active & pooled VMs (wasm_memory_budget_bytes) | Bounded per-instance and server-wide memory usage |
| Execution fuel budget | 1,000,000 instructions per call (including bulk memory and memory.grow charges) | Terminates infinite loops and allocation floods cleanly |
| Call depth & stack depth | 64 WASM frames / 4,096 operand stack entries | Prevents stack overflow inside WASM |
| Module cache & VM pool | 256 decoded modules capped at 128 MiB (LRU); global VM pool capped at 32 instances / 64 MiB | Amortizes decode and allocation across scans without unbounded memory retention |
4. Custom Aggregates (CREATE AGGREGATE)#
Define stateful reducers that work inside group by ... | agg ..., whole-collection summaries, parallel sharded scans, and SQL SELECT lists.
SpydQL Custom Aggregate Syntax#
Supply state <type> -> <return_type>, init, step (binds $state and $value), optional combine for parallel/distributed partial aggregation (binds $left and $right), and optional final (binds $state):
-- Mean-of-squares aggregate using JSON accumulator state
create or replace aggregate sum_sq_avg(i64)
state json -> f64
init { s: 0.0, c: 0 }
step {
s: cast($state["s"] as f64) + cast($value * $value as f64),
c: cast($state["c"] as i64) + 1
}
combine {
s: cast($left["s"] as f64) + cast($right["s"] as f64),
c: cast($left["c"] as i64) + cast($right["c"] as i64)
}
final case
when cast($state["c"] as i64) == 0 then cast(0.0 as f64)
else cast($state["s"] as f64) / cast($state["c"] as i64)
end;
-- Invoke inside a SpydQL `group by ... | agg ...` pipeline
nums | group by grp | agg sum_sq_avg(val) as msq | sort grp;PostgreSQL SQL Aggregate Syntax#
CREATE OR REPLACE FUNCTION prod_step(acc bigint, x bigint)
RETURNS bigint
LANGUAGE sql
AS $$ SELECT acc * x $$;
CREATE AGGREGATE product_agg(bigint) (
SFUNC = prod_step,
STYPE = bigint,
INITCOND = '1'
);
SELECT grp, product_agg(val) AS p FROM nums GROUP BY grp ORDER BY grp;Aggregate Semantics#
nullinputs are skipped before callingstep/SFUNC.- Empty groups still produce one output value:
init/INITCONDis evaluated and passed directly throughfinal(orFINALFUNC) if specified. - Distributed merging: When
combineis present in a SpydQL aggregate, partial states accumulated across partitions or workers can be combined beforefinalruns. Withoutcombine, exact sequential state folding is used.
5. Inspecting & Managing Catalog Routines#
Drop routines atomically when retiring schemas or signatures:
drop function if exists net_total;
drop aggregate if exists sum_sq_avg;Or in SQL:
DROP FUNCTION IF EXISTS clamp_score;
DROP AGGREGATE IF EXISTS product_agg;6. Signed .spydext Extensions#
For versioned, multi-function WASM packages, SpydDB supports .spydext bundles verified against Ed25519 signing keys (extension_trusted_keys) and server revocation lists (extension_revoked_keys, extension_revoked_digests). Production servers (environment = "production") refuse unsigned bundles (allow_unsigned_extensions).
Today, .spydext bundles support numeric scalar exports (abi_version = 0): bool, signed/unsigned 8–64-bit integers, f32, f64, date, and timestamp with strict SQL NULL handling. Rich SPD2 types (abi_version = 1 / spyd_ext_v1), host imports, TVFs, and WASM aggregates remain planned.
DDL & Inspection#
Installing, updating, or dropping an extension requires manage database(extensions) (separate from manage database(security)):
CREATE EXTENSION IF NOT EXISTS math_ext VERSION '1.0.0' FROM 'math_ext-1.0.0.spydext';
ALTER EXTENSION math_ext UPDATE TO '1.1.0' FROM 'math_ext-1.1.0.spydext';
DROP EXTENSION math_ext RESTRICT;CREATE EXTENSION ... FROMresolves bundles strictly inside the configuredextension_dirafter canonicalization (preventing path traversal and symlink escapes).ALTER EXTENSION ... UPDATEenforces monotonicMAJOR.MINOR.PATCHupgrades unlessALLOW DOWNGRADEis supplied, and refuses updates that break callers when export signatures change.DROP EXTENSIONrefuses to drop while tables, views, materialized views, triggers, transforms, pipelines, or streams depend on exported functions (CASCADEdoes not drop dependent objects; drop or alter dependents first).- Inspect installed extensions with
SHOW EXTENSIONS;,SELECT * FROM pg_catalog.pg_extension;, or SpydQLsystem | stats extensions.
HTTP Admin & Multi-Node Guard#
GET /v1/admin/extensionslists installed extensions and their liveallowed_by_policystate.POST /v1/admin/extensionsinstalls or updates a base64-encoded bundle ({ bundle_base64, update, if_not_exists, allow_downgrade }).DELETE /v1/admin/extensions/{name}?cascade=bool&if_exists=boolremoves an extension.- Server configuration exposes
extension_dir,extension_trusted_keys,extension_revoked_keys,extension_revoked_digests,allow_unsigned_extensions, andwasm_memory_budget_bytes. - On distributed queries, coordinators attach
X-Spyd-Extensionsand shard nodes reject mismatched versions or digests with HTTP409(extension_mismatch).