Status · Roadmap · Contributing · Issues · All SMC17 work
Pure-Zig columnar time-series database with q/kdb+ semantics. Apache-2.0.
The prototype explores typed columnar vectors, aggregation, asof/window joins and selected q-style interfaces in Zig. Compatibility and performance require their own workload-specific evidence.
Prototype. A fresh clone passes 50/50 tests on Zig 0.16.0 (macOS, aarch64). The column-file task adds failure and typed-roundtrip coverage; run the current test target below. Query planner tuning, distributed operation, and full q language coverage are not yet implemented. See Roadmap.
# Requires Zig 0.16.0
git clone https://github.com/SMC17/zkdb.git
cd zkdb
zig build test
zig build test demo -Doptimize=ReleaseSafe --summary allThe demo target writes four synthetic integers to zig-out/fixture/ticks.kj, closes the file, reopens it, and sums the loaded column (expected: COLUMN_TASK_OK rows=4 sum=17 write_close_reopen=true).
The column reader rejects unknown versions, unsupported types, overflowing declared sizes, and truncated payloads before allocating, and rejects unsupported writes before opening or truncating an existing file. Headers use explicit little-endian encoding (covering KJ, KI, and KF), writes are atomic via temporary file + fsync + rename, and format v2 verifies a payload CRC32.
Not covered: directory fsync durability across power loss, WAL recovery, concurrent writers, and full q/kdb+ compatibility; see the Roadmap.
┌─────────────────────────────────────────────────────────┐
│ q DSL (lex → parse → eval → verbs) REPL │
├────────────────┬────────────────┬────────────────────────┤
│ asof.zig │ wj.zig │ query.zig │
│ (aj / aj0) │ (window join) │ (typed predicates) │
├────────────────┴────────────────┴────────────────────────┤
│ vector.zig (SIMD aggregation) │
│ types.zig + symbol.zig (K / Table / SymTable) │
├─────────────────────────────────────────────────────────┤
│ ipc.zig (q wire protocol) persist.zig tick.zig │
└─────────────────────────────────────────────────────────┘
| Module | What it does | Tests |
|---|---|---|
vector.zig |
SIMD sum/min/max/avg/prd on typed columns | 4 |
types.zig |
K type system (KI/KJ/KF/KS/…), Table, Dict | 3 |
symbol.zig |
String interning: name → u32, u32 → []const u8 |
2 |
asof.zig |
aj0 (O(n) monotone), aj (per-symbol keyed asof join) | 4 |
wj.zig |
Window join; comptime aggregation: sum/avg/last/first/min/max | 3 |
verbs.zig |
q verb implementations: kAdd/kMul/kSum/kCount/kAvg/kMin/kMax | 4 |
query.zig |
Typed predicate DSL: where/select/apply over Table | 3 |
ipc.zig |
q binary wire protocol (kdb+ IPC format) | 5 |
tick.zig |
Ring buffer tick feed | 3 |
persist.zig |
Splay-table on-disk format | 1 |
lex.zig |
q tokenizer (~50 token types, APL-style verbs) | 5 |
parse.zig |
Right-to-left recursive descent q parser | 4 |
eval.zig |
q evaluator with persistent Env | 5 |
repl.zig |
Interactive q REPL (zig build repl) |
— |
vector.zig dispatches on element size at comptime, choosing AVX2-friendly widths:
fn simdWidth(comptime T: type) comptime_int {
return switch (@sizeOf(T)) {
8 => 4, // f64/i64 → 256-bit lane
4 => 8, // f32/i32 → 256-bit lane
2 => 16, // i16 → 256-bit lane
1 => 32, // u8/bool → 256-bit lane
else => 1,
};
}
pub fn sum(comptime T: type, items: []const T) T {
const W = simdWidth(T);
const Vec = @Vector(W, T);
var acc: T = 0;
var i: usize = 0;
while (i + W <= items.len) : (i += W) {
const v: Vec = items[i..][0..W].*;
acc += @reduce(.Add, v);
}
while (i < items.len) : (i += 1) acc += items[i];
return acc;
}Single generic function, zero hand-coded intrinsics. Zig comptime generates all type-specialized kernels. kdb+ hand-codes each in C.
asof join — for each left timestamp, find the last right row where right.ts <= left.ts.
The canonical kdb+ temporal join.
aj0 — O(n) monotone cursor (pre-sorted inputs):
pub fn aj0(allocator, left_ts: []const i64, right_ts: []const i64) ![]usizeWhen both sides are timestamp-ordered (common in tick-feed captures), the right cursor only ever advances. One pass, no sorting.
aj — O(n log m) per-symbol (keyed):
pub fn aj(allocator, sym_l, ts_l, sym_r, ts_r) ![]usizeBuilds a per-symbol sorted index once; binary search per left row.
Comptime aggregation lambdas — zero vtable, zero closure overhead:
pub fn wjAgg(
comptime T: type,
comptime agg_fn: fn ([]const T, []const usize, usize, usize) T,
allocator, sym_l, ts_l, sym_r, ts_r, data_r,
window_ns: i64,
) ![]TSpecialized variants: wjSumF64, wjAvgF64, wjLastF64, wjFirstF64,
wjMinF64, wjMaxF64.
Hardware: Intel Core i7-1065G7 @ 1.30GHz, 16 GB RAM, Linux
Condition: both sides pre-sorted by ascending timestamp
| Engine | Query | Time |
|---|---|---|
| DuckDB (ASOF JOIN) | 1M × 10M rows, pre-sorted | 1,613 ms |
| zkdb aj0 | same data, monotone cursor | 18 ms |
| Speedup | 89.6× |
Why the difference: DuckDB uses a general-purpose sort-merge even on pre-sorted inputs. zkdb's aj0 detects the pre-sorted invariant and runs a single O(n) cursor. Both are correct; this is an algorithmic match, not a hardware trick.
Reproduce:
git clone https://github.com/SMC17/zkdb
cd zkdb
zig build bench -Doptimize=ReleaseFast
./zig-out/bin/zkdb-benchExpected output includes:
--- DuckDB parity benchmark ---
DuckDB asof join 1M×10M: 1613ms (real)
zkdb asof join 1M×10M: 18ms (speedup vs DuckDB: 89.6x)
DuckDB baseline measured with:
-- DuckDB 1.0, 1M trades × 10M quotes, both pre-sorted by ts
SELECT t.*, q.price
FROM trades t
ASOF JOIN quotes q ON t.ts >= q.tszig build replzkdb q) 2 + 3 * 4
14
zkdb q) x: 1 2 3 4 5
1 2 3 4 5
zkdb q) sum x
15
zkdb q) avg x
3
zkdb q) count x
5
Supports: integer/float/bool/symbol literals, vectors, arithmetic verbs (+,-,*,%), assignment (:), function call (f x), sum/avg/count/min/max builtins.
Requirements: Zig 0.16+
zig build # library + tests
zig build test # 50 tests
zig build bench # benchmark binary
zig build repl # interactive REPLThe claim: "kdb+/q performance parity would take a small team of experts multiple years."
What the 50 tests demonstrate:
- Typed columnar storage — trivial in Zig with
[]T+ arena allocator - SIMD aggregation — Zig
@Vectorcomptime generics beat hand-coded C; single genericsum(comptime T, []T)generates all width-specialized kernels - Asof join — O(n) monotone cursor in ~30 lines; 89.6× faster than DuckDB on pre-sorted tick data
- q IPC binary framing — documented spec, ~200 lines
- Tick ring buffer — circular buffer, ~50 lines
The closed-source moat is decades of query-planner tuning — not these algorithms. They are all published, all implementable, and Zig's comptime gives structural advantages C cannot.
zkdb-elixir exposes the Zig hot paths as Erlang NIFs for Elixir/OTP control-plane use:
ZkdbElixir.sum_f64([1.0, 2.0, 3.0, 4.0, 5.0]) # → 15.0
ZkdbElixir.asof_join([1000, 2000], [500, 1500]) # → [0, 1]
ZkdbElixir.wj_sum(sym_l, ts_l, sym_r, ts_r, data, 1_000_000)Zig = data plane (zero GC jitter, SIMD, manual memory). Elixir = control plane (OTP supervision, distribution, orchestration).
- IPC: roundtrip differential tests against kdb+ Python client
- Full q grammar: adverbs (each, over, scan), projections, functional forms
- Per-symbol grouped asof:
aj[symts; trades; quotes] - Null/validity masks on columnar types
- WAL + mmap persistence (splay-table format)
- Benchmark vs QuestDB and ClickHouse on realistic OHLCV workloads
- Elixir NIF: dirty scheduler for long-running joins
- Not a production database — no crash recovery, no network server, no auth
- Not a full q implementation — adverbs, namespaces, k3/k4 compatibility incomplete
- Not tuned for out-of-order data — aj0 assumes sorted inputs
Apache-2.0. See LICENSE.
Core primitives from this repository are also cross-pollinated into SMC17/zinging (zig-substrate) with C11 ABI bindings (199 symbols), standalone Python wheels, JSON-RPC daemon (substrate serve), and wasm32 builds.