SCUA

How-to

Hibernate a session

A long-lived session — an agent conversation, a player, a workflow — spends almost all of its life waiting for the next message. Keeping a warm process (or container) alive for every idle session costs tens to hundreds of megabytes each, around the clock. SCUA's alternative: freeze the session to a blob, drop it from memory entirely, and rehydrate it when something happens. While it waits, a session costs a few hundred kilobytes of object storage and zero compute — and when it wakes, it resumes exactly where it left off.

This works because a partition already is one relocatable blob (that's Persist and migrate); hibernation is that machinery pointed at a session lifecycle. The session script needs nothing special — it never learns it was frozen.

Everything on this page is driven from a C host through include/scua.h, and all of it runs in the worked example examples/embed_hibernate.c (zig build embed-hibernate from a source checkout). If you haven't embedded SCUA before, read Embed SCUA in a host program first.

#The session is an actor — and an actor freezes whole

A session lives naturally as an actor: a handler function plus its private state, driven one message at a time.

fn handler(state, msg)
  let n = state.count + 1
  print(`turn {n}: "{msg}"`)
  return { count = n, last = msg }    -- the returned state is what gets frozen
end

fn start()
  let a = actor(handler, { count = 0, last = "" })
  tell(a, "hello")
end

Two C calls freeze and thaw it:

  • scua_persist_actor(p, id, &blob, &len) serializes one actor — its state, its mailbox bookkeeping, and (see below) even a call it was parked on — into a self-contained blob. It's a snapshot, not a teardown: the live actor keeps running if you want it to.
  • scua_load_actor(p, blob, len, &id) loads that blob into a partition with the same script loaded, and writes the actor's new id to id.

An actor's id is a scua_actor_id: its slot, the slot's generation and the runtime's epoch. Get one from scua_load_actor or scua_actor_list, keep it for as long as that runtime lives, and never store it with the blob. A slot is reused once its actor is dropped, so an id kept past the drop names nothing (a tell to it is not delivered; it counts as a dead letter, below), and an id from another runtime, or from before a hot reload, is refused with SCUA_ERR_RANGE rather than reaching whichever actor has that slot now.

The blob carries data, never code. On rehydration you load the same script first (scua_load_script), then the actor blob. Capability grants and the I/O platform are host-side state and don't persist either — re-grant and re-install them as part of rehydration. If your script declares record types, the blob is stamped with their schema fingerprint and a mismatched program refuses the load (-SCUA_ERR_FORMAT) instead of misreading frozen state.

An open handle blocks a freeze; a closed one doesn't. If the session can still reach an open file, network connection, process or HTTP stream, scua_persist_actor returns SCUA_ERR_HOST_RESOURCE and writes nothing, because no open OS resource survives a reload. scua_blocking_resource(p) names the handle, for example an open file (fs.close it first). Close it before the turn ends. A handle the session has already closed can stay in its state: it's saved as a closed handle and comes back closed. After the thaw it still prints as <file>, and using it fails the way it did before the freeze (Error({ kind = "closed", message = "this file is closed" }) for a file), even after the thawed session opens new files.

#Idle hibernation: freeze between turns

The everyday case. After the actor has handled its mail (a turn boundary), freeze it, write the blob to your store, and free the whole partition:

/* ...the session handled its message (scua_pcall / scua_io_poll ran to quiescence)... */
uint8_t *blob; size_t len;
scua_actor_id session;
scua_actor_list(p, &session, 1);           /* the session's one actor */
scua_persist_actor(p, session, &blob, &len);
store_put(session_id, blob, len);          /* S3, a KV store, a file — your call */
scua_blob_free(blob, len);
scua_partition_free(p);                    /* the session is now 0 bytes resident */

Hours later, a message arrives for that session:

scua_partition *p = scua_partition_new();
scua_load_script(p, SESSION_SCRIPT, strlen(SESSION_SCRIPT), 0, 0, err, sizeof err);
scua_actor_id id;
scua_load_actor(p, blob, len, &id);        /* state, count, history — all back */
scua_actor_tell_text(p, id, "are you still you?");   /* queue the message (runs nothing yet) */
scua_io_poll(p, err, sizeof err);                    /* run the turn */
/* ...freeze again, drop again... */

The handler sees state.count == 1 and answers turn 2. It cannot tell that a freeze, a file, and a fresh partition happened in between — that's the entire property.

Mid-call hibernation: don't wait resident, wake with the answer

The sharper case: the handler asks a slow question — model inference, a long job — through a parked capability call (the embedder async platform):

fn handler(state, question)
  match model.ask(question)          -- parks; the host performs the real call
    Ok(answer)  -> use(answer)
    Error(e)    -> reconcile(e)      -- e.kind == "interrupted": see the snapshot-survival page
  end
end

model here is the host's own module. Register ask with scua_register_module, and inside the native call scua_return_pending(ctx, "model", "ask", idempotent, safe_echo): when it returns 1 the turn has parked exactly as http.get parks under the platform, with the same submit callback, the same token completes, and the same wake calls below; when it returns 0 parking isn't available (no platform, or not a handler turn), so take a blocking path instead. Built-in capability calls (http.get, fs.read, …) park the same way with no extra work. And one more thing to re-establish on rehydration, alongside grants and the platform: re-register your modules — natives are process state and never ride the blob; one you don't re-register resolves nil and fails cleanly if called.

If the answer takes 30 seconds, holding a resident partition for 30 seconds of waiting defeats the point. Instead: freeze the actor mid-park (scua_persist_actor works exactly the same while a call is parked — the park travels in the blob), drop everything, and when your answer arrives, rehydrate and deliver it into the parked call:

/* the answer you kicked off out-of-band has landed; you own it */
scua_actor_id id;
scua_load_actor(p, blob, len, &id);              /* same script + grants + platform first */

scua_actor_id park;
scua_io_parks(p, &park, 1);                       /* the reloaded, waiting call — exactly 1 here */
scua_io_park_read(p, park, mod, sizeof mod, op, sizeof op, echo, sizeof echo);  /* optional: "model ask" */

scua_io_wake_http(p, park, 200, answer, strlen(answer));  /* hand it the result you hold */
scua_io_poll(p, err, sizeof err);                 /* the handler resumes in Ok(answer) */

The handler wakes up inside its Ok(answer) arm as if the call had taken five milliseconds, when in fact it hibernated through the wait — possibly on a different machine.

The one rule: wake before you poll. A reloaded parked call is governed by the reload rule: the first drain — any scua_io_poll, or a scua_pcall that runs turns — settles it as Error({ kind = "interrupted" }), permanently, and a later wake is a silent no-op (your script then pays for the operation twice via its reconcile arm). scua_load_actor and scua_actor_tell_text don't drain, so the safe rehydration order is always: load → wake → poll. All the scua_io_wake_* result shapes mirror scua_io_complete_* (_http, _text, _bytes, _nil, _error), and a duplicate wake after settlement is a defined no-op — retrying hosts are safe.

Only wake with a result you own. Waking is you asserting "this operation completed, and this is its outcome". That's true when your process armed the call, or when you read the outcome from a durable job store you share with whoever did. If you can't establish that — a different host picked up the blob, the job's fate is unknown — don't fabricate an Ok. Just poll: the handler gets Error({ kind = "interrupted" }) and its reconcile arm asks the durable side what really happened, which is the always-safe default. (A held failure is still a result — deliver it with scua_io_wake_error rather than leaving the script to guess.)

#One copy at a time, and who holds it

A session has one identity, and only one copy of it runs in a process at a time. Loading a blob whose actor is already running is refused: scua_load_actor returns -SCUA_ERR_ALREADY_LIVE (and actors.revive returns Error({ kind = "already_live" })). Send the next message to the running copy instead. A script that really wants a second, separate actor from one blob asks for it with actors.revive(blob, { fork = true }), and the fork gets an identity of its own. Forking is a grant of its own, off by default: the host gives it with scua_grant_fork(p, 1) (the CLI's --allow-fork), and without it the fork returns Error({ kind = "not_granted" }).

Within one process the runtime also refuses a blob that is older than one it has already revived or dropped for that session (-SCUA_ERR_STALE_GENERATION, or kind = "stale_generation"), so an old copy cannot quietly come back after a newer one ran.

Messages sent to a hibernated session are not lost silently either. A tell to a session that is not running is a dead letter: it is counted, and a line naming the sender and the session is written to the log. If you want to keep that mail and deliver it after the revive, install a hook with scua_set_dead_letter_hook: it is called with the session's identity, the sender, and the message as JSON text. (A tell through a scua_actor_id whose actor has gone reaches the hook too; its identity is reported as 0 once the runtime has reused or released the slot, so key your kept mail by your own session id, not by that number.) scua_get_actor_stats returns the counts, with the revives refused by reason.

#Taking over a session from another process

Across processes, the runtime cannot tell an old holder of a session from a new one: two processes that revive the same blob would count the same generations. So the number that decides comes from your store. The protocol has three steps:

  1. Claim. Before reviving, read the blob and the generation stored beside it (G), and claim the session with a compare-and-set on that row: set its generation to a new number g only if it still holds G. Pick g with room above anything the old holder can still write: the next multiple of 2³² above G is a good choice. If the compare-and-set fails, someone else claimed it first: don't revive.
  2. Revive with the claim. scua_load_actor_fenced(p, blob, len, g, &id), or actors.revive(blob, { generation = g }) in a script. g must be above the blob's generation. The revived session's next snapshots are generations g + 1, g + 2 and so on. Nothing runs until your next scua_io_poll, so read scua_last_load_report first and check that its identity_lo, identity_hi and generation are the session and the claim you expect.
  3. Fenced writes. Every time you store a blob, compare-and-set again: write it only if its generation is above the one the row holds.

After a crash, the new holder simply claims and revives. If the old holder is still alive (cut off from the network, say), it keeps writing generations below the claim, and step 3 refuses every one of them, so the two can never overwrite each other's state, whichever is still serving. Saying no to a lower generation is not enough on its own: without the claim, both holders write the same numbers and both keep serving.

scua_load_report r = { .struct_size = sizeof r, .version = 2 };
scua_actor_id id;
if (scua_load_actor_fenced(p, blob, len, claimed, &id) == SCUA_OK &&
    scua_last_load_report(p, &r) == SCUA_OK && r.generation == claimed)
    serve(p, id);

#Editing your code while sessions are frozen

A frozen session holds references to your functions, so the obvious worry is what happens when you deploy. Editing a named function's body binds saved sessions to the new code, and reordering functions changes nothing. That's the point of hibernation, and it's what makes a bugfix deploy safe with sessions on disk.

A frozen session holds its own data and the functions it stored, and nothing else of your program: a revive reads your current functions, constants and modules by name, as a new session would. So:

  • A function you add is there in a revived session, and a function you remove or rename refuses the load only if the session holds it (stored it in its state, or was paused inside it).
  • A changed constant reaches revived sessions, including a table the session stored from it (state items = ITEMS): it follows the constant's name and keys to the new value. A list element follows only if it has an id field, so give list elements an id. If the constant is gone, the session keeps its stored copy as its own data, and the load report counts it (constants_kept). See what a revived partition sees.
  • Adding an enum or flags declaration refuses the load, even one the session doesn't use.

Where a save genuinely can't be honoured, the load refuses and names the function rather than reporting the file as corrupt:

`restock` is not in this program — it was renamed or removed since the save was written

One asymmetry is worth knowing. Editing a named function's body is fine. Editing an anonymous one — let f = fn(x) ... end — invalidates saved references to it:

fn restock(shop)  -- edit this body freely; saved sessions rebind to it
  ...
end

let pick = fn(item) return item.qty end   -- editing THIS body invalidates saves that hold it

An anonymous function has no name to be recognised by; it's identified by its position among its siblings. So a save can't prove which of two lambdas it meant, and guessing is how you end up running the wrong one. If a function is stored in session state and you expect to edit it, give it a name.

Records are checked by name. A saved session or actor records each record type it holds by the module that declares it and its name, and the load finds each one in the new program the same way, so reordering declarations or adding unrelated records changes nothing. A record type the save holds can gain a field with a constant default or an optional one (coupon: string?): the load fills it in every saved copy. One that lost a field, retyped one, gained one with no default, or was renamed or moved to another module, refuses the load, naming it and showing the saved and current field lists:

record `Cart` changed its fields since this save: field `total` was removed, and its saved values would be lost. Saved {items:{Item};total:int;}, now {items:{Item};}

Finally, a session that was paused inside a function you then edited has that paused turn dropped — the session itself lives, and the load tells you how many turns it dropped. A paused turn can't resume under a changed body, because it would continue from a position in code that no longer exists. If your data can't tolerate a dropped turn (a half-applied transfer, say, rather than a wave timer), ask for the load to be refused instead.

What a load did, in numbers. After scua_load_actor, or scua_load_script over a partition from scua_load, scua_last_load_report fills a scua_load_report: functions matched exactly, rebound onto edited code (and across how many distinct functions), paused turns dropped, record types rebound by name (a record that gained fields among them), and new state fields filled in; and the revived session's identity and generation. The same line goes to your log sinks at info. Log it per load and aggregate it per deploy: a count that is not zero where you expected zero is the first thing to look at when behaviour changes after a release.

scua_load_report r = { .struct_size = sizeof r, .version = 2 };
if (scua_last_load_report(p, &r) == SCUA_OK)
    log_info("load: %u rebound, %u turns dropped, %u record types", r.functions_rebound,
             r.turns_discarded, r.types_rebound);

To see what a blob holds before you deploy anything, run scua blob-info on it (see the CLI reference).

#Signing saves with your deployment's keys

A blob carries everything about its session, including what the session is allowed to do. When saves pass through storage or a network you don't fully control, sign them, so a revive refuses any blob that changed after your runtime wrote it. Give the runtime your keys — 32 random bytes each — before the script loads; one of them signs, and every one verifies, so you can rotate keys without stranding saves:

scua_blob_key keys[2] = {
    { .key = { /* current: 32 bytes from your secret store */ }, .flags = SCUA_BLOB_KEY_SIGN },
    { .key = { /* previous: still verifies the saves it signed */ } },
};
scua_set_blob_keys(p, keys, 2, 0);

A revive of a blob that does not verify returns -SCUA_ERR_INTEGRITY (a script's actors.revive gets kind = "integrity"), and so does one saved without a key: pass SCUA_BLOB_ACCEPT_UNKEYED as the flags while a deployment moves over. scua_actor_stats.loads_by_key counts revives by the id of the key that signed each blob; when the old key's count stops growing, remove it. The keys stay in the host's memory, where no script can read them. From the command line, the same is --blob-keys=FILE, and scua blob-info --keys FILE checks a save, or a directory of them, against your keys.

A whole-partition save (scua_persist) is signed the same way, with the same keys. Load a signed one with scua_load_keyed, which checks it by the same rules and gives the loaded partition those keys, so its next save is signed too:

int status;
scua_partition *q = scua_load_keyed(data, len, keys, 2, 0, &status);
if (!q && status == SCUA_ERR_INTEGRITY) { /* changed in storage, or signed with a key you retired */ }

scua_load has no keys to check a signed save with, so it refuses one (it returns NULL). An unsigned save loads with either.

An unsigned blob has a checksum instead, which catches damage (a torn write, a truncated copy) but not a deliberate change.

#Secrets come back wiped

A session that holds a secret, such as a key it unwrapped to read the user's data, freezes like any other: a secret never stops a snapshot. The blob doesn't keep the secret's bytes, though. Each secret is written as an empty marker (the blob shows only its length, rounded up to 8 bytes), and after the revive it is wiped: using it faults, and a call that returns a Result gives Error({ kind = "wiped" }). A secret that was already released comes back released. This is the same within one process and after a restart, and a host's redacted save treats a secret the same way. The load report line says how many came back wiped, and a script's actors.stats().secrets_wiped counts them.

So the session reads the secret again when it wakes. Keep what is safe to save in its state, the key in wrapped form, and have one resident partition that never hibernates hold the key that unwraps it:

import actors
import crypto
import secrets

-- Stays resident. Holds the master key and unwraps a session's data key when asked.
partition Keyholder(master)
  state master = master

  ask Unwrap(wrapped)
    return crypto.aes_key_unwrap(master, wrapped)
  end
end

-- Whether `s` is a secret this partition can still use.
fn usable(s)
  return s != nil and (pcall(fn() return len(s) end) matches Ok)
end

-- Hibernates when idle. `wrapped` is safe in a snapshot; `key` comes back wiped.
partition Session(keyholder, wrapped)
  state keyholder = keyholder
  state wrapped = wrapped
  state key = nil

  ask Seal(text)
    if not usable(key) then
      let k = ask keyholder.Unwrap(wrapped) timeout 1s
      key = k?
      print("session: unwrapped the data key")
    end
    return crypto.aes_gcm_encrypt(key, crypto.random_bytes(12)?, text)
  end
end

let master = crypto.random_bytes(32, { as_secret = true })?
let data_key = crypto.random_bytes(32, { as_secret = true })?
let wrapped = crypto.aes_key_wrap(master, data_key)?
data_key.release()

let session = Session(Keyholder(master), wrapped)
let sealed = ask session.Seal("first") timeout 1s
print(sealed matches Ok)

let blob = actors.snapshot(session, { drop = true })?
let back = actors.revive(blob)?
let resealed = ask back.Seal("second") timeout 1s
print(resealed matches Ok)
print(actors.stats().secrets_wiped)
$ scua rewake.scua
session: unwrapped the data key
true
session: unwrapped the data key
true
1

The session unwraps the key once when it starts and once after the revive. An idle session forgets its unlocked key, as a password manager does after a timeout, and the cost of waking is one ask and one unwrap. A C host that hibernates sessions follows the same pattern: the session script reads its secrets again, and the host has nothing to restore. secrets_wiped in scua_load_report (version 4) says how many a load brought back wiped.

#What it costs — honestly

Measured on the real C-ABI path (zig build bench-hibernate, Apple-silicon dev machine, local-file store; your store's PUT latency will dominate for big sessions):

history (records) blob at rest freeze (copy+serialize) rehydrate (load actor)
16 ~7 KB ~0.005 ms ~0.05 ms
4,096 ~1 MB ~0.4 ms ~0.4 ms
32,768 ~8 MB ~3.3 ms ~2.7 ms

Three things to know before you build on it:

  • Freezing costs O(accumulated state), not O(the last turn). Every freeze copies the session's whole live set (the running session itself is left as it is). A long conversation pays more per message to freeze — budget for it, or freeze on idle rather than after every turn.
  • The store round-trip is the real suspend cost. Compaction is sub-millisecond to a few milliseconds; a network PUT of a multi-megabyte blob is not. Count both.
  • Resume also recompiles the script (code never rides the blob). It's fast (~0.2 ms above), and a host that rehydrates many sessions of the same script amortizes it naturally.

Against the alternative — tens to hundreds of MB of warm process per idle session — the blob-at-rest column is the whole argument.

#See also

  • Write handlers that survive snapshots — the reload rule and the reconcile-on-resume habit; mid-call hibernation is that page's happy path, and its interrupted arm is your safety net whenever a wake isn't possible.
  • Persist and migrate — the persistence model this rides on (one relocatable blob, no custom serialization).
  • Embed SCUA in a host program — the C-ABI basics, grants, and the async I/O platform used here.
  • examples/embed_hibernate.c — both flows above, runnable end to end (zig build embed-hibernate).