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.
| Part | State |
|---|---|
scope, spawn, join, Task[T] | Built (C0, C1) |
channel, send, recv, try_send, try_recv, close | Built (C2) |
| Loop back-edge poll | Built (C4) |
select with recv, send, after(ms) and default cases | Built (C3): compiler/src/parser/select.kn, compiler/src/typing/select.kn, tests/test_select.sh |
tests/test_concurrency.sh (end-to-end), bench/concurrency.py | Built; 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:
scope { ... }— a structured task group and cancellation domain.spawn fn(args...) -> Task[T]— an ordinary function call on a fixed stack.- Channels — bounded, typed, ownership-transferring, split endpoints.
select— receive from several channels, with timeout and cancellation cases.- 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
| Type | Ownership | Notes |
|---|---|---|
Task[T] | affine | join(task) -> T ! TaskError; auto-joined at scope exit; no detach |
Sender[T] | capability | send(tx, v) -> bool; closed/cancelled gives false |
Receiver[T] | capability | recv(rx, &mut ok) -> T; shared by consumers for work queues |
channel[T](capacity) | scope | bounded; 0 is rendezvous; returns (Sender[T], Receiver[T]) |
close(&mut tx) | exclusive | requires every sender view dead; no close-while-send |
Shared[T] / Atomic[T] | v2 | only needed when the scheduler gains OS threads |
Safety rules
spawnaccepts 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/Receiverlive in the scope that created the channel; they cannot escape it.closeis an exclusive borrow, so Go's "send on closed channel" panic is a compile error.selectscans 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, andjoinpropagates 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.knandconc_x64.kn; arm64 savesx19-x30, d8-d15, sp, x64 savesrbx, rbp, r12-r15, rsp. - Scheduler: FIFO ready queue, one blocked list per channel,
sleep_msis built (kern_sched_sleep_ms); timeouts useafter(ms)inselect. 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_yieldat zero (10,000 iterations, the value inconc_arm.kn). CPU-bound tasks therefore cannot starve others, without signals. - Channels: ring buffer allocated from the scope arena;
sendblocks while full,recvwhile 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
| Stage | Deliverable | Acceptance | Status | Evidence |
|---|---|---|---|---|
| C0 | Lexer/AST/parser for scope, spawn, channel[T], Task[T], Sender[T], Receiver[T] | kern fmt round-trips the new syntax; parse-error fixtures | Done: a parser unit test exists; no parse-error fixtures | compiler/src/parser/parse.kn (test "concurrency syntax parses ...") |
| C1 | scope + spawn + join, scheduler, context switch, fixed stacks | tests/test_scope.sh: nested scopes, result values, error propagation, 10k tasks | Done: tests/test_concurrency.sh covers nesting, results, errors and 1,000 tasks; the benchmark runs 10,000 | compiler/src/backend/concurrency.kn, compiler/src/frontend/finish.kn (front-end tests) |
| C2 | Bounded channels, split endpoints, close, try-send/try-recv | tests/test_channels.sh: producer/consumer, rendezvous, backpressure, close | Done: tests/test_concurrency.sh; a lost message frees its owners (3324) | compiler/src/runtime_extra/conc_chan_x64.kn |
| C3 | select, timeouts, cancellation cases | tests/test_select.sh: deterministic order, timeout, cancellation | Done: 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 |
| C4 | Loop back-edge poll and fairness | tests/test_fairness.sh: a CPU-bound task does not starve a heartbeat | Done: tests/test_concurrency.sh has the fairness case | compiler/src/backend/loops.kn |
| C5 | Self-hosted compiler parity | none now: Kern has one compiler | Obsolete: the Rust stage0 is removed | .cip/bootstrap.lock |
| C6 | Worker threads, then M:N scheduler + Shared/Atomic (separate RFC) | parallel speedup and race-free stress tests | Worker threads done (tests/test_threads.sh); M:N, Shared, Atomic not started | compiler/src/runtime_extra/conc_thread_x64.kn, conc_thread_arm.kn |
| C7 | Concurrency benchmark | python3 bench/concurrency.py: spawn/join, ping-pong, 10k tasks, switch cost | Done | bench/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.
| Area | Folders and files | State |
|---|---|---|
| Front end | lexer, parser (statements.kn, expressions.kn, types.kn), syntax, format | Built for scope, spawn, channel, select (parser/select.kn) |
| Types | typing/concurrency.kn (E161, E163, E164, E165) | Built |
| Ownership | ownership/concurrency.kn (E162-E165: linear Task, capability views, move-only spawn arguments) | Built |
| Code generation | backend/concurrency.kn, backend/loops.kn (poll) | Built, including select (backend/statements.kn) |
| Runtime | runtime_extra/conc_arm.kn, conc_x64.kn, conc_chan_arm.kn, conc_chan_x64.kn | Built for arm64 and x64 (macOS arm64 run checked) |
| Parity | api, rules, testhash, testcache | Hash and rule walkers handle the new nodes; the task_never_joined rule is not built |
Diagnostics (block E16x)
| Code | Meaning |
|---|---|
E161 | spawn target is not a function, has the wrong arity or is outside a scope |
E162 | spawn argument borrows task-local memory (ordinary view or slice) |
E163 | task handle used after join, joined twice, or joined by itself |
E164 | channel endpoint escapes its scope |
E165 | close needs an exclusive sender borrow |
E166 | bad 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
- 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.
- Fixed stacks vs recursion. 64 KiB caps recursion depth. Add
stack=onscopeand a clean trap. - 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.
- 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.
- Scheduler fairness. The loop poll adds an instruction per back-edge. Tune the budget; make it a profile setting, not a user rule.
- 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 adefer-style cleanup feature first? - Fixed 64 KiB stacks, or per-scope
stack=from day one?