Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Task operations

(snail shell task) defines tasks and the scheduler that runs them, both in snail-scheme:

OperationMeaning
(dispatch work)Run a thunk as an independent local task.
(yield)Let every other ready task run first.
(sleep milliseconds)Wait for an I64 number of milliseconds.
(ticket)A fresh I64 ticket, naming one wait.
(await tickets)Wait until every ticket in the list is woken.
(tasks-wake! scheduler ticket)Cross the ticket off the task waiting on it, readying the task once none is left; a stale ticket does nothing.
(tasks-close! scheduler)Forget every queued, sleeping and waiting task; none runs again.
(through-host start finish)Wait on a host operation by ticket (below).
(make-mailbox)A new, empty (Mailbox T): a queue of messages between tasks.
(mailbox-post mailbox message)Add a message at the back. Posting never waits.
(mailbox-receive mailbox)Take the message at the front, waiting until one is posted.
(mailbox-try-receive mailbox)Take the message at the front, or answer None at once when there is none.
(import
 (snail core base)
 (snail core io)
 (snail shell task))

(define (main (out OutputPort)) (→ Unit)
  (dispatch
   (lambda ()
     (yield)
     (write-line out "the child finishes after main returns"))))

A task waits by suspending: yield, sleep and await stop it where it is, however deep in its calls, and the scheduler keeps the rest of it. Waiting needs no capability and is in no type, so an ordinary function may call a callback that waits, and a function that waits is written like any other.

The host creates one explicit Scheduler for a program and passes it to the program’s main export, turns, wakes and closure. That export is the entry’s start, which calls its target library’s start with the scheduler and a thunk that calls the root main with its capabilities, so main runs as the scheduler’s first task and may yield, sleep or await like any other task. A child starts when the parent yields or returns. Every task runs until it finishes: nothing cancels one. Tasks that should stop early agree on it between themselves, for example through a mailbox or a flag in a record they share. A trap fails the run. The host reports it and closes the scheduler, which forgets its queued work; Wasm traps do not unwind, so nothing more runs in the trapping frame. Whole-program and separately linked builds use this same explicit scheduler. Libraries have no runtime initializers.

The operations are not actors: there are no request/reply protocols or supervisors. A task’s id names it to the host, which reports a trap under it, and to an application, whose loop is a task (applications).

How a task runs

A task is a function that runs one step of it. Its first step runs the work under a with-prompt of the prompt every wait suspends to, waiting, whose handler does not resume: it answers a Step holding the rest of the task, to run when the wait is over.

(enum Wait
  (Yield)
  (Sleep ((delay I64)))
  (Await ((tickets (List I64)))))

(define waiting (→ (Prompt Wait Unit)) (make-prompt))

(define (start-task (work (Fn → Unit))) (→ Step)
  (with-prompt waiting
               (lambda ()
                 (work)
                 (Finished))
               (lambda (wait resume) (Stopped wait (lambda () (resume (unit)))))))

(enum Step
  (Finished)
  (Stopped ((wait Wait) (next (Fn → Step)))))

The scheduler keeps every task that is not running in exactly one list: the ready tasks, the timers, sorted by deadline, or the waiters, by ticket. A turn takes the ready list whole and runs those tasks, so tasks that yield to each other cannot keep the host from its events, files each step where it says, then readies the sleepers whose deadline has passed. tests/programs/tasks.sld shows the order: yields interleave, sleepers with one deadline wake in the order they slept.

A task holds what it uses in its closures, so a child keeps the capabilities its parent handed it after the parent returns, and at every resumption. A waiting task holds no stack. Its with-prompt returned when it waited, through each frame of the work, which saved the rest of itself in the resumption (resuming).

A task asks for tickets and dispatches children without being handed its scheduler: a turn notes the scheduler it runs each step for, and ticket, dispatch and a mailbox’s wait read that. It is the library’s one piece of state outside a scheduler, set and restored around each step.

Scheduling

The policy is cooperative first-in, first-out, with no priorities:

  • dispatch adds a new task to the ready list. A turn begins by taking the whole list, leaving an empty one, and runs what it took in the order it became ready; a task that yields joins the new list, so it runs again only in the next turn. Tasks that yield to each other therefore cannot keep the host from its events.
  • sleep moves the task to the timers, kept sorted by deadline, a new timer after every timer due no later, so sleepers with one deadline wake in the order they slept. After the ready tasks have run, every timer whose deadline has passed joins the ready list, in deadline order.
  • await parks the task among the waiters, holding its tickets. When a host operation settles, the host calls wake with its ticket, which crosses it off; a waiter with none left moves to the ready list. A ticket nothing waits on wakes nothing, as after a trap or a close.
  • Between turns, turn answers what the host should do next (driving the scheduler): 0 when a task is ready, the milliseconds until the earliest deadline, -2 when every live task waits on a ticket, and -1 when no task is live.
  • After a trap, running still names the trapped task for the host’s report, and the host closes the scheduler instead of running more tasks.

Scheduler is an ordinary record whose fields hold its lists as immutable values. Closing marks the scheduler closed and empties every list. A task that stops after its scheduler has closed is forgotten, as is the rest of the turn’s tasks, and a late wake finds nothing.

Locality

Dispatched work is an (Fn → Unit): what it may change is what it closed over. It may suspend to any prompt whose with-prompt runs inside it; a suspension to a with-prompt around the dispatch finds none running when the task runs later, and panics there (prompts).

A program can run tasks itself, for a simulated clock in a test or a scheduler of its own: make-scheduler, dispatch-in and tasks-turn are ordinary functions, and a with-prompt of its own prompt gives it waits of its own (tests/programs/prompt-handoff.sld hands the rest of a generator from one task to another).

Local dispatch may capture shared mutable objects, because the work stays in this single-threaded instance. Work for another instance travels as bytes through a queue, never as a closure (#553, proposed).

Only yield, sleep and await let other tasks run. Console and the core Fs services remain synchronous; using a capability does not by itself wait, and the scheduler does not preempt a CPU loop. Dispatching a filesystem operation from (snail core io) defers it but does not make the kernel operation asynchronous; the native capability below supplies asynchronous reads.

Native asynchronous file reads

(snail shell async-files) exports the capability Files. Its read-file : Files String I32 -> Result<Bytes, FileError> reads an entire file up to the supplied byte limit. It suspends the calling task while other tasks run. A task that has other work meanwhile dispatches the read and receives its result through a mailbox:

(let ((results (make-mailbox)))
  (dispatch (lambda ()
              (mailbox-post results (file-read-file files "notes.txt" 1048576))))
  ;; Other work can happen here; dispatch did not wait.
  (consume-result (mailbox-receive results)))

Here file-read-file is imported with a file- prefix, and the dispatched task closes over the Files it was handed (tests/async-files/main.sld).

Limits range from zero through 16 MiB. The host reads at most limit plus one bytes, distinguishing an exact fit from TooLarge; metadata is not proof that the subsequent read fits. Other error values are Unavailable, InvalidInput, NotFound, PermissionDenied, and Failed. Reads of a changing file are not snapshots. This first capability does not change core filesystem operations.

Node does each read with its asynchronous file system (host/native/async-files.mjs): it opens the file, reads at most the limit plus one bytes, and closes it, while the program’s other tasks run. There is no periodic polling and no worker pool of the language’s own; Node’s event loop wakes the read’s ticket when it completes. A page has no Files, since it has no file system to read.

A suspended read holds only its request’s id. The host keeps the path, the buffer and the file handle until the read completes, then closes the file before letting the operation go. A completed result whose ticket wakes no task, because the task trapped or the run closed, is discarded.

Only scalar operation IDs, tickets, path characters and bytes cross the host boundary. The runtime makes the managed Bytes after the read completes, so no managed object is shared with the host while it reads.

Mailboxes

A Mailbox is how tasks hand each other values. Messages are received in the order they were posted. Its queue of messages and the wakers of the tasks waiting for one are snail-scheme data in its fields: tasks share a mailbox, so its contents are the one piece of state this library cannot thread through a single task. A post queues its message and wakes every waiting task, and each takes a message for itself when it runs; one that finds none waits again. Each message, such as a work item, goes to exactly one receiver, and no message is handed to a task that may never run, as one whose scheduler closed. The price is fairness: a task that asks while a message waits takes it, even ahead of receivers woken for it that have not run yet (tests/programs/mailbox-order.sld). The name is mailbox-receive, not receive, because (snail shell socket) exports UDP’s receive, and a program importing both libraries would have conflicting imports.

(let ((mailbox (make-mailbox)))
  (dispatch (lambda () (write-line out (mailbox-receive mailbox))))
  (dispatch (lambda () (mailbox-post mailbox "hello"))))

A receiver that finds the queue empty takes a ticket, keeps in the mailbox a waker, (Fn → Unit), closed over its scheduler and that ticket, and awaits the ticket. A waker only moves its task to the ready list, so any code may call it: another task, or code between turns. A call after the task was woken, or once its scheduler has closed, wakes nothing. A waiting task does not run again until it is woken, so waiting costs nothing while nothing is posted, where a loop of yields would run every turn. tests/programs/mailbox.sld has two tasks posting and one receiving.

Waiting on the host

A host operation that completes later, such as a socket read, waits the same way. The host’s capability takes a ticket, starts the operation on the host, which reads its arguments and returns at once, awaits the ticket, and finishes by taking the result the host built for it:

(define through-host
  (lambda (start finish) (let ((id (ticket)))
    (start id)
    (await (list id))
    (finish id))))

(snail shell socket), (snail shell process) and the application’s event and storage waits all wait through through-host, from whichever task called them. Waiting needs no lock, because a task runs until it waits: nothing else runs between taking a ticket and awaiting it, so neither a post nor a host completion can come first.

A task may also start several operations and await them together: (await tickets) parks it until every one has completed, and each completion only crosses its ticket off, so the order they settle in does not matter. read-resources in (snail shell resource) reads a program’s linked files this way, so a page fetches them together rather than one after another.

The host boundary

The host sees the scheduler only through five exports of (snail shell task):

ExportMeaning
tasks:turn nowRun a turn at the host’s clock, in milliseconds. Answers 0 when a task is ready, -1 when none is live, -2 when every live task waits on a ticket, and otherwise the milliseconds until the next deadline.
tasks:wake ticketReady the task waiting on a ticket, answering whether one was.
tasks:closeForget every task, as ending a program does.
tasks:runningThe id of the running task; after a trap, the task that trapped.
tasks:liveHow many tasks have not finished.

A host’s loop calls turn, rests until the answer says, or until a completion wakes a ticket, and calls it again until no task is live (host/browser/tasks.mjs’s drive). A trap unwinds out of turn. The host reports the trap under tasks:running, closes the scheduler and ends the run. An answer of -2 while no host operation is outstanding is a deadlock: no completion will wake a ticket, so the run fails.

A host operation’s start and finish are synchronous imports. host/browser/tasks.mjs keeps each outcome under its ticket until the finish takes it. The finish answers with numbers, from which the library builds its result in the waiting task’s own call; a host never builds a managed value (the native boundary). An outcome whose ticket wakes nothing, because its task trapped or its run closed, or that is still held when the run closes, is disposed of instead: an accepted connection is closed.

Tickets count from 1 in each scheduler. Every wake names its scheduler as well as its ticket: a host’s through the scheduler it created, and a waker’s through the scheduler it closes over. A restarted run has a new scheduler, so a waker that a Mailbox in the application’s state kept from the old one finds that scheduler closed and wakes nothing in the new one.

A task runs on the host’s ordinary Wasm stack, and keeps none while it waits. Deep non-tail recursion can overflow it; use tail calls for loops requiring constant stack space.