Capabilities, Concurrency & GPU
Clever replaces ambient authority, unbounded thread spawning, and opaque GPU fallbacks with explicit capabilities, deterministic simulation, structured concurrency, and statically checked GPU kernels.
Capabilities: Zero Ambient Authority
In Clever, ordinary functions cannot read the filesystem, open sockets, inspect the clock, or draw random bytes. Authority enters a program in one place only: main(io: Io).
Io destructures into fine-grained capability values:
val (out, err, inp, fs, clock, rng, net, args) = ioOut(out,err) — write bytes / lines /U64to stdout or stderrIn(inp) — read bytes from stdinFs(fs) — confined filesystem access (no symlink or..escape outside--root)Clock(clock) — monotonic clock (now()) and wall clock (wallNow())Rng(rng) — random bytes /U64Net(net) — TCP listen/dial, socket pairs, and non-blocking event polling (poller/watch/wait)Args(args) — command-line arguments and explicit environment variables
Because capabilities are affine values, passing only out and clock to a helper statically guarantees it can never touch the filesystem or network:
fun greet(out: &mut Out, clock: &mut Clock, rng: &mut Rng) {
val t = clock.now()
val r = rng.nextU64()
out.write(b"tick=")
out.printU64(t)
out.write(b"rand=")
out.printU64(r)
}
fun main(io: Io) {
val (out, _, _, _, clock, rng, _, _) = io
greet(out, clock, rng)
}Deterministic Replay & Simulation
Every world capability can be controlled from the CLI so runs are bit-for-bit reproducible across interpreter, C, and Wasm:
clever run app.clv main --clock 1000 --seed 42 --root ./sandbox --net transcript.net --env MODE=test -- --port 6379--clock Tsets the initial monotonic clock value--seed SseedsRngand the deterministic task scheduler--root DIRconfinesFstoDIR--net FILEreplays a recorded network oracle transcript--env K=Vexposes only the listed environment variables (nothing else from the host environment is visible)
Data Parallelism (par for)
par for partitions one or more slices/buffers into disjoint fixed-size chunks with .chunksExact(N). Ownership guarantees each iteration accesses only its own mutable chunk, so par for is provably race-free and equivalent to its sequential loop:
export fun scaleChunks(out: &mut Slice<U64>, src: &Slice<U64>, factor: U64) {
par for (i, dst in out.chunksExact(2), inp in src.chunksExact(2)) {
dst[0] = inp[0] *% factor +% i
dst[1] = inp[1] *% factor +% i
}
}Control the native thread pool with CLEVER_THREADS=N (or link with -DCLEVER_RT_SEQUENTIAL for a zero-pthread sequential build).
Structured Concurrency (suspend, scope, spawn)
Cooperative concurrent functions are marked suspend fun. Tasks can only be spawned inside a scope { ... } block, and every spawned task finishes before the scope exits — tasks can never escape their scope or dangle over borrowed parent data.
fun sq(x: U64): U64 = x *% x
export suspend fun fanOut(a: U64, b: U64): U64 {
var left = [0u64; 2]
var right = [0u64; 2]
scope {
val t1 = spawn {
left[0] = sq(a)
left[1] = sq(a +% 1u64)
left[0] +% left[1]
}
val t2 = spawn {
right[0] = sq(b)
right[1] = sq(b +% 1u64)
right[0] +% right[1]
}
t1.await() +% t2.await()
}
}Channels, Actors, Locked<A> & Atomic<T>
For concurrent coordination across tasks, Clever provides four explicit primitives:
Channel<T>(capacity)— bounded FIFO channel (send,receive). Deadlocks (every task blocked) trap deterministically withtrap: deadlock.actor class— isolated mutable state accessed asynchronously via method messages (.start()).locked class(Locked<A>) — mutex-protected state whose member calls run synchronously on the calling thread, ensuring exclusive access to heap buffers.Atomic<T>— lock-free sequentially consistent atomics (load,store,swap,compareAndSwap,fetchAdd,fetchSub,fetchAnd,fetchOr) forU32,U64,I32,I64.
actor class Counter(var total: U64) {
fun add(delta: U64) {
total = total +% delta
}
fun read(): U64 = total
}
locked class Bucket(var sum: U64, var log: Buf<U8>) {
fun record(v: U64, tag: U8) {
sum = sum +% v
log.push(tag)
}
fun summary(): U64 = sum +% log.len
}
export suspend fun concurrencyTour(a: U64, b: U64): U64 {
val counter = Counter(0u64).start()
val bucket = Bucket(0u64, Buf<U8>()).share()
val atomic = Atomic<U64>(0u64)
val ch = Channel<U64>(2u64)
scope {
spawn {
counter.add(a)
bucket.record(a, 1u8)
atomic.fetchAdd(a)
ch.send(a)
}
spawn {
counter.add(b)
bucket.record(b, 2u8)
atomic.fetchAdd(b)
ch.send(b)
}
}
val c1 = ch.receive()
val c2 = ch.receive()
counter.read() +% bucket.summary() +% atomic.load() +% c1 +% c2
}Deterministic Concurrency Testing (clever sim)
Test any export suspend fun across thousands of deterministic interleavings before running on real threads:
clever sim prog.clv --entry concurrencyTour --seeds 1000 10 20
# 1000 seeds passed (1 distinct result)If a seed triggers a trap or unexpected output, clever sim prints the exact replay command (clever run prog.clv concurrencyTour 10 20 --seed S), and clever c --seed S replays the exact same schedule natively.
Metal GPU Kernels (par(gpu) for)
Write a GPU kernel with the exact same syntax as CPU par for — simply add (gpu). Clever checks the GPU kernel profile at compile time (no recursion, no heap allocation, flat slices/arrays only) and never silently falls back to CPU: a violation is a compile error.
F32(default): compiled to exact IEEE-754 soft-float on Metal (-fno-fast-math -fmetal-math-mode=safe -ffp-contract=off), producing bit-identical results to the CPU and interpreter.FastF32(opt-in via.fast()/.exact()): maps to native GPU fast-math instructions (fast::divide,fast::sqrt, flushed subnormals) for maximum throughput when ULP tolerance is acceptable.
export fun gpuSquareU64(buf: &mut Slice<U64>) {
par(gpu) for (i, c in buf.chunksExact(1)) {
c[0] = c[0] *% c[0] +% i
}
}
export fun gpuFastBlend(out: &mut Slice<F32>, x: &Slice<F32>, y: &Slice<F32>) {
par(gpu) for (i, c in out.chunksExact(1)) {
val a = x[i].fast()
val b = y[i].fast()
c[0] = a.fma(b, 1.0).sqrt().exact()
}
}Compile and inspect Metal kernels on macOS:
# Emit MSL source only (works on any OS for inspection)
clever metal kernel.clv --msl -o kernel.metal
# Emit host C with AOT-compiled .metallib embedded (macOS with Xcode Metal toolchain)
clever metal kernel.clv -o kernel_host.c
# Or compile MSL at first launch on macOS
clever metal kernel.clv --msl-source -o kernel_host.c
clang -O3 kernel_host.c runtime/clever_metal.m -fobjc-arc -framework Metal -framework FoundationOn non-Metal targets (clever run, clever c, clever wasm, clever js), par(gpu) for executes with its identical sequential semantics, making GPU differential testing automatic.