SCUA 0.43.0 lets every partition read the same copy of a large frozen
value. Freeze an array, a table, a record or a string of 64 KiB or more,
send it to as many workers as you like, and each one reads that one
value in place, with nothing copied on the way. The release also adds an
append-only log to durable, Argon2id password hashing,
return, break and continue inside
a value match or if, and a
sys.readline that lets the rest of the program keep running
while it waits.
#A large frozen value is now shared, not copied
freeze a value of 64 KiB or more (1 MiB on Windows),
counting everything inside it, and every partition you send it to in a
tell, an ask or a reply reads the same one. A
fan-out that gives four workers the same frozen data now holds one copy
of it, which keeps the workers' data in the processor's cache. The send
costs nothing however large the value is: a 12.8 MB record of 24 columns
reaches four workers in under a millisecond.
Because a shared send is free, you can pass the data with every
ask:
fn readings(n)
let xs: { f64 } = []
for i in 0:n do push(xs, (i % 101) * 0.5) end
return xs
end
partition Worker
ask Sum(xs, lo, hi)
let s = 0.0
for i in lo:hi do s = s + xs[i] end
return s
end
end
let data = freeze(readings(1000000))
let ws = [Worker(), Worker(), Worker(), Worker()]
let sums = map_all(range(0, 4), fn(k)
return ask ws[k].Sum(data, k * 250000, (k + 1) * 250000) timeout 10s
end)
print(sums)
$ scua shared.scua
[6249525.0, 6249837.5, 6250150.0, 6250462.5]
$ scua --mem-stats shared.scua 2>&1 | grep -oE 'shared=[0-9]+|shared-holds=[0-9]+|freezes-[a-z]+=[0-9]+'
shared=8388640
shared-holds=5
freezes-moved=1
freezes-copied=0
The program holds 8 MB of readings once: the main script and the four
workers read the same array. Your code does not change: the value is
frozen in every partition, and a write to it faults with the same
message as before. When freeze does make a copy, it now
writes it straight into the shared area, so freezing that 12.8 MB record
takes 3 to 4 ms.
Four workers, one copy of the data goes into how the sharing works and the cases where SCUA still copies.
#freeze now moves a value instead of copying it
freeze gives you a frozen copy and leaves the original
as it was. When nothing else holds the original, there is nothing to
keep, so freeze now freezes the value where it is. That
covers a value made in the function that freezes it and not used after
the freeze: a literal, a fill, a string joined
with .., bytes read with fs.read,
or the result of a function in the same file that only ever returns
values like these. readings above is one, which is why the
run counts freezes-moved=1.
At 64 KiB or more the value moves into the shared area, and a large
array's or bytes value's storage goes with it untouched.
Freezing a freshly built 3.2 MB array of numbers takes no measurable
time. A parameter, a value stored somewhere else and a local used after
the freeze are still copied, and
freezes-copied= counts them. See freeze.
#durable now supports an append-only log
durable.append(f, entries, version, T) writes a batch of
entries to the end of a file in one write, after checking every entry
against T. A batch with one bad entry is an
Error naming it, and nothing is written.
durable.read_stream(f) and
durable.next(stream, T) read the entries back one at a
time, however long the log is:
import durable
import fs
enum Change { Placed(money), Paid, Refunded(string) }
record Entry { seq: int where seq >= 1, order: int, change: Change }
let w = fs.open("orders.log", { mode = "append" })?
print(durable.append(w, [
{ seq = 1, order = 42, change = Change.Placed(19.99 USD) },
{ seq = 2, order = 42, change = Change.Paid },
{ seq = 3, order = 42, change = Change.Refunded("damaged") },
], 1, Entry, { sync = true }))
print(durable.append(w, [{ seq = 0, order = 43, change = Change.Paid }], 1, Entry))
fs.close(w)
let r = fs.open("orders.log")?
let log = durable.read_stream(r)
let item = durable.next(log, Entry)
while item != nil do
let e = item?
print(`#{e.seq} order {e.order}: {e.change}`)
item = durable.next(log, Entry)
end
fs.close(r)
$ scua --allow-fs orders_log.scua
Ok({frames = 3, bytes = 220, offset = 8, head = nil})
Error({record = Entry, field = seq, value = 0, message = durable.append(w, values, …, Entry): values[0].seq violates Entry's where rule (got 0), path = values[0].seq, at = [0].seq})
#1 order 42: Change.Placed($19.99)
#2 order 42: Change.Paid
#3 order 42: Change.Refunded(damaged)
{ sync = true } returns once the batch is on the disk.
Each entry is a durable value, converted on the way out as
durable.decode converts a save, so entries of several
schema versions share one log and migrate upgrades the old
ones. Pass chain and each entry is linked to the one before
it by a SHA-256 hash, so an entry that was changed or moved is reported.
A write cut short by a crash is reported once, as a
torn_tail with the offset to cut the file at.
durable.encode_log gives the same bytes without a file,
and durable.read_stream reads a bytes value as
well, so a log works in a sandbox and over a socket. Keep an append-only log
covers chains, crash recovery and the file format.
#sys.readline no longer stops the program
While the top level waits for a line, spawned tasks, the
timers they set with wait, and partitions all carry on. A
stdio server can poll or send a heartbeat between requests without a
second process, and a prompt can show progress while the person
types:
import sys
let beats = 0
let answered = false
spawn(fn()
while not answered do
wait(250ms)
beats = beats + 1
end
end)
sys.write("Your name: ")
let name = sys.readline()
answered = true
print(`hello, {name}; {beats} heartbeats while you typed`)
$ scua --allow-tty heartbeat.scua
Your name: Ada
hello, Ada; 11 heartbeats while you typed
With nothing else to do, the program waits for the line without using
CPU. match pcall(sys.readline), the usual way to catch the
fault for a line over 1 MiB, keeps the program running too. Put the read
inside within to give up at a deadline: what was typed so
far is kept for the next read. sys.readpassword, a run
under --fast and the WebAssembly build still hold the
program while they read. See The
rest of the program keeps running and
examples/prompt_heartbeat.scua.
#match and if can now return, break or continue
An arm of a value match, or a branch of a value
if, can be a single return, break
or continue. That arm leaves the function or the loop, and
the other arms give the value:
import int
fn ports(lines)
let found = []
for line in lines do
let port = match int.parse(line)
Ok(n) -> n
Error(_) when line == "" -> continue
Error(e) -> return Error(`{line}: {e}`)
end
let open = if port >= 1024 then port else continue end
push(found, open)
end
return Ok(found)
end
print(ports(["8080", "", "443", "9000"]))
print(ports(["8080", "eighty", "9000"]))
$ scua ports.scua
Ok([8080, 9000])
Error(eighty: not an integer)
return can be bare or carry values, and it is checked
against the function's declared return type like any other. A bare
return arm in a statement match now ends at
its line, so another arm can follow it. See Control flow and A match as a
value.
#Passwords can now be hashed with Argon2id
crypto.argon2id_hash(password)? gives a string with a
fresh random salt and its settings inside, in the standard format other
Argon2 libraries read and write. Store it, and check a login with
crypto.argon2id_verify(typed, stored):
import crypto
-- when the account is made: keep this string, never the password
let stored = crypto.argon2id_hash("correct horse battery staple")?
print(stored)
-- at login
print(crypto.argon2id_verify("correct horse battery staple", stored))
print(crypto.argon2id_verify("Tr0ub4dor&3", stored))
-- a row changed to ask for 4 GiB is refused before anything is allocated
let tampered = "$argon2id$v=19$m=4194304,t=2,p=1$c29tZXNhbHQ$CTFhFdXPJO1aFaMaO6Mm5c8y7cJHAph8ArZWb2GRPPc"
print(crypto.argon2id_verify("password", tampered))
$ scua login.scua
$argon2id$v=19$m=19456,t=2,p=1$xwITNI8+gPSmCoUKtw5Rcw$pJ0LUkkFOTRqqaezHlEzy9nYPQnQfKLVGzW4XAP/qA0
Ok(true)
Ok(false)
Error({kind = limit, message = argon2id_verify: 4194304 KiB of memory is above this call's limit of 65536 KiB. If the parameters come from data you trust, raise it with { max_memory_kib = … }})
Every guess costs an attacker memory as well as time, so Argon2id is
now the way to store passwords in SCUA. The defaults are OWASP's
recommended settings: 19 MiB, two passes and one lane. The settings in a
stored hash come from your database, so they are checked before anything
is allocated: by default at most 64 MiB and at most sixteen passes over
that much, and less if --max-mem or a sandbox's
memory leaves less free.
crypto.argon2id(password, salt, opts?) derives raw bytes
for a key, and crypto.pbkdf2 stays for formats that specify
it. See Storing
a password to check later and
examples/password-hash.scua.
#Live feeds can now end when the server stops
A response stream has a stopping field. An event feed
that checks it can finish its body and return as soon as a stop reaches
its grace, so stopping a server doesn't wait out the whole grace, 25
seconds by default, for every browser tab left open:
import http
fn handle(req)
let s = http.start(req, { headers = { "content-type" = "text/event-stream" } })?
let n = 0
while not s.stopping do
select wait(500ms) -> nil end
n = n + 1
if s.write(`data: {n}\n\n`) matches Error then break end
end
let _ = s.finish()
return nil
end
http.serve(handle, { bind = "127.0.0.1:8080" })?
Run it with scua --allow-serve=127.0.0.1:8080 feed.scua,
open the feed with curl -N http://127.0.0.1:8080/, and
press Ctrl-C in the server's terminal. The feed ends at its next tick,
curl gets a complete response, and the server prints
scua: stopped cleanly: 1 request answered while stopping.
During the drain delay that --serve-drain-delay sets,
stopping stays false and the feed keeps
serving. From the grace on, s.write returns
Error({ kind = "stopping" }) instead of writing, so a feed
that only checks its writes ends too. The server never ends a stream
itself, so a long download that checks neither still has the whole grace
to finish. See When
the server stops.
#Smaller additions
fs.truncate(f, size)cuts the file behind a write handle tosizebytes. It is how you cut a log's torn tail, or undo a failed write. A handle opened with"append"then writes at the new end.httprequests can setcontent-encodingwhen the body isbytesyou encoded yourself, such as a Web Push message encrypted forContent-Encoding: aes128gcm. The header goes out once, as written, with the body unchanged. See Sending a body you encoded yourself.--mem-statsreports shared values.shared=is their bytes, counted once, withshared-graphs=,shared-holds=andshared-fallbacks=beside it.freezes-moved=andfreezes-copied=count how everyfreezewent, so you can check that afreezeyou expect to cost nothing didn't copy.- The optimising JIT now compiles a loop over a constant array of
numbers kept in a partition's
state, or over a shared frozen array, as it does a loop over an array the partition built itself. A loop that reads an array by index or withfor … instays compiled whether a call brings it a shared array or an ordinary one. - A method call on a
constrecord, such asC.label_at(i), or on a shared frozen record, stays in compiled code, and so does a function that takes such a record as a typed parameter. durablenow saves an enum variant that carries a value, payload included, by name. Reordering the enum is safe, and a variant renamed or removed since the save is refused by name.- A partition's handler, an
http.serverequest handler included, can run the commands you declare inscua.toml's[exec]table or an--allow-fileexeclist, as the main script can.
#Upgrading
- Install 0.43.1, which followed on the same day with one fix. A
function that picks its body with
comptime ifand returns from every branch is accepted, with noreturn Ok(nil)at the end. Since 0.32.0 such a function was refused for not givingOkorErrorat its end, or warned about a forgottenreturnwhen it used?. - A local with the same name as an import now means the local, from
its line to the end of its block, for method calls and calls like
query.f(x)as well as field reads. Before 0.43.0,query.push(1)on a local array calledquerycalled the module. Aletthat hides an import now gets a warning where it is declared:`query` hides the imported module `query` until the end of its block; rename the local to reach the module there. It never stops a program, not even under--deny-warnings. See A local with a module's name. - A
durablesave that holds an enum variant with a payload is written in durable format 3, whichdurable.current_format()now returns. Every other save is still format 2, byte for byte, so older releases keep reading those. - An actor or session holding a file, connection, process or stream handle it has already closed can now be saved, and the handle comes back closed. Releases before 0.43.0 refuse to load such a save. An open handle still refuses, naming its kind.
#What's next
SCUA is in private evaluation with a small group of testers, and what they hit steers the work. The next step on the roadmap is the public package registry: a static index served from a CDN, with a signed transparency log from the first public publish. For the agent runtime, snapshot, fork and replay of agent sessions are designed and queued.
The changelog lists everything else in 0.43.0 and 0.43.1.