UDFs, WASM & Custom Aggregates

Scalar and table-valued functions, deterministic sandboxed WebAssembly modules (LANGUAGE wasm), and parallel user-defined aggregates.

6 min read Programmability

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:

sql
-- 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:

sql
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) and normalize(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#

sql
-- 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:

sql
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, or CALL mutations 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:

sql
-- 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 TypeWASM Value TypeEncoding Convention
bool, u8, u16, i8, i16, i32i32Two's-complement / unsigned integer (bool: non-zero → true)
u32, u64, i64i6464-bit integer bits
datei64Signed days since Unix epoch (1970-01-01)
timestampi64Signed microseconds since Unix epoch (1970-01-01T00:00:00Z)
f32f32IEEE-754 single-precision float
f64f64IEEE-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:

rust
// 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#

ConstraintLimitRationale
WASM specificationWebAssembly 1.0 MVP (\0asm\x01\0\0\0) + bulk memory, sign-extension, saturating float-to-intSingle-pass validation and bounded decode without JIT overhead
Host imports (Section 2)Forbidden (0 allowed)Zero filesystem, network, clock, or syscalls
Start sectionForbiddenNo implicit execution during module load
Max module / bundle size1 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 memory256 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 budget1,000,000 instructions per call (including bulk memory and memory.grow charges)Terminates infinite loops and allocation floods cleanly
Call depth & stack depth64 WASM frames / 4,096 operand stack entriesPrevents stack overflow inside WASM
Module cache & VM pool256 decoded modules capped at 128 MiB (LRU); global VM pool capped at 32 instances / 64 MiBAmortizes 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):

sql
-- 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#

sql
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#

  1. null inputs are skipped before calling step / SFUNC.
  2. Empty groups still produce one output value: init / INITCOND is evaluated and passed directly through final (or FINALFUNC) if specified.
  3. Distributed merging: When combine is present in a SpydQL aggregate, partial states accumulated across partitions or workers can be combined before final runs. Without combine, exact sequential state folding is used.

5. Inspecting & Managing Catalog Routines#

Drop routines atomically when retiring schemas or signatures:

sql
drop function if exists net_total;
drop aggregate if exists sum_sq_avg;

Or in SQL:

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)):

sql
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 ... FROM resolves bundles strictly inside the configured extension_dir after canonicalization (preventing path traversal and symlink escapes).
  • ALTER EXTENSION ... UPDATE enforces monotonic MAJOR.MINOR.PATCH upgrades unless ALLOW DOWNGRADE is supplied, and refuses updates that break callers when export signatures change.
  • DROP EXTENSION refuses to drop while tables, views, materialized views, triggers, transforms, pipelines, or streams depend on exported functions (CASCADE does not drop dependent objects; drop or alter dependents first).
  • Inspect installed extensions with SHOW EXTENSIONS;, SELECT * FROM pg_catalog.pg_extension;, or SpydQL system | stats extensions.

HTTP Admin & Multi-Node Guard#

  • GET /v1/admin/extensions lists installed extensions and their live allowed_by_policy state.
  • POST /v1/admin/extensions installs or updates a base64-encoded bundle ({ bundle_base64, update, if_not_exists, allow_downgrade }).
  • DELETE /v1/admin/extensions/{name}?cascade=bool&if_exists=bool removes an extension.
  • Server configuration exposes extension_dir, extension_trusted_keys, extension_revoked_keys, extension_revoked_digests, allow_unsigned_extensions, and wasm_memory_budget_bytes.
  • On distributed queries, coordinators attach X-Spyd-Extensions and shard nodes reject mismatched versions or digests with HTTP 409 (extension_mismatch).