Workflows
Write checkpointed tool-call graphs with typed Rust steps, bounded batches, branches and joins; configure and run a complete local workflow.
A workflow belongs to a service. Its builders prepare typed tool calls; the host runs them and saves checkpoints between calls.
Use a workflow-capable public crab CLI/runtime and a matching berm-lang revision. Check crab workflow --help; to call an existing deployment, see Running workflows.
A complete workflow
This service normalizes up to three names and saves the batch when it is nonempty. Its saved names belong to the deployment and are shared by callers.
Start with the Cargo setup in A complete service. Replace src/lib.rs with:
#![cfg_attr(target_arch = "wasm32", no_std)]
extern crate alloc;
use alloc::{string::String, vec::Vec};
use berm_lang::{Branch, Result, Schema, tool, workflow};
#[derive(Schema)]
pub struct Input {
pub names: Vec<String>,
}
#[derive(Schema)]
struct Ready {}
#[derive(Schema)]
struct Empty {}
#[derive(Schema, Branch)]
enum Route {
Ready(Ready),
Empty(Empty),
}
#[derive(Schema)]
pub struct Report {
pub names: Vec<String>,
pub saved: bool,
}
/// Trim a name and convert it to lowercase.
#[tool(query)]
pub fn normalize(name: String) -> Result<String> {
Ok(name.trim().to_lowercase())
}
const NAMES: &str = "names";
/// Replace the deployment's saved names with this batch.
#[tool]
pub fn save(names: Vec<String>) -> Result<usize> {
berm_lang::set_json(NAMES, &names)?;
Ok(names.len())
}
struct NameBatch;
#[workflow]
impl NameBatch {
#[step(each, max = 3)]
fn normalized(input: &Input) -> Vec<NormalizeCall> {
input
.names
.iter()
.map(|name| NormalizeCall { name: name.clone() })
.collect()
}
#[branch]
fn route(normalized: &[String]) -> Route {
if normalized.is_empty() {
Route::Empty(Empty {})
} else {
Route::Ready(Ready {})
}
}
#[step]
fn saved(route: &Ready, normalized: &[String]) -> SaveCall {
let _ = route;
SaveCall {
names: normalized.to_vec(),
}
}
#[output]
fn report(normalized: &[String], saved: Option<&usize>) -> Report {
Report {
names: normalized.to_vec(),
saved: saved.is_some(),
}
}
}Replace crab.toml with:
[database]
size = "1MiB"
[tools.normalize]
budget = { cpu = 100000, read = 1, written = 1, memory = 32 }
[tools.save]
budget = { cpu = 100000, read = 1, written = 1000, memory = 32 }
[workflows.name_batch]
access = "public"
max_cost = 100000
checkpoint_bytes = 1048576
retain = "7d"
budget = { cpu = 100000, read = 0, written = 0, memory = 32 }NameBatch becomes the workflow name name_batch. Its application tools are internal because their tables omit access; the workflow entry is public.
Build and deploy to the local host, replacing name-flow with your service's crate name:
crab build
crab dev -d
crab --context default deploy
crab --context default workflow inspect name-flow.name_batch
crab --context default workflow run name-flow.name_batch '{"names":[" Alice ","BOB"]}' --dry-run
crab --context default workflow run name-flow.name_batch '{"names":[" Alice ","BOB"]}' --yes
crab --context default workflow status name-flow.name_batch RUN_IDUse the run ID returned by run. The completed result is {"names":["alice","bob"],"saved":true}; an empty input list skips saving and returns {"names":[],"saved":false}.
The Page Watch example applies the same structure to bounded HTTP reads, comparison and saving changed snapshots. It links the existing public Markdown library and needs no provider account.
Steps and dependencies
Parameter names select producers: input is the workflow input, and every other name is an earlier method. Parameters borrow results with &T, batches with &[T], or potentially skipped results with Option<&T> / Option<&[T]>.
NormalizeCall and SaveCall come from the tools' #[tool] macros. Their fields are the tool arguments; consumers receive the tool's result type, such as String or usize.
| Method | Returns | Consumer receives |
|---|---|---|
#[step] |
A call descriptor | The tool's output |
#[step] |
Option<Call> |
The output, or a skipped node for None |
#[step(each, max = N)] |
Vec<Call> |
Ordered outputs borrowed as &[T] |
#[branch] |
A Schema, Branch enum |
Its selected payload or the whole enum |
#[output] |
A Schema value |
The workflow's final result |
Any method may return Result<T> around its declared result; Err fails that control invocation. There must be one input type, exactly one output, and no unused nodes, forward dependencies or cycles.
Builders, branches and output methods cannot use HTTP, storage, time, randomness or other application syscalls. Put those operations in tools, as save does above.
Items in an each step run sequentially. The prepared list is checkpointed before dispatch; exceeding max fails before the first item call. N must be between 1 and 100.
Branches and joins
A Branch case wraps exactly one distinct Schema payload type. route: &Ready makes saved eligible only when route selected Route::Ready; the Empty case skips it.
The output's saved: Option<&usize> joins both paths. It gets None when saving was skipped; pending or failed work does not become None.
#[step] can also return Option<Call> to skip a call directly. Use an optional dependency in a downstream join when that producer may be skipped.
Calling other services
Fetch the accessible target's actual IDL and declare it in the service:
crab idl web/markdownberm_lang::declare_service!(markdown);Workflow steps can then return descriptors such as markdown::ReadCall, with argument fields and output types generated from that IDL. The descriptor keeps the deployed target address; inspection resolves its current image, permissions and price.
Calling it requires an accessible deployment. Linking a service's Rust API instead runs that library in your own service, as Page Watch does.
Budgets, retention and continuation
max_cost is the owner's cumulative Cloud managed-spend cap in USD micros across all attempts. budget bounds each builder, branch and output invocation; its storage reads and writes must be zero, and tools retain their own budgets.
checkpoint_bytes reserves capacity for complete checkpoints, and retain sets their lifetime. The local runtime does not settle task fees; optional customer pricing, owner costs and external provider charges are covered in Workflow costs.
Continuation keeps the original image, input, prepared calls, branch decisions and successful checkpoints. Queries may be retried; an uncertain write requires its target's unexpired idempotency guarantee or an authoritative recorded outcome. The example's save declares no such guarantee.
Inspect status before continuing a failed or indeterminate run. Expired or deleted checkpoints cannot be continued, and cancellation cannot undo completed effects; see Continue or cancel.
Schedules and checks
An optional [workflows.name_batch.schedule] table supplies a five-field UTC cron and input; redeploy to change it. Occurrences have a 60-second delivery window; later delivery is refused with E0075 and does not run. See Schedule behavior.
Before deploying, build the image, inspect the graph and accepted terms, and dry-run representative input. Check a normal batch, an empty batch, and four names: the last must fail without dispatching a normalization call.
Native Rust calls can test builder logic; checkpointing, branch skipping and continuation need the real host. Page Watch's workflow tests arrange HTML responses, fail a later read, and verify continuation keeps earlier successful reads.
V1 has no sleeping workflows, human waits, repeat loops, webhook triggers, automatic retries or automatic crash continuation. Full field and macro rules: crab.toml, Macros.