Window Functions, Rollups & JIT

Analytical window partitions and frames, GROUPING SETS / ROLLUP / CUBE, UNNEST, hyperloglog/t-digest sketches, and LLVM/Cranelift JIT.

3 min read SpydQL & Data Modeling

SpydDB pairs transactional MVCC writes with vectorized analytical execution: full ANSI/PostgreSQL window functions with disk spilling, multi-dimensional ROLLUP / CUBE / GROUPING SETS, streaming approximate sketches, array unnesting, SQL set operations, in-engine regression fitting (ml_train), and a native Cranelift JIT predicate/expression compiler.


1. Window Functions & Analytic Frames (window)#

Unlike group by, a window stage computes aggregate, ranking, or positional values across related partition rows while preserving every input row:

Important — SpydQL ordering keyword: Inside a SpydQL window specification, sort expressions use sort by (for example over (partition by dept sort by -score) or sort by salary desc), whereas standard SQL over pgwire uses ORDER BY.

sql
orders
| window
    row_number() over (partition by region sort by -amount) as rn,
    rank()       over (partition by region sort by -amount) as r,
    dense_rank() over (partition by region sort by -amount) as d,
    sum(amount)  over (
      partition by region
      sort by created_at
      rows between unbounded preceding and current row
    ) as running_total,
    lag(amount, 1, 0)  over (partition by region sort by created_at) as prev_amount,
    lead(amount, 1, 0) over (partition by region sort by created_at) as next_amount,
    first_value(amount) over (
      partition by region
      sort by created_at
      rows between 1 preceding and current row
    ) as win_first,
    last_value(amount) over (
      partition by region
      sort by created_at
      rows between 1 preceding and current row
    ) as win_last
| sort region, rn
| pick id, region, rn, r, d, running_total, prev_amount, next_amount, win_first, win_last;

Supported Functions & Complexity Guarantees#

CategoryFunctionsImplementation
Rankingrow_number(), rank(), dense_rank()Sorted peer-aware partition pass
Offset / Valuelag(expr [, offset [, default]]), lead(expr [, offset [, default]]), first_value(expr), last_value(expr)Direct frame indexing
Framed Aggregatescount, sum, avg, min, maxPrefix sums (O(1) per row for additive aggregates) and segment trees (O(log N) for min/max)

Frame Clauses (ROWS & RANGE)#

  • rows between <start> and <end>: Positional row offsets (unbounded preceding, <n> preceding, current row, <n> following, unbounded following).
  • range between <start> and <end>: Peer-value bounds over single numeric or temporal sort by keys (matching SQL RANGE semantics, including the default RANGE UNBOUNDED PRECEDING TO CURRENT ROW frame when sort by is present without an explicit frame).
  • Large-partition spilling: Partitions that exceed query memory spill transparently to disk (WindowSpill) and clean up on completion or error.

2. Multi-Dimensional Grouping (ROLLUP, CUBE, GROUPING SETS)#

Compute multi-level subtotals and grand totals in a single scan without UNION ALL:

sql
-- Hierarchical subtotals: (region, product), (region), and grand total ()
sales
| group by rollup (region, product)
| agg count() as n, sum(amount) as revenue, max(amount) as top;

-- Full cross-tab combinations
sales
| group by cube (region, product)
| agg count() as n, sum(amount) as revenue;

-- Explicit custom grouping combinations
sales
| group by grouping sets ((region, product), (region), ())
| agg count() as n;

Modifiers cube, rollup, and grouping sets are contextual—columns named cube or rollup still parse unambiguously when listed as ordinary keys (| group by cube, rollup).


3. Approximate Analytics (approx_count_distinct, approx_percentile)#

When sub-second cardinality or latency quantile queries span millions of rows:

  • approx_count_distinct(expr): Uses a 4096-register HyperLogLog sketch (standard relative error ~1.63%, deterministic across row order and across row vs. PAX columnar scans).
  • approx_percentile(expr, q): Uses a streaming t-digest / rank-bounded sketch returning values within 1% rank error (q = 0 and q = 1 are exact min/max).
sql
events
| group by tenant_id
| agg
    approx_count_distinct(user_id) as approx_dau,
    approx_percentile(latency_ms, 0.99) as p99_ms
| sort p99_ms desc;

4. In-Engine ML Model Fitting (ml_train)#

Fit deterministic regression models directly over query partitions without exporting training sets:

sql
-- Each vector element[0] holds target y, element[1..] hold features
training_rows
| group by cohort
| agg ml_train(features) as model_json
| sort cohort;

The returned JSON model string (Linear weights + bias) can be passed directly into ml_score(model_json, f1, ...) in subsequent pipelines or stored in a catalog metadata collection.


5. Set Operations & UNNEST#

Combining Result Sets#

Both SpydQL pipelines and SQL queries support duplicate-eliminating and bag-preserving set combinators:

  • union / union all
  • intersect / intersect all
  • except / except all
sql
(active_customers | pick email)
except
(suppressed_recipients | pick email)
| sort email;

Flattening Typed Arrays (unnest)#

sql
articles
| unnest tags as tag
| group by tag
| agg count() as article_count
| sort article_count desc;

6. Cranelift Native JIT & Columnar Acceleration#

Whenever a query filters or projects eligible expressions, SpydDB's expression compiler automatically lowers hot predicates and arithmetic into native x86_64/ARM64 machine code via Cranelift (Native::compile):

  • JIT-compiled primitives: Comparisons on numeric columns and literals, SQL three-valued boolean logic (and, or, not), signed integer arithmetic (+, -, *), unary negation, is null / is not null, numeric in lists, and numeric between ranges.
  • Zero-allocation calling convention: Evaluates row pointers (*const i64, *const u8 null bitmap) in registers across parallel table/columnar scan workers.
  • Exact parity & transparent fallback: If a value triggers signed integer overflow or hits an unmodeled type, the compiled routine returns a FALLBACK tag and re-evaluates identically using the bytecode interpreter—guaranteeing JIT optimization never changes query semantics.
  • PAX Columnar SIMD: Pair analytical tables with store column for (...) so scans, filters, and aggregates operate over cache-aligned columnar vectors automatically.