Kern
On this page

Structured concurrency plan

Status: C0-C4, C6 (pinned worker threads) and C7 are built in the self-hosted compiler (checked 2026-11-26). SPEC.md ("Tasks and channels") is the contract; this file is the original plan. Step 13 of the backend plan (PLAN.md); MCU work is deferred. The design keeps the smallest-first rules so it can later run on MCUs too.

PartState
scope, spawn, join, Task[T]Built (C0, C1)
channel, send, recv, try_send, try_recv, closeBuilt (C2)
Loop back-edge pollBuilt (C4)
select with recv, send, after(ms) and default casesBuilt (C3): compiler/src/parser/select.kn, compiler/src/typing/select.kn, tests/test_select.sh
tests/test_concurrency.sh (end-to-end), bench/concurrency.pyBuilt; the script replaces the planned scripts for C1, C2 and C4
Worker threads: N pinned scheduler threads, default one per host CPU (KERN_THREADS overrides)Built (C6, option C of CONCURRENCY-NEXT.md); tests/test_threads.sh, tests/test_fd_threads.sh
Shared, Atomic, work stealing (M:N)Not started (v2)

Where the code differs from the text below, the code is the reference. Channel endpoints are capability values: a task receives tx: Sender[T] and calls send(tx, v). It does not take &tx. The receive form is recv(rx, &mut ok). join takes join(move t). close takes close(&mut tx). Goal: Go-style tasks and channels with Rust-style compile-time safety, no garbage collector and no async colouring.

1. Contract

The language gains five things and no more:

  1. scope { ... } — a structured task group and cancellation domain.
  2. spawn fn(args...) -> Task[T] — an ordinary function call on a fixed stack.
  3. Channels — bounded, typed, ownership-transferring, split endpoints.
  4. select — receive from several channels, with timeout and cancellation cases.
  5. A cooperative scheduler in the runtime.

select (item 4) is built. A cancelled or closed channel makes its case ready, so there is no separate cancellation case.

No threads, no Send/Sync traits, no Arc, no shared mutable data without Shared/Atomic.

scope {
    let (tx, rx) = channel[i64](64)
    let producer = spawn produce(tx)
    let consumer = spawn consume(rx)
    // scope exit joins both; an error cancels the other
}

Types

TypeOwnershipNotes
Task[T]affinejoin(task) -> T ! TaskError; auto-joined at scope exit; no detach
Sender[T]capabilitysend(tx, v) -> bool; closed/cancelled gives false
Receiver[T]capabilityrecv(rx, &mut ok) -> T; shared by consumers for work queues
channel[T](capacity)scopebounded; 0 is rendezvous; returns (Sender[T], Receiver[T])
close(&mut tx)exclusiverequires every sender view dead; no close-while-send
Shared[T] / Atomic[T]v2only needed when the scheduler gains OS threads

Safety rules

  • spawn accepts moved owned values and capability values (Sender, Receiver). It rejects ordinary views and slices (E162): a task cannot alias another task's memory in v1.
  • A Task[T] cannot be dropped, joined twice, or joined by its own task; the compiler reports all three.
  • Sender/Receiver live in the scope that created the channel; they cannot escape it.
  • close is an exclusive borrow, so Go's "send on closed channel" panic is a compile error.
  • select scans cases in source order, so scheduling is deterministic and testable.
  • Every blocking operation is a cancellation point. Cancellation is cooperative in v1: the op returns false/ok=false, and the task returns normally after its own cleanup. Forced unwinding is v2.
  • A task body may return T ! E; the first task error cancels its siblings, and join propagates it.

2. Runtime model, v1

One OS thread in this v1 text; later work added pinned worker threads (see the Status line and SPEC.md). The scheduler is cooperative. This delivers the programming model and all safety checks without OS threads, atomics or a memory-order model.

Smallest-first applies here too (EMBEDDED.md): a task stack comes from a memory provider (an mmap region when hosted, a static pool on a microcontroller), a channel buffer comes from the scope arena, and there is no hidden heap on a bare-metal target.

  • Stacks: fixed, 64 KiB with a guard region below (conc_stack_x64.kn, conc_stack_arm.kn), recycled through a small free list; scope stack=... does not exist. Fixed stacks are required because Kern views into stack memory must never move; Go's growable stacks copy frames.
  • Context switch: save/restore callee-saved registers and the stack pointer. One routine per arch in compiler/src/runtime_extra/conc_arm.kn and conc_x64.kn; arm64 saves x19-x30, d8-d15, sp, x64 saves rbx, rbp, r12-r15, rsp.
  • Scheduler: FIFO ready queue, one blocked list per channel, sleep_ms is built (kern_sched_sleep_ms); timeouts use after(ms) in select. When no task is ready, sleep the OS thread until the next deadline (desktop only).
  • Preemption: the compiler decrements a per-task budget at every loop back-edge and calls sched_yield at zero (10,000 iterations, the value in conc_arm.kn). CPU-bound tasks therefore cannot starve others, without signals.
  • Channels: ring buffer allocated from the scope arena; send blocks while full, recv while empty; waiting tasks are woken in FIFO order.
  • Cancellation: a scope owns an atomic flag (a plain word in v1); blocking calls check it. The scope waits for every child to return, so there are no detached tasks and no leaks.

Deliberate non-goals for v1

  • No work stealing: a task stays on its worker thread.
  • No Shared, Atomic, memory-order model or work stealing (v2).
  • No forced termination of a task that ignores cancellation.
  • No closures: spawn produce(&tx) names a function; arguments are explicit.

3. Stages

StageDeliverableAcceptanceStatusEvidence
C0Lexer/AST/parser for scope, spawn, channel[T], Task[T], Sender[T], Receiver[T]kern fmt round-trips the new syntax; parse-error fixturesDone: a parser unit test exists; no parse-error fixturescompiler/src/parser/parse.kn (test "concurrency syntax parses ...")
C1scope + spawn + join, scheduler, context switch, fixed stackstests/test_scope.sh: nested scopes, result values, error propagation, 10k tasksDone: tests/test_concurrency.sh covers nesting, results, errors and 1,000 tasks; the benchmark runs 10,000compiler/src/backend/concurrency.kn, compiler/src/frontend/finish.kn (front-end tests)
C2Bounded channels, split endpoints, close, try-send/try-recvtests/test_channels.sh: producer/consumer, rendezvous, backpressure, closeDone: tests/test_concurrency.sh; a lost message frees its owners (3324)compiler/src/runtime_extra/conc_chan_x64.kn
C3select, timeouts, cancellation casestests/test_select.sh: deterministic order, timeout, cancellationDone: recv, send, after, default cases; a closed or cancelled case is ready; E166 fixtures in tests/errors/compiler/src/parser/select.kn, compiler/src/typing/select.kn
C4Loop back-edge poll and fairnesstests/test_fairness.sh: a CPU-bound task does not starve a heartbeatDone: tests/test_concurrency.sh has the fairness casecompiler/src/backend/loops.kn
C5Self-hosted compiler paritynone now: Kern has one compilerObsolete: the Rust stage0 is removed.cip/bootstrap.lock
C6Worker threads, then M:N scheduler + Shared/Atomic (separate RFC)parallel speedup and race-free stress testsWorker threads done (tests/test_threads.sh); M:N, Shared, Atomic not startedcompiler/src/runtime_extra/conc_thread_x64.kn, conc_thread_arm.kn
C7Concurrency benchmarkpython3 bench/concurrency.py: spawn/join, ping-pong, 10k tasks, switch costDonebench/concurrency.py

A stage is done when its acceptance script passes with build/kern on macOS arm64 and the Linux targets. The compiler that builds Kern is build/kern, so a feature in the compiler source must also compile under the pinned bootstrap compilers. Run sh tests/test_selfhost_cli.sh build/kern-bootstrap --host-only for that.

4. Work breakdown

All work is in the self-hosted compiler (compiler/src/). The Rust stage0 no longer exists.

AreaFolders and filesState
Front endlexer, parser (statements.kn, expressions.kn, types.kn), syntax, formatBuilt for scope, spawn, channel, select (parser/select.kn)
Typestyping/concurrency.kn (E161, E163, E164, E165)Built
Ownershipownership/concurrency.kn (E162-E165: linear Task, capability views, move-only spawn arguments)Built
Code generationbackend/concurrency.kn, backend/loops.kn (poll)Built, including select (backend/statements.kn)
Runtimeruntime_extra/conc_arm.kn, conc_x64.kn, conc_chan_arm.kn, conc_chan_x64.knBuilt for arm64 and x64 (macOS arm64 run checked)
Parityapi, rules, testhash, testcacheHash and rule walkers handle the new nodes; the task_never_joined rule is not built

Diagnostics (block E16x)

CodeMeaning
E161spawn target is not a function, has the wrong arity or is outside a scope
E162spawn argument borrows task-local memory (ordinary view or slice)
E163task handle used after join, joined twice, or joined by itself
E164channel endpoint escapes its scope
E165close needs an exclusive sender borrow
E166bad select: a case that is not recv, send, after or default, two after, default with after, one channel twice, or an empty select

5. Tests and benchmarks

The end-to-end tests are in tests/test_concurrency.sh, tests/test_select.sh and tests/test_threads.sh. The benchmark exists. The scripts below, except tests/test_select.sh, were planned and do not exist. Compiler unit tests are in compiler/src/parser/parse.kn and compiler/src/frontend/finish.kn (front end and ownership; E161-E165).

  • tests/test_scope.sh — order, results, nesting, errors, 10k tasks, stack overflow trap.
  • tests/test_channels.sh — bounded/unbounded semantics, rendezvous, multiple consumers, close.
  • tests/test_select.sh — deterministic scan, timeout, cancellation, no lost wakeups.
  • tests/test_fairness.sh — CPU-bound task plus channel heartbeat.
  • Error fixtures under tests/errors/ for E161-E166.
  • bench/concurrency.py — spawn+join latency, channel round-trip, throughput, peak RSS per task.
  • Stress: 100k short tasks, 1M messages, repeated scope exit during cancellation (leak check by RSS).

6. Risks and open decisions

  1. Bootstrap compatibility. The compiler source is built by the pinned bootstrap compilers. Do not use a concurrency feature inside the compiler source until the bootstrap compilers support it.
  2. Fixed stacks vs recursion. 64 KiB caps recursion depth. Add stack= on scope and a clean trap.
  3. Cancellation cleanup. Kern has no destructors. v1 is cooperative; a task that ignores cancellation can delay scope exit. v2 should add forced termination only for tasks that own no heap values, or a per-scope arena so wholesale cleanup is safe.
  4. Views across suspension. The rule "no ordinary views cross a task boundary" is what makes this safe; do not relax it without a full borrow analysis across suspension points.
  5. Scheduler fairness. The loop poll adds an instruction per back-edge. Tune the budget; make it a profile setting, not a user rule.
  6. M:N scheduler. Deferred deliberately. It needs atomics, memory ordering, work stealing and a preemption story; the v1 semantics must not change when it arrives.

Open decisions for the user (the build so far chose single-threaded v1, cooperative cancellation and fixed stacks; select is built):

  • Is single-threaded v1 acceptable as the first ship, with parallelism in v2?
  • Cooperative cancellation with ok=false, or a defer-style cleanup feature first?
  • Fixed 64 KiB stacks, or per-scope stack= from day one?

Source: CONCURRENCY.md in the repository.