Skip to Content
Motoko

The host contract

interface StorageScope { kind: string; name: string }                       // one agent instance
interface Lease {
  readonly signal: AbortSignal;                    // aborts if the lease is lost
  release(wake?: Wake): Promise<void>;             // `wake`: what the instance left (pi-durable's harness.wake())
}
interface AgentStore {                             // what a database supplies per instance
  lease(scope: StorageScope): Promise<Lease>;      // rejects with LeaseHeldError while another writer holds it
  storage(scope: StorageScope, lease: Lease): Promise<Storage>;  // pi-durable Storage, opened under that lease
  unfinished?(): AsyncIterable<StorageScope>;      // optional: scopes that may have work, for runtime.recover()
  erase?(scope, lease, conversations): Promise<void>;  // optional: erase deleted sessions, storage closed
}
interface AgentHost extends AgentStore {           // what the runtime takes: a store plus wake-ups
  readonly wake: HostWake;
}
type HostWake =
  | { kind: "process" }                                                    // pi-durable's own timers
  | { kind: "alarm"; arm(scope: StorageScope, wake: Wake): Promise<void> }; // evictable host; pi-durable's Wake
assertScope(scope): void    // the one definition of a valid scope, for every host and storage
scopeKey(scope): string     // a stable string for maps and lease tables
inProcessLeases(): (scope) => Promise<Lease>  // a lease table of its own, held in this process's memory

processHost(store: ProcessStore): AgentHost    // a long-lived process's host, wake: { kind: "process" }
processLeases: (scope) => Promise<Lease>       // the default, shared by every processHost of the process
type ProcessStore<L extends Lease = Lease> = {  // an AgentStore, or a storage alone
  lease: (scope: StorageScope) => Promise<L>;   // optional when L is Lease, default: processLeases
  storage: (scope: StorageScope, lease: L) => Promise<Storage>;
  unfinished?: () => AsyncIterable<StorageScope>;
  erase?: (scope: StorageScope, lease: L, conversations) => Promise<void>;
}

assertScope accepts a scope whose kind and name are strings of 1 to 1024 characters (Unicode code points), well-formed Unicode (isWellFormed(): no lone surrogates), with no NUL character, and throws a TypeError naming the part that is not. The runtime checks every instance it makes; a host or storage that keys anything by scope calls it too.

A database supplies the store: its lease and its storage, always as one pair, because a storage may fence its commits with the lease its own lease() made. The environment adds the wake-ups that make the store a host, such as processHost(store) in a long-lived process. The store's methods may take a narrower lease than Lease, since the runtime hands storage and erase the lease that the same store's lease() returned.

processHost(store) is the host of a Node, Bun or Deno server or an Electron backend: pi-durable's own timers wake sleeping work. Its store is sqliteStore of @chia1104/motoko-node, one of a database package such as @chia1104/motoko-store-postgres, or the app's own. The store's storage and erase get only the lease that its own lease returns. A store with no lease gets processLeases, so its storage must take any lease, as sqliteStorage({ directory }) does. A storage that fences its commits with its own lease, such as Postgres's, does not, so processHost({ storage: store.storage }) of a Postgres store does not type-check.

pi-durable keeps durability in the storage, so this is all a host supplies. Opening an instance takes the lease, opens the storage, opens one Harness, attaches to the sessions that have unfinished work and calls harness.resume(). A lost lease closes the instance at once. With an alarm host the runtime passes pi-durable's onWake to arm. From before every call that can start work (submit, approve, abort, resume, delete) until the call is done, it arms only { active: true }, whatever other calls and runs report meanwhile, since pi-durable reports a call's work only after the commit that starts it. Once no such call is under way it arms harness.wake() (pi-durable reports only changes, and a call that started nothing changes nothing). The host calls instance.resume() when its alarm fires. @chia1104/motoko-cloudflare is such a host: a Durable Object's.

Two capabilities are optional. unfinished() lists the scopes whose storage may hold work that needs a process: a task that can run or was running, or a sleep. It must never list fewer than those; it may list more, at the cost of opening them. A host learns what an instance left from release(wake), which the runtime calls with harness.wake() as it closes the instance, and a scope whose lease was never released (its process crashed) counts too. erase(scope, lease, conversations) erases deleted sessions: each conversation with its entries, tasks, submissions and documents, and the conversations its tasks made. The runtime calls it with the lease held and the storage closed; the host skips a conversation that still has unfinished work or that another conversation forks from, and the runtime asks again at the instance's next close.

inProcessLeases() admits one writer per scope among the hosts given the same function, and sees no other process. processLeases is one, made once for the process: the lease of every processHost whose store brings none.

Checking a host

@chia1104/motoko-core/testing holds the contract as a suite every host runs against itself. It takes the host's own test runner, as pi-durable's registerStorageConformance does, so the core depends on no test framework:

import { registerHostConformance } from "@chia1104/motoko-core/testing";
import { describe, expect, it } from "vitest";

registerHostConformance({ describe, expect, it }, "my host", async (use) => {
  const host = myHost(); // fresh resources for each case, cleaned up after it
  await use(host);
});

Each case runs on scopes of its own, so one host may serve every case. The suite checks that a held scope refuses a second lease() with LeaseHeldError and that release() frees it; that a second release() after another holder took the scope frees nothing; that scopes differing only in where a / falls hold separate leases and storages; that an invalid scope is rejected with a TypeError; that storage(scope, lease) opens a pi-durable Storage that commits and reads back, while the lease's signal stays unaborted; and that release(wake) frees the scope. For a host that has them, it checks that unfinished() lists a scope released with work that can run or with a sleep, and that erase() removes a session the runtime deleted and keeps the others. What one host adds (expiry, other processes, fencing) stays in its own tests.

A host that serves one scope alone, as a Durable Object's serves the object's own, runs registerSingleScopeHostConformance instead. Its provider makes a fresh host for each case and names the scope it serves, use(host, scope); the cases run on that scope, and in place of keeping two scopes apart the host must refuse every other scope with a TypeError.

Shared-database stores

@chia1104/motoko-core/store is what every store that keeps many scopes in one database has in common, whatever its SQL dialect: a row lease per scope with a fencing token and an expiry by the database clock, renewed for all of a store's leases in one statement per interval; and a commit that reads the check state once, runs pi-durable's batch checks in memory, and writes the accepted batches' net effect once, atomically, only if a guard holds (the lease token current and unexpired, next_seq unchanged). createSharedStore(dialect, options) makes the store from a StoreDialect, the statements of the store and its lease, and a dialect's storage commits with commitBatches through a CommitPort: read the check state, write a plan if the guard holds and say why it refused, read a copy's source. A plan claims only the IDs no stored record claims yet, so a commit that only rewrites a task claims nothing. A StorageShell is the rest of a dialect's storage that is not SQL: it admits calls until close() and drains them, mints IDs in memory, runs the commit, retries a read after a transient connection failure, and keeps the content findDocument read for the document() call that follows (DocumentRows, materializeDocument). The dialect owns its storage's reads, its schema and its migrations. @chia1104/motoko-store-postgres and @chia1104/motoko-store-mysql are such stores.

registerStoreConformance(runner, name, provider) of @chia1104/motoko-core/store/testing is the suite such a store runs against itself, on the runner shape of registerHostConformance. The provider hands each case a target: the store, and what only the dialect can do to its database (expire a lease now, delete a scope's row behind its holders, cut a connection, run something between a commit's read and its write, count a scope's rows). It checks that a writer that lost its lease writes nothing, that a lease expires and is taken over, that a release records the wake unfinished() lists, that scopes in one database are apart, the rules of erase() and deleteScope(), and that two storages under one lease cannot both commit. A target without otherProcess (a database of one connection) passes the case that needs another process without running it.