M6: cooperative tasks on microcontrollers
Status: design, not implemented. This document is the M6 contract and adds no code.
Prerequisites: M2 (M2-RUNTIME.md: freestanding runtime, linker task-stack region, per-function stack
proof, SysTick) and M3 (M3-MMIO.md: interrupt fn, critical, static var, capabilities). M4/M5 are
size and encoding prerequisites for shipping, not for the semantics below. Parent plans: EMBEDDED.md
(M6 row in §4) and CONCURRENCY.md (the language surface). Design law: every feature must run on a
single-core MCU with a few tens of kilobytes of RAM, a few hundred kilobytes of flash and no operating
system.
M6 is the MCU realization of concurrency stages C1-C4 in CONCURRENCY.md. It keeps the surface
(scope, spawn, Task[T], channels, select) and changes only what the target forces: stacks are a
static pool, channels are statically sized, error propagation is one concrete type, and preemption is
cooperative plus declared interrupts.
0. The whole surface
| Form | Kind | Purpose |
|---|---|---|
scope { ... } | statement | task group and cancellation domain |
spawn f(args...) | expression -> Task[T] | start a task on a pooled static stack |
join(task) | builtin -> T ! TaskError | wait for a task and take its value |
channel[T](capacity) | expression -> (Sender[T], Receiver[T]) | bounded static ring in scope storage |
send(&tx, move v) -> bool | builtin | blocking send; false on close or cancel |
recv(&rx, &mut value) -> bool | builtin | blocking receive into caller storage |
try_send(&tx, move v) -> bool | builtin | non-blocking send |
try_recv(&rx, &mut value) -> bool | builtin | non-blocking receive into caller storage |
close(&mut tx) | builtin | half-close once every sender is dead |
select { ... } | statement | ordered multi-wait with timeout and cancellation |
cancelled() -> bool | builtin | cooperative cancellation check |
sleep_ms(n) / clock_ns() | existing builtins | SysTick time |
It does not add threads, SMP, task priorities, work stealing, detached tasks, a heap, Shared,
Atomic, defer, async, pointers or any way to name a stack address.
The safety argument is one paragraph:
A task runs on its own fixed stack, owns every value it was given, and reaches another task only by moving a value into a channel or by holding a channel capability. The scheduler switches only at explicit yield points in task context; interrupt handlers never touch scheduler, channel or scope state. Every task stack, channel buffer, result slot and control block is reserved before the program runs. A program that compiles therefore has no allocation failure, no unbounded queue, no data race and no timing-dependent scheduling decision.
0.1 What changes from CONCURRENCY.md
| Topic | CONCURRENCY.md | M6 | Reason |
|---|---|---|---|
| Task stack | 64 KiB, lazily committed mmap | 1 KiB from a static pool | no MMU, no demand paging |
| Task count | unbounded | 8 maximum, 4 default | static pool, one-byte ids |
| Channel capacity | any usize; 0 is rendezvous | power of two, 1..=256 | mask wrap, one static buffer |
| Channel storage | scope arena from the heap | static object per scope site | no heap, no arena on none |
recv result | returns T with an ok flag | writes caller storage, returns bool | no fabricated T on close or cancel |
| Task error | T ! E propagates | T ! TaskError | Kern has concrete error types |
| Loop poll budget | 10,000 back-edges | 2,048 back-edges | latency at 16 MHz |
| Idle | sleep the OS thread | wfi plus a 1 ms tick | no OS |
| Switch | anywhere in the scheduler | task context only, no ISR switch | M3 §2.6 |
| Detach, priorities | absent | absent | determinism, size |
1. Task model
1.1 Scope, spawn and join
fn main() {
scope {
let (tx, rx) = channel[i64](16)
let producer = spawn produce(&tx)
let consumer = spawn consume(&rx)
match join(producer) {
ok(made) { print_int(made) }
err(error) { print_int(1) }
}
match join(consumer) {
ok(used) { print_int(used) }
err(error) { print_int(2) }
}
close(&mut tx) // legal: both sender views are dead
}
}
Rules:
scopeis a statement, not an expression. It may nest. It has no result; its only failure is the propagation of an unobserved child error (§1.6).spawn f(args...)returns an affineTask[T].fis a named function; there are no closures and no captured environment. Signature, arity and argument types are checked (E161). A spawn site executes at most once per entry of its enclosing scope: it may not be nested in a loop that is inside that scope (E187). A loop that needs several tasks writes several spawn sites, or puts thescopeinside the loop.- A spawn argument is a moved value or a channel capability (
&Sender[T],&Receiver[T]). Ordinary views, slices, arena handles and handles into task-local memory are rejected (E162). - A
Task[T]is affine: it cannot be dropped, joined twice, or joined by the task it names (E163). There is no detach. A task handle cannot leave its scope (E164). - Every spawned task is implicitly joined at scope exit, in spawn order. A scope does not return until every child has exited and every stack slot is free.
- A task runs its function at most once. Its stack slot is held from
spawnuntil exit, not untiljoin. mainis task 0. It runs on the main stack and is not part of the task pool.- There are no task priorities. The ready queue is FIFO; handlers keep their M3 priorities.
- A task result
Tmust be a plain value: no slice, no borrow, no arena, no handle and no owning reference. It is copied into a spawn slot in scope storage before the task stack is released (E162). - A scope that owns spawns or channels has one static object per scope site (a scope object, §3.1) holding its cancellation flag, spawn slots and channel objects. A site reachable from more than one task root is rejected (E187).
Because a scope joins before it exits and recursion is rejected, one static object per site is enough: the object is initialized at every scope entry and reused on the next entry.
1.2 Task states
| State | Meaning | In ready queue | In timer list | In channel wait |
|---|---|---|---|---|
FREE | slot unused | no | no | no |
READY | runnable | yes | no | no |
RUNNING | current task | no | no | no |
SEND | blocked on a full channel | no | no | sender list |
RECV | blocked on an empty channel | no | no | receiver list |
JOIN | waiting in join for another task | no | no | no (target id in wait) |
SELECT | blocked in select | no | maybe | one or more receiver lists |
SLEEP | in sleep_ms | no | yes | no |
ZOMBIE | exited, result and error pending join | no | no | no |
Transitions are only performed by task-context runtime code. An interrupt never changes a state.
1.3 Stacks from the static pool
The profile fixes three numbers:
tasks = { max = 4, stack = 1K, margin = 64, budget = 2048 }
tasks.maxis the number of spawned tasks; main is extra. Default 4, hard maximum 8.tasks.stackis the stack size of every task, a multiple of 8,512..=4096. Default 1024.tasks.marginis an additional safety allowance included in the proof. Default 64.tasks.budgetis the loop back-edge budget (§2.6). Default 2048.
The pool comes from M2's __task_stacks region, one slot per task, each slot 8-byte aligned:
__task_stacks_start
slot 0: [ stack 0 ][ stack 1 ] ... [ stack max-1 ]
__task_stacks_end
The TCBs are a separate .bss array. The linker assertion from M2 (__task_stacks_end <= __main_stack_bottom) stays; the compiler also reports the pool size and the largest proven chain.
The per-task proof is the M2 static chain plus the switch and exception overhead:
need(f) = round8(chain(f) + SWITCH + EXCEPTION + margin)
| Item | Cortex-M3/M4 | RV32 (ESP32-C3) |
|---|---|---|
SWITCH | 40 B (r4-r11, lr, alignment) | 56 B (ra, s0-s11, alignment) |
EXCEPTION | 40 B (hardware frame on PSP, 8-byte alignment) | isr_stack (handlers run on the task stack) |
| Handler frames | on MSP, not the task stack | on the task stack, included in isr_stack |
On Cortex-M, tasks run on PSP and handlers on MSP, so a task stack carries only the 32-byte hardware
exception frame, not the handler call chain. On RV32 there is no separate handler stack in M3, so every
task stack includes the profile's isr_stack headroom. A task whose need exceeds tasks.stack, or
whose body is recursive, is rejected (E182; recursion is already an M2 error). The compiler prints the
largest chain and the per-slot usage.
A spawn initializes only the synthetic frame at the top of its slot (saved registers, trampoline address and argument block). It does not clear the rest of the stack; the language already requires every local to be initialized before use.
1.4 Task count and the stack budget
tasks.max is enforced at compile time. The compiler walks the acyclic call graph from main and
computes the maximum number of simultaneously live spawned tasks:
live(main) = max over statements of (sum of 1 + live(body) over spawns that can be live together)
Spawns in one scope are summed because the scope joins all of them. Sequential scopes take the
maximum, and the count starts at zero at main. A cycle that contains a spawn edge is rejected
(E189), because it would make the count and the static stack proof unprovable.
Examples, with max = 4:
| Program | Live tasks | Result |
|---|---|---|
scope { spawn a } | 1 | accepted |
scope { spawn a; spawn b } | 2 | accepted |
spawn a, and a does scope { spawn b } | 2 | accepted |
scope { spawn a; spawn b }, each with one nested child | 4 | accepted |
| nine sibling spawns | 9 | E180 |
The stack budget is tasks.max * (tasks.stack + sizeof(Tcb)) plus the scope objects, scheduler state
and the main stack. The profile may declare tasks.ram; otherwise the compiler derives the sum. A
budget over the part's RAM is a compile-time error (E182) and, independently, a linker assertion.
1.5 Exhaustion
Exhaustion is a compile-time error, not a runtime condition:
- a program whose live-task bound exceeds
tasks.maxis rejected with E180; - a program whose stacks, TCBs or scope objects do not fit the declared RAM is rejected with E182;
- a task whose proven chain exceeds
tasks.stackis rejected with E182.
The runtime still acquires a slot with a short check. If the free counter is zero, it calls the trap
hook with kind 7 (task_pool) and halts. In a checked program this is unreachable; it exists so that
a compiler bug or a future analysis relaxation cannot silently corrupt a stack. The diagnostic and
the trap are tested with an internal fault-injection build, never with a user-visible flag.
spawn therefore has no error return. Making it fallible would force every caller to handle a case
that the static proof already excludes, and would add an error path to the smallest runtime.
1.6 Task errors
enum TaskError { Cancelled, Failed }
- A spawned function returns
TorT ! TaskError. Another error type is rejected (E181). A task that wants to report a typed error returns a result value (for example a small enum) asT, or sends details on a channel.TaskErrormeans "abort the group", not "here is the payload". - A
fail TaskError.Failedin a child sets the scope'scancelflag, wakes every child blocked at a cancellation point withfalse, and leaves the failing child as aZOMBIEcarryingFailed. joinreturns the value of a task that finished before cancellation. A task that exited after the flag was set returnsCancelled, and its value is discarded. Joining a failed task returnsFailed.- An unobserved failed child fails the scope at exit with
Failed. In a function that returns! TaskError, the scope failure propagates with the ordinarytryrules. In an infallible function, every fallible task must be explicitly joined and both arms handled; otherwise E188. This is why the example in §1.1 can spawn a fallible task inmainand handle the error locally.
join is always typed T ! TaskError, even for an infallible child, so the surface has one shape.
The error arm of a provably infallible child can only be Cancelled, caused by a sibling.
The typed-error restriction is deliberate for v1: Kern error types are concrete, so a generic
join -> T ! E would need a synthesized union, a conversion trait or type erasure. All three are
larger than the feature. CONCURRENCY.md's richer propagation is deferred; §12 records the
alternative.
2. Scheduler
2.1 Runtime state
The runtime is compiler-emitted .bss; it is not user static var and may hold addresses.
TASKS[MAX_TASKS] one Tcb per task, main included
READY[MAX_TASKS] FIFO ring of task ids
READY_HEAD, READY_TAIL
TIMERS[MAX_TASKS] task ids sorted by absolute deadline
TIMER_LEN
CURRENT running task id
BLOCKED count of SEND/RECV/JOIN/SELECT/SLEEP tasks
TICKS u64 millisecond counter
MAX_TASKS = tasks.max + 1.
The TCB is 32 bytes on a 32-bit target:
| Field | Type | Bytes | Use |
|---|---|---|---|
sp | u32 | 4 | saved stack pointer |
stack_base | u32 | 4 | slot base for canary and reporting |
result | u32 | 4 | address of this task's spawn slot |
scope | u32 | 4 | address of the enclosing scope object |
deadline | u32 | 4 | tick deadline for SLEEP/timed SELECT |
wait | u32 | 4 | channel address, select case base, or joined task id in JOIN |
id | u8 | 1 | 0..7 |
state | u8 | 1 | §1.2 |
flags | u8 | 1 | cancelled, failed, joined, canary |
select | u8 | 1 | select case mask |
joiner | u8 | 1 | task waiting in join, or NONE |
| pad | 3 | alignment |
There is no priority field, no link pointer and no dynamic memory. A task id fits in one byte, which is why eight tasks is the hard maximum.
2.2 Ready queue
A FIFO ring of task ids, capacity MAX_TASKS. Enqueue at the tail, dequeue from the head. A task is in
exactly one state, so an id is never in the queue twice. The running task is not in the queue.
When a task yields voluntarily, it is enqueued at the tail before the next task is chosen. When it blocks, it is not enqueued. When an event wakes a task, it is enqueued at the tail in the order the event names it. A block never pushes the current task.
The queue operations are a handful of byte loads and stores. They need no masking: only task context touches them (§2.7).
2.3 Blocked lists
Each channel has two FIFO arrays of task ids, send_wait[capacity] and recv_wait[capacity], with
lengths. Capacity is MAX_TASKS (8 entries, 9 bytes per direction including the length). A blocked
task is appended to one list. A SELECT task is appended to the receiver list of every receive case
and possibly to the timer list.
Wake rules:
- a send fills a slot and wakes the oldest blocked receiver;
- a recv frees a slot and wakes the oldest blocked sender;
closewakes all receivers, then all senders, in ascending task id;- task exit wakes its joiner, if any, and leaves the exit state in
ZOMBIE; - a wake is idempotent: if the task is already
READY, nothing happens.
ok=false is expressed as the false return from send, recv, try_send, try_recv and
sleep_ms; there is no separate ok variable to thread through the call.
Removal on wake, timeout or cancellation is a bounded scan of at most eight ids and a shift. There are
no linked lists, no stale pointers and no allocation. A stale entry left by a SELECT task is stale
for at most one scheduling step: the task unregisters from its other cases before it re-blocks.
A join on a running task sets JOIN, stores the joiner id in the child's joiner field and yields.
A task handle is affine, so there is at most one joiner. task_exit moves the child to ZOMBIE and
enqueues the joiner; a join on an existing ZOMBIE copies the result and frees the slot without
blocking. JOIN counts as blocked for the deadlock check.
Arrays rather than bitmaps preserve FIFO order. At eight tasks the difference is nine bytes per list.
2.4 Timer list
A sorted array of task ids by absolute u32 deadline. Insertion is O(n) over at most eight entries; a
timer wheel would be more code than the data it indexes. The list is checked at every scheduler entry
(block, yield, exit), never in an interrupt. expire(now) wakes tasks whose deadline has passed, in
deadline order and then ascending id, and removes them from the list.
Deadlines use wrapping u32 tick arithmetic: expired = (now - deadline) < 0x8000_0000. A sleep or
timeout is limited to 2^31 - 1 ms (about 24.8 days), far beyond an MCU power cycle.
2.5 Yield and idle
yield_now(from):
expire(now())
if state[from] == RUNNING:
state[from] = READY
ready_push(from) // the queue now holds at least `from`
if ready_empty():
idle() // only when `from` is blocked
expire(now())
if ready_empty(): trap(deadlock)
to = ready_pop()
if to == from:
state[from] = RUNNING
return
state[to] = RUNNING
CURRENT = to
switch(TASKS[from], TASKS[to])
idle():
if TIMER_LEN == 0:
if BLOCKED > 0: trap(deadlock)
exit_board() // no runnable and no blocked task
mask; recheck ready and timer under the mask; wfi; restore
expire(now())
idle follows M2's race-free protocol: mask, recheck, wfi with the timer able to become pending,
restore, loop. If the ready queue is empty and no timer exists while tasks are blocked, no event can
ever wake them: trap kind 8 (deadlock). This turns the common deadlock into a deterministic test
failure instead of a hang. If nothing is runnable and nothing is blocked, the program exits through the
board hook (semihosting or halt).
A task that is alone and runnable does not switch. The common yield_now therefore costs a queue
check and a return, not a context switch.
2.6 The loop poll
Every while and for back-edge in task code decrements one counter and calls the scheduler at zero:
.Lloop:
subs r7, r7, #1
bne .Lbody
bl kern_loop_poll @ reloads r7, yields if another task is ready
.Lbody:
... body ...
On Thumb-2 the fast path is two instructions and 4 bytes (subs on r0-r7 has a 16-bit encoding). On
RV32 it is the compressed c.addi/c.bnez pair, two instructions and 4 bytes. If the optimizer
cannot keep the counter in the reserved register, the fallback is a frame slot: load, subtract, store,
branch, 4 instructions and about 10 bytes. The optimizer's job is to make the two-instruction form the
normal case.
The counter lives in a reserved callee-saved register: r7 on Thumb-2, s0 on RV32. Both are AAPCS/RISC-V callee-saved and have short encodings; the compiler simply never allocates them to a user value or a frame pointer. External compiler helpers preserve them, so interoperation with the toolchain is unchanged. The context switch saves the counter with the other callee-saved registers, so the bound is per task across all functions, not per function.
Cost and latency:
| Item | Value |
|---|---|
| Fast path | 2 instructions, 4 B Thumb / 4 B RV32, 2 cycles |
| Slow path | one out-of-line call per tasks.budget back-edges, 8-12 B |
| Default budget | 2,048 back-edges |
| Worst-case run slice | about 4k-8k cycles, 0.25-0.5 ms at 16 MHz |
| Tasks that never loop | not preemptible; a long straight-line MMIO wait must be split by hand |
The poll is suppressed in interrupt fn and every function reachable from one (M3), in every function
reachable from critical, and in the scheduler runtime. critical may not contain a yield, so a
called function must not poll either; the effects analysis carries a critical-safe summary, the same
way it carries ISR safety. A function reachable from both a critical block and a normal loop has its
poll suppressed everywhere; a fairness test covers the normal call.
The poll does not check cancellation. A CPU-bound task observes cancellation only when it calls
cancelled() or reaches a blocking operation (§5).
2.7 Interrupts, critical and what is masked
M3 fixes the contract; M6 makes it concrete:
- An interrupt can preempt a task at any instruction and returns to the same task. That is the only preemption in the system; tasks give way to each other only at the yield points in §2.5, §2.6 and the blocking operations.
- An
interrupt fnnever callsspawn,join,select,send,recv,sleep_msor any function that does (E185, extending M3's E177). It never switches stacks and never yields. - A handler may publish one word or push into a
static varring. A task polls that word at a yield point. There is no channel or scheduler call in interrupt context. - SysTick increments
TICKSand returns. It does not inspect the ready queue, the timer list or any TCB, and M6 uses no PendSV switch. - The only runtime state shared with an interrupt is
TICKS. It is read in acriticalsection because it is 64-bit on a 32-bit core. Scheduler, channel and scope state are task-only, so their accesses need no masking. - Runtime
criticalsections are a handful of instructions (tick read, idle recheck), never a loop or a call. The mask budget is under 20 cycles, far below one 1 ms tick. criticalis also the task-to-task lock. A task switch happens only at a yield, andcriticalcannot contain a yield, so two tasks cannot interleave inside it. Astatic varreached from two task contexts, or from a task and a handler, requirescriticalaround every access (E176, extended from M3's access-context rule). For a cell private to one task, nocriticalis needed.- A handler must not read a
static varthat a task writes outsidecritical; this is M3's rule and M6 does not weaken it.
The consequence is a small and checkable model: interrupts are the only asynchronous events, and the only thing they share with tasks in the runtime is the millisecond counter.
2.8 Context switch
Cortex-M3/M4:
switch(from, to):
mrs r2, psp @ main's save uses MSP and stores to from.sp
stmdb r2!, {r4-r11, lr} @ r7 is the budget counter
str r2, [from].sp
ldr r2, [to].sp
ldmia r2!, {r4-r11, lr}
msr psp, r2
bx lr
The first switch to a task loads a synthetic frame whose lr is the trampoline and whose r7 (or
s0) is tasks.budget. The trampoline reads the argument block from the spawn slot, calls the task
body, stores the result in the spawn slot and calls task_exit. Main keeps MSP; the switch sets PSP
and CONTROL.SPSEL when entering a task and clears them when returning to main. Handlers are always
MSP.
RV32 saves ra and s0-s11 and swaps sp; there is no PSP or CONTROL register. Handlers run on
the task stack, which is why isr_stack is part of every RV32 task stack.
The switch is about 40-70 cycles including the queue update; it is called only from task context. There is no nested switch, no FPU context (M3 ships with the FPU off) and no lazy stacking.
2.9 Determinism
Given the same program and the same sequence of external interrupts, the schedule is reproducible:
- the ready queue is FIFO, and a wake appends at the tail;
- sibling spawns become ready in spawn order; scope exit joins in spawn order;
selectscans cases in source order (§3.5);- timers that expire in the same tick wake in deadline order, then ascending id;
closewakes waiters in ascending id;- the loop poll uses a fixed budget, not wall-clock time;
- no task priority, no work stealing, no time-slice length based on the tick.
The tick affects only when a deadline expires, never which ready task is chosen. QEMU with
-icount is used to make the tests repeatable; the semantics do not depend on it.
2.10 Trap kinds
M2 defines kinds 0-6 (overflow, bounds, assert, division, cast, precondition, postcondition). M6 reserves the next four for the task runtime:
| Kind | Name | Cause |
|---|---|---|
| 7 | task_pool | free slot counter is zero in spawn; unreachable after E180 |
| 8 | deadlock | no ready task, no timer, at least one blocked task |
| 9 | stack | debug canary word overwritten |
| 10 | channel | ring or wait-list invariant violated in a checked build |
They use the same numeric kern_trap_hook(kind, file_id, line) ABI as M2, so a test can assert the
kind and a board can print it without new formatting code.
3. Channels
3.1 Surface and static storage
let (tx, rx) = channel[i64](16)
capacityis a literal or aconstin1..=256and a power of two. Wrap isindex & (capacity-1), one instruction, no division. Anything else is E183.Thas a fixed size and no slice, owner, arena, handle or view.sizeof(T) <= 64keeps the monomorphised copy loop small. Anything else is E184.- A channel may be declared only in a
scopeblock, and not in a loop inside that scope. It is one object in that scope's static storage, not a stack local and not a heap allocation. The object is initialized at scope entry. - A scope site that declares a channel must be reachable from at most one task root (E187). The common
cases are a channel in
main's scope or in one task body. A worker pool shares one channel frommain; per-worker private channels are a later pool feature (§11, §12.5). Sender[T]andReceiver[T]are affine endpoint values, one word each: the address of the channel object.&Sender/&Receiverin aspawnor call is a capability copy, not a borrow of the caller's variable; the child receives the one-word handle and cannot name the parent's frame. The borrow checker still treats the call as a shared borrow of the endpoint for lifetime and close purposes; only the runtime value is a copy.- Endpoints cannot escape their scope (E164).
closeneeds the unique sender (E165).
The channel object is the static arena that EMBEDDED.md §10 describes for the MCU: a fixed buffer
plus a header, no fragmentation and no allocator.
3.2 Layout
struct Channel[T] {
head: u16 // 2
tail: u16 // 2
len: u16 // 2
capacity: u16 // 2
flags: u8 // 1 closed
pad: u8[3] // 3
send_wait: u8[8] // 8 FIFO of task ids
send_len: u8 // 1
recv_wait: u8[8] // 8
recv_len: u8 // 1
pad: u8[2] // 2
buffer: [T; capacity]
}
The header is 32 bytes at tasks.max = 8 (28 bytes at the default 4, because the wait arrays shrink).
The buffer is aligned to alignof(T) and follows the header. len distinguishes full from empty, so
the buffer needs no sentinel slot and no Option[T] tagging. A slot is written before len is
incremented and read before len is decremented; an unoccupied slot is never read.
Examples on the 20 KiB part:
T | Capacity | Header | Buffer | Total |
|---|---|---|---|---|
u8 | 64 | 32 | 64 | 96 |
u32 | 32 | 32 | 128 | 160 |
i64 | 16 | 32 | 128 | 160 |
| 16-byte struct | 8 | 32 | 128 | 160 |
i64 | 64 | 32 | 512 | 544 |
A per-channel cap (tasks.channel, default 1 KiB, maximum 4 KiB) rejects a channel that would eat the
part (E184).
3.3 Send and receive ownership
send(&tx, move v) moves v into the ring:
- closed: return
false; len < capacity: copyvintobuffer[tail],tail = (tail+1) & (capacity-1),len += 1, wake the oldest receiver, returntrue;- scope cancelled: return
false; - otherwise: state
SEND, append tosend_wait,yield_now, retry from 1.
recv(&rx, &mut value) -> bool:
len > 0: copy outbuffer[head]intovalue,head = (head+1) & (capacity-1),len -= 1, wake the oldest sender, returntrue;- closed and empty: return
falsewithout writingvalue; - cancelled: return
falsewithout writingvalue; - otherwise: state
RECV, append torecv_wait,yield_now, retry from 1.
try_send and try_recv perform step 1-3 only and never block. They still return false on a
closed channel or a cancelled scope.
Ownership is a bitwise move of a value that contains no owners, slices or handles. A move argument
is consumed on entry: false means it was not enqueued, and the caller cannot use it again. The
sender's binding is consumed, the ring owns the value until a receiver copies it out, and neither side
aliases the other. recv writes the caller's storage only on success, so a failed receive never
fabricates a T; there is no zero value to misuse and no Option tag. The caller's previous value
survives a false, which also makes the try retry loop straightforward.
Multiple senders and multiple receivers are allowed through capability copies. Each channel is FIFO per direction; there is no cross-channel fairness guarantee.
3.4 Close
close(&mut tx) is an exclusive borrow of the unique sender. It is legal only when every sender
capability is dead, including the copies passed to spawned tasks. A spawn borrow lasts until the child
is joined (or the scope exits), so the idiom is join the producer, then close, then join the consumer:
let producer = spawn produce(&tx)
match join(producer) { ok(_) {} err(_) {} }
close(&mut tx)
let consumer = spawn consume(&rx)
match join(consumer) { ok(_) {} err(_) {} }
A receiver may drain values that were buffered before the close; once the buffer is empty it gets
false. A closed channel stays closed. Close twice is a compile error (the exclusive borrow), and
a send while a close is possible is E165. A blocked sender cannot coexist with close because the
sender holds a live capability, which the borrow rule forbids.
A scope does not implicitly close its channels. If a child blocks forever on a channel that no one
will send to, the scope waits forever; the all-blocked case traps kind 8, and a watchdog covers the
rest. The programmer's tools are close, a sibling failure, and a timeout in select.
3.5 Select
select {
case recv(&rx_a) -> a { use(a) }
case recv(&rx_b) -> b { use(b) }
case timeout(100) { ... }
case cancelled { ... }
}
- Cases are receives, at most one timeout, and an optional cancellation case. One to eight cases. A non-receive, non-timeout, non-cancelled case is E166; duplicate receivers, a second timeout and zero cases are E186. The exact surface syntax is C0's; the case set and order below are the contract.
- Cancellation is checked first: if the scope flag is set and a
cancelledcase exists, it runs. If nocancelledcase exists, the select returns without taking a case and the task checkscancelled(). - Otherwise cases are scanned strictly in source order with the try operations. The first ready receiver wins. A timeout case is eligible only when its deadline has passed; placing it last is the convention but not a rule.
- If no case is ready, the task registers on every receive case and on the timer list, sets state
SELECT, and yields. On wake it unregisters from every case, re-scans in source order, and either takes a case or re-blocks. - Check-and-register happens without a yield, and interrupts do not touch channels, so there is no lost wakeup. Readiness is level-triggered: a woken task re-checks, and if another task consumed the value first it re-blocks. This is deterministic for a fixed schedule and avoids reserving a value in the scheduler.
The scan is at most eight try operations. The case set is compiled code, not a heap array; there is no
closure and no allocation. select with a single receive is the plain blocking receive; select with
a timeout is the v1 timeout form.
3.6 No heap growth
Every byte is in the scope object: header, wait arrays, ring buffer. A blocked task adds one id to a
fixed array. A send copies into a slot; it does not allocate a node. A select adds at most eight ids.
The image's .bss is constant after link, the task pool is constant, and nm must show no
kern_alloc, malloc, mmap or free in a none image. A 10,000-message run uses exactly the same
RAM as a 10-message run.
4. Time
4.1 SysTick
M2 configures SysTick at 1 ms only when clock_ns, sleep_ms or tasks are reachable. The handler
increments a static u64 TICKS and returns. Reads use a short critical section because the counter
is 64-bit on a 32-bit core. clock_ns() is TICKS * 1_000_000, monotonic with 1 ms resolution. The
runtime uses a wrapping 64-bit multiply for this conversion; overflow is documented rather than trapped
(it is reached after about 584 years of uptime).
A mask longer than one tick loses ticks (M2). Runtime critical sections are tens of cycles; user
critical blocks must stay below a tick. A test with a long critical section records the loss instead
of pretending the clock is exact.
4.2 sleep_ms
sleep_ms(0)returnstrueimmediately and does not yield (M2).sleep_ms(n > 0)computes a deadline, setsSLEEP, inserts itself into the timer list and yields. It returnstrueon expiry andfalseif the scope is cancelled.- The deadline rounds up to the next tick: a sleep of
nms never returns early, and may return up to one tick late. Tests assertn <= elapsed <= n + 2ticks. sleep_msin aninterrupt fnis E177 (M3). In main it works because main is task 0.- If every task is asleep,
idleenterswfiuntil the next tick and the timer list is checked on wake.
4.3 Timeouts
A timeout is a select case with an absolute deadline computed once at select entry. It participates
in the same timer list and wakes the task through the same path. A timed-out select takes the timeout
case; if the timeout case is absent, the select is not timed out and the task re-blocks.
A false result alone does not distinguish close from cancellation from timeout. The select cases do; a
plain recv_timeout wrapper is deliberately absent in v1. A single-receive select with a timeout is
the supported form, and it composes with cancellation in one place.
4.4 Tickless idle
Tickless idle is feasible on Cortex-M (reprogram the SysTick reload to the next deadline) and on RV32 board timers, but it is not free:
- the tick handler must add the programmed interval, not one, and
clock_nsmust stay monotonic; - a new earlier deadline must re-arm the timer from task context, with the same mask/recheck protocol;
- RV32 timer adapters differ per board, and QEMU does not model their power behaviour;
- a rounding error turns into a missed or late deadline, which is worse than a wasted tick.
At 1 kHz a tick costs a few hundred cycles per second, under 0.01% of a 16 MHz core. The saving is
idle current, not CPU. M6 therefore keeps the periodic 1 ms tick and wfi, and leaves a
tasks.tickless profile option for a later power milestone. The HIL gate, not QEMU, would judge it.
5. Cancellation and errors
5.1 The flag
Each scope object has a cancel byte. It is set by the first child that fails, and by nothing else in
v1; there is no user-visible cancel() call. Setting it wakes every child blocked at a cancellation
point with false. A child checks it at every blocking operation and through cancelled().
5.2 Cancellation points
| Operation | On a cancelled scope |
|---|---|
send, recv, try_send, try_recv | return false |
sleep_ms | return false |
select | run the cancelled case, or return without a case |
cancelled() | return true |
join | not a cancellation point; waits for the child |
spawn | returns a handle; the child sees the flag at its first check |
join must wait: returning early would let the scope reuse a stack slot or spawn slot that the child
still owns. The child is responsible for observing cancellation and returning. A child that never
blocks and never calls cancelled() delays the scope indefinitely; the watchdog covers it, and the
all-blocked case traps.
5.3 Scope cleanup
Scope exit, in order:
- wait for every unjoined child (
joinsemantics, in spawn order); - for each unjoined child that failed, mark the scope failed;
- free every slot: the task stack returns to the pool, the TCB becomes
FREE; - the scope object stays in static storage and is reinitialized on the next entry;
- if the scope failed and the enclosing function is fallible with
! TaskError, fail withFailed.
There is no leak to check: stacks, TCBs and buffers are static. A second scope can reuse a slot immediately, and a test spawns 10,000 sequential tasks through four slots to prove it.
5.4 Why forced unwinding is out of scope
M6 cannot terminate a task that ignores cancellation:
- Kern has no destructors and no unwind tables. Forced termination would need either a cleanup protocol for every owned value or a wholesale reclaim of memory the task might still be using.
- A task may be inside
critical, inside an MMIO read-modify-write sequence, or holding a channel capability thatcloseis waiting on. Cutting it at an arbitrary instruction breaks the M3 device model. - On Cortex-M, unwinding means EHABI personality routines; on RV32 it means a second unwinder. Both are larger than the scheduler and the channel code combined.
- A fixed stack can be reclaimed wholesale only if nothing on it needs cleanup. That is true for scalars, but not for an owned heap slice, an arena or a handle, and the exceptions would be the values that matter most.
- Non-local exits make the schedule depend on where the cancellation landed, which is exactly the nondeterminism this design removes.
v1 is cooperative: the operation returns false, the task runs its own cleanup, and it returns
normally. The existing ownership checker already requires every continuing exit, including the
false path, to free or transfer every owner, so a cooperative exit is checked by rules that
already exist.
5.5 What a cancelled task may own
- It may own plain values, fixed arrays, structs and its stack frame. They disappear with the frame.
- It may own an
allocslice only if the MCU profile declared a heap; it must free it before returning, exactly as on any other exit.closeand channel capabilities are borrowed, not owned. - It cannot half-send: a send either completed (the value is in the ring and owned by the channel) or returned false. There is no pending value in the task's frame.
- It may write its result slot only on success. A cancelled child's result is discarded.
- It may not be mid-
criticalwhen it returns;criticalis a block with no early exit (M3 E176), so this is structural.
6. Memory
6.1 RAM map
RAM (20 KiB example)
+------------------------------+ high
| main stack (MSP, 1 KiB) |
+------------------------------+
| task stacks (max x 1 KiB) | PSP per task, one pool slot each
+------------------------------+
| task control blocks (32 B) |
+------------------------------+
| scheduler state (32 B) |
+------------------------------+
| scope objects (channels, | static per scope site
| result slots, cancel flag) |
+------------------------------+
| application .data / .bss |
+------------------------------+ low
M2's linker script already reserves __task_stacks and __main_stack; M6 fills the task region with
max named slots and puts TCBs, scheduler state and scope objects in .bss. There is no heap
(__heap_size = 0).
6.2 Per-item accounting
| Item | Bytes | Notes |
|---|---|---|
| Task stack | 1,024 | tasks.stack, 8-aligned |
| Task control block | 32 | one per task plus main |
| Channel (i64, cap 16) | 160 | 32 header + 128 buffer |
| Scope control | 8 | cancel, failed, padding |
| Spawn slot | 8-16 each | max(arguments, result), reused |
| Scheduler state | 32 | ready ring, timer array, indices, ticks |
| Main stack | 1,024 | main chain plus MSP handler headroom |
A task costs stack + TCB = 1,056 bytes. A channel costs 32 + capacity * sizeof(T). A scope costs
its channels plus slots plus 8. This is the whole accounting; nothing grows at runtime.
6.3 Two, four and eight tasks on a 20 KiB part
Assumptions: 20,480 B RAM, 1 KiB main stack, one scope with two i64/16 channels (360 B total),
512 B of application .data/.bss, 32 B scheduler state, one main TCB. Channel headers are sized at
MAX_TASKS = 8, so the scope figure is 8 B conservative at the default max = 4.
| Tasks | Task stacks | Task TCBs | Fixed | Total used | Free | Free % |
|---|---|---|---|---|---|---|
| 2 | 2,048 | 64 | 1,960 | 4,072 | 16,408 | 80.1 |
| 4 | 4,096 | 128 | 1,960 | 6,184 | 14,296 | 69.8 |
| 8 | 8,192 | 256 | 1,960 | 10,408 | 10,072 | 49.2 |
| 8 @ 512 B | 4,096 | 256 | 1,960 | 6,312 | 14,168 | 69.2 |
Fixed is main stack 1,024 + main TCB 32 + scheduler 32 + scope 360 + application 512. The table
excludes application stacks/arrays beyond the assumed 512 B; a real project substitutes its own
.data/.bss. At 1 KiB stacks, eight tasks fit and leave half the part; at 512 B stacks, eight tasks
leave 69%. The first configuration to reject is usually a channel buffer, not a stack.
6.4 What must be rejected at compile time
E161-E166 are the concurrency diagnostics defined in CONCURRENCY.md; E180-E189 are new and specific
to the MCU resource model.
| Check | Code |
|---|---|
Live task bound exceeds tasks.max | E180 |
| Spawn target signature, arity or error type | E161 / E181 |
| Spawn argument or task result is a view, slice, handle or task-local borrow | E162 |
| Task handle dropped, joined twice, self-joined or escapes | E163 / E164 |
close with a live sender or a shared borrow | E165 |
Task stack proof exceeds tasks.stack | E182 |
| Task pool, TCBs, scope objects or main stack exceed RAM | E182 |
| Channel capacity is zero, not a power of two, or over 256 | E183 |
Channel element has a slice/owner/handle, is over 64 B, or the channel exceeds tasks.channel | E184 |
Task or channel operation in an interrupt fn or critical | E185 |
select case is not a receive, timeout or cancellation | E166 |
select shape: zero cases, duplicate receiver, two timeouts | E186 |
| Scope object (spawns or channels) reachable from more than one task root, or a spawn/channel site in a loop inside its scope | E187 |
| Fallible task in an infallible function not explicitly joined | E188 |
| Call-graph cycle containing a spawn edge | E189 |
| Recursion in a task's call chain | M2 recursion error |
| Pool overlaps the main stack | linker ASSERT |
6.5 Report
kern size prints the accounting, and tests/run_embedded.sh checks it against the profile:
flash text 7,840 B data 120 B
ram .data 120 B .bss 944 B task stacks 4,096 B main stack 1,024 B
tasks max 4 stack 1,024 B pool 4,096 B scope 360 B budget 2,048
nm must show no allocator symbol. readelf must show .task_stacks inside RAM and .vectors at the
profile's load address. A growth over 5% against the committed baseline fails, as in M3.
7. Isolation
7.1 One address space, no MPU
All tasks share one address space. M6 has no MPU, no guard pages and no privilege levels. The language, not the hardware, provides isolation:
- no pointer type, no address arithmetic, no integer-to-address conversion;
- every array index and slice range is checked (M2);
spawnaccepts only moved values and channel capability handles (E162);- channel objects are in static scope storage, never in a task stack;
- a task result is copied out before the task stack is released.
A memory-safety bug that the language cannot catch is a stack overflow: with no MPU, a frame that exceeds its slot silently writes into the neighbouring slot or the TCB array. The primary defence is the static stack proof (§1.3); the secondary is a debug canary. The canary paints the lowest word of each slot and checks it at every switch and at task exit; a hit traps with kind 9. It costs one load and compare per switch and is compiled out of release images. A later MPU option (§12) would put a 32-byte no-access region below each stack and turn the overflow into a fault.
7.2 What crosses a scope
The rule is: only moved values and channel capabilities cross a task boundary.
- A moved value is copied into the task's argument block; the parent no longer owns it.
- A
&Sender/&Receiveris a one-word handle to a channel object in static scope storage. The child can call send/recv/close on it and nothing else. It cannot derive an address, index it, or reach the parent's frame. - An ordinary view or slice is rejected at the spawn site (E162), even if its lifetime would be long enough. The rule is syntactic and does not need a borrow analysis across suspension points.
- A result crosses back as a plain value, through the spawn slot. A slice, handle or borrow as the result is rejected for the same reason.
- Static storage is shared by all tasks, but
static varaccess is governed by M3's context rule, extended to task contexts (§2.7). The language does not expose the address of astatic, so it cannot be turned into a slice.
This is why the channel object must live in scope storage rather than on the parent's stack: a handle into another task's frame would be a view by another name. A scope site with channels is required to have one task root (E187), which keeps the object's address static and its lifetime exactly the scope.
7.3 What is not protected
| Hazard | M6 position |
|---|---|
| Stack overflow | static proof, debug canary; no hardware guard until an MPU option |
| Wild write through a compiler bug | same as a hosted bug; no MMU to contain it |
| Handler reading half-updated task state | M3's critical rule; fault handlers are outside the model |
| DMA or a second core | out of scope; M6 is single-core, no DMA |
| Denial of service by a non-cooperative task | watchdog; no forced termination |
The claim is precise: no source program can name or mutate another task's stack, and no scheduler or channel data structure is touched concurrently. It is not a claim that a hardware fault is contained.
8. Testing
8.1 Harness
Runtime tests live in tests/embedded/tasks/<case>/ with src/main.kn, kern.target and an expect
file, and run through tests/run_embedded.sh: build, run QEMU with a 10 s wall-clock timeout, check
the exit code and the kern-test: lines, and check the size budget. Boards: mps2-an385
(Cortex-M3) is the primary gate; sifive_e (RV32) is the second; netduinoplus2 (M4F, FPU off) is
optional.
Compile-time diagnostics are ordinary host tests in tests/test_tasks.sh and
tests/errors/E18*.kn; they need no QEMU. examples/mcu/tasks_*.kn holds the readable sketches.
8.2 Case list
| Case | Asserts |
|---|---|
order | three siblings push their id to a channel; main sees spawn order |
nested | a task spawns a child; both stacks come from the pool; scope exit joins |
join_value | a computed result crosses the scope and is not aliased |
error_cancel | a failing child wakes a blocked sibling with false; join returns Failed/Cancelled |
pingpong | two tasks exchange 1,000 messages through capacity-1 and capacity-16 channels |
close | close after join wakes every receiver; buffered values drain first |
select_order | two ready channels; source order wins on 100 consecutive runs |
timeout | select timeout fires within n..n+2 ticks; a ready receiver beats an expired timeout only if it comes first |
fairness | a CPU-bound loop yields at the budget; a heartbeat task runs at least once per 10 ms |
blocked_wakeup | no lost wakeup: a receiver registers, the sender sends, the receiver sees the value |
sleep_idle | all tasks sleep; the scheduler reaches wfi; the wake is correct |
cancel_select | cancellation during a select runs the cancel case or returns clean |
stack_reject | a chain over tasks.stack is E182; a canary-injection build traps kind 9 |
pool_reject | 9 live spawns is E180; the runtime pool check traps 7 under injection |
deadlock | all tasks blocked with no timer traps kind 8 |
throughput | 10,000 messages complete, in order, no loss, under the time gate |
memory | nm has no allocator; the pool and .bss match the report; .vectors is at the base |
isr_flag | a handler publishes a word; a task drains it; a channel op in the handler is E185 |
recursion | a spawn cycle is E189; direct recursion is the M2 error |
8.3 QEMU and hardware
| Behaviour | QEMU | Hardware |
|---|---|---|
| Ordering, FIFO, select scan, cancellation | yes | no |
| Blocked wakeups, close, backpressure, 10k messages | yes | no |
| Timeout and sleep semantics | yes (tick model) | tick accuracy and drift |
| Stack proof and pool budget | compile/link | real SRAM and silicon |
| Stack overflow fault | canary injection only | MPU guard, real fault |
| Throughput in cycles | -icount proxy | DWT CYCCNT, 16/72 MHz |
wfi entry and wake latency | not observable | current draw, latency |
| Interrupt latency and priority | not cycle-accurate | logic analyser |
| 20 KiB part fit | linker map | actual board |
The 10k-message gate has two forms. In QEMU it is functional: 10,000 i64 values, exact order,
no loss, completion under the wall-clock timeout, with -icount for repeatability. On hardware it is
a cycle budget measured with CYCCNT: an initial target of under 200 ms at 16 MHz for a capacity-1
ping-pong and under 100 ms for capacity 16. The numbers are calibrated, not asserted from QEMU.
8.4 Size gates
| Feature | Incremental .text ceiling | Notes |
|---|---|---|
| Scheduler, switch, spawn/join, loop poll | 1,024 B | M2's task line, excluding bodies and stacks |
| Channels | 256 B per element type | ring ops, close, wait arrays |
select and timeout | 384 B | up to four cases, timer list included |
| Total task feature | 1,664 B | measured and reported per architecture |
M2's 1,024 B line becomes the first row of this table; the sum is the honest feature cost. The image
gate stays EMBEDDED.md's: two tasks and two channels within 10 KiB flash and 4 KiB RAM. Any ceiling
change is an explicit, evidenced revision, not a silent relaxation.
9. Phases
Each phase lands in stage0 first for iteration speed. T3 is the parity gate: the self-hosted compiler must pass the same embedded suite before M7. No phase is done until the hosted suite is unchanged.
| Phase | Deliverable | Acceptance |
|---|---|---|
| T0 | scope/spawn/join/Task, static pool, TCBs, ready queue, context switch, loop poll, scope teardown, traps 7/8, E180-E182/E188/E189 | order, nested, join_value, 10k sequential spawn/join, stack/pool rejection fixtures, no allocator symbols, +1,024 B text, pool exactly max * stack |
| T1 | Channels, ring, send/recv/try, close, waiter FIFO, backpressure, E183-E185/E187 | pingpong, capacity 1 and 16, close, two consumers, 10k messages, constant RAM, +256 B per element type |
| T2 | select, timeout, sleep_ms on the timer list, cancelled(), idle wfi, deadlock trap, E186 | select_order 100 runs, timeout within the tick window, all-asleep wake, cancel during select, +384 B |
| T3 | ISR interop, critical/static var context rules, size gates, SPEC/README, self-host parity, HIL smoke | Embedded suite green on stage0 and the self-built compiler, hosted suite unchanged, kern size within budget, self-host proof byte-identical, one STM32 and one ESP32-C3 smoke |
T0 acceptance details:
- the largest proven chain is printed per spawn site; a chain of 900 B fits a 1 KiB stack on M3 and is
rejected on RV32 with
isr_stack = 256because900 + 56 + 256 + 64 > 1,024; - 10,000 sequential spawn/join cycles reuse four slots and leave the pool counter at zero;
- a fault-injection build whose pool counter reports one extra free slot traps kind 7 on the next
spawn beyond the real pool (with
max = 8, the ninth).
T1 acceptance details:
- a capacity-1 channel with one producer and one consumer transfers exactly 10,000 values in order, with no lost wakeup, in both 16-bit and 32-bit element widths;
closewith a buffered value lets the receiver drain it, then reportsfalse; two receivers both see the close;nmis unchanged between a 10-message and a 10,000-message image.
T2 acceptance details:
select_orderproduces byte-identical output over 100 runs and over two QEMU-icountsettings;- a 10 ms timeout returns between 10 and 12 ticks, including when another task is runnable;
- a main-only program that sleeps reaches the idle path and wakes on the tick; HIL records current;
- cancelling a task blocked in a three-case select removes it from all three lists and leaves the lists empty.
T3 acceptance details:
tests/test_selfhost_cli.sh build/kern-stage0 --host-onlyis byte-identical with tasks in the compiler's own test program;- the hosted corpus
sh tests/run.sh --host-only build/kernis untouched; kern sizematchestests/embedded-size.jsonwithin 5% fortasks_2,tasks_4andtasks_8;- the STM32F103 HIL image prints the same
kern-test:lines as QEMU.
10. Files and impact
10.1 Stage0 (Rust)
| File | Change |
|---|---|
src/lex.rs | keywords scope, spawn, select; channel, Task, Sender, Receiver stay names |
src/ast.rs | Stmt::Scope, Expr::Spawn, SelectStmt, Ty::Task/Sender/Receiver, task builtins |
src/parse.rs | scope block, spawn call, select cases, channel instantiation |
src/check.rs | spawn signature and error type, channel capacity/element, select shape, cancelled |
src/ownership.rs | affine Task, capability copies, scope lifetime, close-exclusive, result rules |
src/target.rs | tasks.* profile keys and validation |
src/effects.rs | critical-safe and task-context summaries, ISR extension for task ops |
src/sched.rs (new) | live-task traversal, scope-site root count, stack/TCB/scope budget report |
src/gen.rs, src/gen/stmt.rs, src/gen/expr.rs | scope prologue/epilogue, spawn trampoline, join, channel ops, select, loop poll |
src/gen/runtime.rs, src/gen/support.rs | ready queue, blocked lists, timer list, switch, idle, traps |
src/gen/board.rs | task stack slots, scope objects, .bss layout, trap kinds 7-10 |
src/size.rs | task, channel and scope accounting in kern size |
src/rules.rs | poll-suppressed and dispatch rules; no new style rules |
src/format.rs | canonical formatting for the new forms |
10.2 Self-hosted (Kern)
| Area | Files | Change |
|---|---|---|
| Lexer/model/parser | lexer/*, model/*, parser/* | the same forms and tables |
| Typing/ownership/effects | typing/*, ownership/*, effects/* | task and channel checks, critical-safe, task contexts |
| Backend | backend/*, new tasks.kn, select.kn | prologue, trampoline, channel code, select, poll, reserved r7/s0 |
| Runtime | runtime_mcu/*, runtime/emit.kn | scheduler, queues, timer, switch, idle |
| Target/size | target/*, size/* | tasks.*, accounting |
| Tests/format/spec | runner/*, format/*, spec/print.kn | parity with stage0 |
10.3 Spec, tests, docs
SPEC.md gains the forms, E161-E166 and E180-E189; compiler/src/spec/print.kn is regenerated. tests/test_tasks.sh,
tests/errors/E18*.kn, tests/embedded/tasks/, tests/run_embedded.sh, examples/mcu/, README.md
and EMBEDDED.md follow the phases. This document is the design commit; code is out of scope.
11. Risks
- Stack overflow is silent without an MPU. The proof is the only real defence; a compiler bug in the chain calculation corrupts memory. Mitigation: print every chain, keep the 64 B margin, run the canary in debug, and add the MPU option before claiming hard isolation.
- Scope storage is static per site. A channel in a helper function reached from two tasks is rejected (E187). Mitigation: a clear diagnostic with the two roots named, and the shared-channel idiom; a scope-frame pool is the upgrade path.
- The live-task analysis is conservative. It can reject a program that would fit if two roots never overlap. Mitigation: report the offending path; the trap backstop covers an under-count.
- A non-cooperative task hangs its scope. Cancellation is checked only at blocking points and
cancelled(). Mitigation: watchdog, the all-blocked deadlock trap, and tests that fail fast. - The loop poll taxes every back-edge. Two instructions is cheap, but a tight DSP loop pays it.
Mitigation: profile-tunable budget, suppression in ISRs and
critical, and a benchmark. - Reserved r7/s0 is an ABI commitment. Every generated function and every external AAPCS helper must preserve it. Mitigation: both are callee-saved in their ABI; a startup test checks that a compiler-helper call preserves the budget.
criticaland the poll interact. Suppressing the poll in everycritical-reachable function can make a normally-called loop non-preemptible. Mitigation: keep critical-reachable code short, report the set, and test the normal call.- QEMU timing is not silicon. Throughput and wake latency gates are proxies. Mitigation: cycle
counts on HIL,
-icountfor repeatability, and no timing assertion based on QEMU wall clock. - Both compilers double the work. Mitigation: stage0 first, T3 parity gate, hosted corpus unchanged from T0.
- Tick loss under long masking. A user
criticalover 1 ms drops ticks, andsleep_msbecomes late. Mitigation: the M2 warning, a measured test, and a rule of thumb in the docs.
12. Open decisions and recommendations
12.1 Stack size defaults
Options. (a) Uniform 1 KiB for every task. (b) Uniform 512 B, relying on the proof to reject deep
chains. (c) Per-spawn stack= from day one.
Recommendation: (a). 1 KiB covers a 880 B chain on M3 and a 648 B chain on RV32 with a 256 B ISR allowance, which is comfortable for driver code. It costs 1,056 B per task, and the 2/4/8 table shows four tasks at 30% of a 20 KiB part. 512 B is allowed where the proof fits (leaf tasks on M3) and is the first tuning step after the report. Per-site sizes (c) are a real optimisation but they complicate the pool, the trampoline and the report; defer until measurements show the uniform pool is the constraint.
12.2 Task count
Options. (a) 4 default, 8 hard. (b) 8 default. (c) 16 with 16-bit ids.
Recommendation: (a). Four covers the common sensor/actuator/protocol/control split. Eight is the hard maximum because ids, wait lists and select masks are one byte, the ready queue is eight entries, and a 1 KiB stack at eight tasks already uses half of a 20 KiB part. Raising the limit needs wider ids and a new memory table; it is a profile change, not a runtime change.
12.3 Preemption budget
Options. (a) 2,048 back-edges. (b) 10,000, matching the desktop plan. (c) A tick-based slice.
Recommendation: (a). At two cycles per fast-path back-edge, 2,048 is about 4k cycles, 0.25 ms at 16 MHz and 0.06 ms at 72 MHz, so a heartbeat task sees the CPU promptly. 10,000 would be about 1.25 ms at 16 MHz in the best case, which is too coarse for a 1 ms tick. A tick-based slice (c) needs a timer interrupt that switches, which breaks the "no ISR switch" rule and adds a second preemption source; keep the loop poll. Make the number a profile key and calibrate it on HIL.
12.4 Does select ship with channels?
Options. (a) Channels in T1, select in T2. (b) Both in T1. (c) select last, after integration.
Recommendation: (a). Channels are useful without select: try_recv, close and one blocking
receive cover most drivers. select needs the timer list and the multi-list registration, which are
T2 work; shipping it early would either delay channels or grow T1 past its size gate. The select
surface is small and additive, so a program written for T1 keeps working when T2 lands.
12.5 Secondary decisions
| Decision | Recommendation | Reason |
|---|---|---|
| Task error type | TaskError only in v1 | one concrete error type; payloads go in T or a channel |
| Pool exhaustion | compile-time E180, trap 7 backstop | spawn stays infallible; the proof is the contract |
| Scope storage | static per site, one root (E187) | no heap, no view into a task stack; minimal RAM |
| Channel capacity | power of two, 1..=256 | mask wrap, one instruction, bounded RAM |
| Channel element | fixed size, 64 B max | small copy loops, predictable code size |
recv failure | writes nothing, returns false | no zero value or Option; the caller keeps its storage |
select order | cancellation first, then source order | deterministic and easy to test |
join cancellable | no | protects the stack and result slot |
| Tickless idle | not in T0-T3 | power, not CPU; HIL-only judgement |
| MPU stack guard | later opt-in | per-switch region programming; RV32 PMP differs |
Explicit cancel() | not in v1; add if deadline patterns demand | the failure path already cancels |
| PSP vs single stack | PSP on Cortex-M, single stack on RV32 | M3's handler model; RV32 has no PSP |
Shared/Atomic | out of scope | critical is the primitive; no memory model until threads |
13. What M6 does not do
- No parallel execution, SMP, second core or DMA.
- No task priorities, work stealing or time-sliced preemption; only the loop poll and blocking yields.
- No forced termination, unwinding or
defer. - No heap, no growable stacks, no unbounded queue, no dynamic task creation beyond the static pool.
- No MPU, guard page or hardware isolation.
- No channel operation in an interrupt handler;
static varpluscriticalis the ISR-to-task path. - No
Shared/Atomicand no memory-order model. - No tickless deep sleep, low-power mode or power management.
- No hosted task runtime;
CONCURRENCY.mdC0-C7 on macOS/Linux remains a separate, later track that should adopt these semantics. - No Xtensa, no FPU context save, no cache maintenance.