# Workflows

Code on this page is in Rust. The same page in [Python](https://docs.laserdata.com/md/python/laser-sdk/workflow.md), [TypeScript](https://docs.laserdata.com/md/typescript/laser-sdk/workflow.md), or with every language at https://docs.laserdata.com/md/laser-sdk/workflow.md.

The complete programs on this page are plain text, one language each, at [https://docs.laserdata.com/md/python/laser-sdk/workflow.md](https://docs.laserdata.com/md/python/laser-sdk/workflow.md), [https://docs.laserdata.com/md/typescript/laser-sdk/workflow.md](https://docs.laserdata.com/md/typescript/laser-sdk/workflow.md), and [https://docs.laserdata.com/md/rust/laser-sdk/workflow.md](https://docs.laserdata.com/md/rust/laser-sdk/workflow.md).

A durable workflow is a function whose steps are recorded on the log. Python decorates functions with `@ls.step` and `@ls.workflow`, TypeScript wraps them with `step()` and `workflow()`, and Rust passes closures to `run_with`. Each step that finishes is written to the `agent.workflow_journal` topic, so a run that stops part way continues from the first step that did not finish. Workflows run on plain Apache Iggy, Laser Stack, and LaserData Cloud.

Use a workflow when a job has several dependent steps and must survive a restart, such as ingest, then analyze, then report. For a single request and reply, send the request to the agent directly.

## Quick example

This program runs a three-step durable workflow in its own process. Each step is a function, the workflow function calls them in order, and `analyze` waits one second before it returns. The program prints the run's status, the finished steps in order, and the workflow's value as JSON.

The program connects with `LASER_CONNECTION_STRING`. With that variable set, it needs no Docker and no local server. Without it, the [resolve block](#run-it-with-an-api-key) below connects with a LaserData API key.

```bash
cargo add laser-sdk
echo "${LASER_CONNECTION_STRING:+configured}"  # prints configured when the variable is set
cargo add tokio --features macros,rt-multi-thread,time
cargo add serde_json
```

The complete Rust workflow program, saved as `src/main.rs`: three steps inside `run_with` and one line that prints the outcome.

```rust
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread,time
// cargo add serde_json
// Needs only LASER_CONNECTION_STRING, which connect_env() reads. No server to start when it is set.
use laser_sdk::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_env().await?;
    let run = laser
        .workflow("pipeline")
        .run_with(async |run| {
            let frames: String = run
                .step("ingest", async || Ok("frames from sat-7".to_owned()))
                .await?;
            let analysis: String = run
                .step("analyze", async || {
                    tokio::time::sleep(Duration::from_secs(1)).await;
                    Ok(format!("analyzed {frames}"))
                })
                .await?;
            run.step("report", async || Ok(format!("report on {analysis}")))
                .await
        })
        .await?;
    let report = serde_json::json!({
        "status": run.status,
        "steps": run.completed_steps,
        "report": run.json::<String>("report")?,
    });
    println!("{report}");
    laser.close().await
}
```

Python prints this, TypeScript prints it without the spaces, and Rust orders the keys by name:

```json
{"status": "completed", "steps": ["ingest", "analyze", "report"], "report": "report on analyzed frames from sat-7"}
```

`run()` returns the outcome: `status`, `completed_steps` (TypeScript: `completedSteps`) in the order the steps finished, `value`, which is what the workflow function returned, and `run_id`. `status` is `completed` for every returned outcome, because a failed run raises the step's error instead. Calling the workflow as a function, `pipeline()`, returns the value alone. In Python an `async def` workflow is awaited, and its steps can be `async def` too. The run creates its stream and its topics on the first write, so the program needs no `bootstrap`.

## How a run is recorded

* A step takes and returns what JSON holds: an object, a list, text, a number, a boolean, or null. A step call returns the value as JSON decodes it, on a first run and on a resumed one alike, so a Python tuple comes back as a list. A value JSON cannot hold is refused with the step's name.
* A step is recorded under its name as its label. A second call of the same step in one run is recorded as `name#2`, the third as `name#3`. `completed_steps` lists these labels, and `outcome.json(label)` reads one step's value (Rust: `run.json::<T>(label)`).
* The run is recorded on the client's default stream, else on the stream `LASER_STREAM` names, else on a stream named after the workflow, `pipeline` here. The run creates the stream when it is missing.
* The stream stays after the run, so the journal is there for a resume. Delete it with `laser.stream("pipeline").delete()` when you no longer need it.
* Each run has a run ID. Resuming with it returns the recorded value of every finished step without calling the step again and runs the rest. Pass the workflow's arguments again, because the journal does not hold them.
* A resumed step call finds its record by the step's name and its arguments. A call with the same arguments returns the recorded value, and a call with other arguments runs as a new call. Rust's `run.step` takes no arguments, so its calls take the records of their label in call order.
* When the workflow function returns, no new step starts. A step still running then has 5 seconds to finish and be recorded. A step that takes longer is not recorded and runs again on a resume.

| | TypeScript | Rust | Python |
| --- | --- | --- | --- |
| Run and get the outcome | `await pipeline.run()` | `laser.workflow("pipeline").run_with(...)` | `pipeline.run()` |
| Resume a run | `await pipeline.resume(runId)` | `laser.workflow("pipeline").run_id(run_id).run_with(...)` | `pipeline.resume(run_id)` |
| Run on a client you hold | `pipeline.bind(laser).run()` | The client the workflow was made on | `pipeline.bind(laser).run()` |
| Name the stream | `workflow(name, fn, { stream })` | `laser.with_default_stream(stream)` | `@ls.workflow(stream=...)` |

A workflow function connects with `LASER_CONNECTION_STRING` and closes its connection when the run ends. A bound one uses your client and leaves it open.

## Run it with an API key

With a LaserData API key in `LD_API_KEY` instead of a connection string, add this block to the program. It turns the key into the connection string in three calls: the key's organization from `/tenants`, the deployments the key can read from `/tenants/{tenant_id}/deployments`, and the login from the deployment's `/credentials`. Set `LD_DEPLOYMENT` to the deployment's name or ID when the key sees more than one deployment. The block then exits and lists the ones it sees. The key's role needs `deployment:read` and `deployment:credentials:read` on the deployment's environment. The block keeps the connection string in memory and never prints it.

```rust
// cargo add reqwest --features json
// cargo add serde_json
// Add these two functions, then connect with Laser::connect(&connection_string().await?) in main.
use serde_json::Value;

async fn laserdata(client: &reqwest::Client, url: &str) -> Result<Value, Box<dyn std::error::Error>> {
    let key = std::env::var("LD_API_KEY")?;
    let response = client.get(url).header("ld-api-key", key).header("user-agent", "laserdata-docs-example").send().await?;
    let status = response.status();
    if !status.is_success() {
        return Err(format!("GET {url} answered {status}: {}", response.text().await?).into());
    }
    Ok(response.json().await?)
}

async fn connection_string() -> Result<String, Box<dyn std::error::Error>> {
    if let Ok(value) = std::env::var("LASER_CONNECTION_STRING") {
        return Ok(value);
    }
    let api_url = std::env::var("LD_API_URL").unwrap_or_else(|_| "https://api.laserdata.cloud".to_owned());
    let client = reqwest::Client::new();
    let tenants = laserdata(&client, &format!("{api_url}/tenants")).await?;
    let mut deployments = Vec::new();
    for page in 1_u64.. {
        let url = format!("{api_url}/tenants/{}/deployments?results=100&page={page}", tenants[0]["id"]);
        let reply = laserdata(&client, &url).await?;
        deployments.extend(reply["items"].as_array().cloned().unwrap_or_default());
        if page >= reply["total_pages"].as_u64().unwrap_or(0) {
            break;
        }
    }
    let wanted = std::env::var("LD_DEPLOYMENT").ok();
    let matches: Vec<&Value> = deployments
        .iter()
        .filter(|deployment| wanted.as_deref().is_none_or(|wanted| deployment["name"] == wanted || deployment["id"].to_string() == wanted))
        .collect();
    let [deployment] = matches.as_slice() else {
        let visible: Vec<String> = deployments.iter().map(|deployment| format!("{} ({})", deployment["name"].as_str().unwrap_or_default(), deployment["id"])).collect();
        eprintln!("Set LD_DEPLOYMENT to the name or ID of one deployment. Visible: {}", visible.join(", "));
        std::process::exit(1);
    };
    let supervisor_url = deployment["supervisor_url"].as_str().ok_or("The deployment has no supervisor_url yet")?;
    let credentials = laserdata(&client, &format!("{supervisor_url}/deployments/{}/credentials", deployment["id"])).await?;
    Ok(credentials["connection_string"].as_str().ok_or("The credentials answer has no connection_string")?.to_owned())
}
```

The block calls nothing else: it never changes access rules and never needs `info:read`. A Free deployment admits every address, so the program connects at once. A paid deployment admits only the addresses its [access rules](/networking/access-rules) allow, and a connect from any other address times out naming `the Iggy server to accept the connection`. [Agent access](/agents#the-network-path) shows how to admit an address, and [When no deployment exists](/agents#when-no-deployment-exists) shows how to create one.

## The builder: steps that agents run, verifiers, compensation, and budgets

A workflow function runs every step in your process. Use the builder when a step is a request to an agent that offers a capability, when a step needs a verifier or a compensation, or when the run needs a budget. Both forms write the same journal and resume the same way. The [workflow reference](/laser-sdk/advanced/agents#workflows) lists every builder option.

### Steps in your process

With the builder a step is declared with its label and the labels it runs after, and its body reads the earlier outputs as bytes. This program runs on a scratch stream with a unique name and deletes that stream at the end, so it leaves nothing to clean up.

The same pipeline with the builder, saved as `src/main.rs`.

```rust
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread,time
// cargo add serde --features derive
// cargo add serde_json
// cargo add async-trait
// Needs only LASER_CONNECTION_STRING, which connect_env() reads. No server to start when it is set.
use laser_sdk::prelude::*;
use serde::Serialize;
use std::time::Duration;

#[derive(Serialize)]
struct Report {
    run_id: String,
    status: SessionStatus,
    completed_steps: Vec<String>,
    report: Option<String>,
}

struct Analyze;

#[async_trait::async_trait]
impl StepFn for Analyze {
    async fn build(&self, context: &StepContext<'_>) -> Result<Vec<u8>, LaserError> {
        let ingested = context.outputs.get("ingest").cloned().unwrap_or_default();
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok([b"analyzed ".to_vec(), ingested].concat())
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let root = Laser::connect_env().await?;
    let scratch = root.scratch_stream("workflow").await?;
    let result = run_pipeline(scratch.laser()).await;
    scratch.delete().await?;
    let outcome = result?;

    let report = Report {
        run_id: outcome.run_id.to_string(),
        report: outcome.text("report"),
        status: outcome.status,
        completed_steps: outcome.completed_steps,
    };
    println!("{}", serde_json::to_string(&report)?);
    Ok(())
}

async fn run_pipeline(laser: &Laser) -> Result<WorkflowOutcome, LaserError> {
    laser
        .workflow("pipeline")
        .step_local("ingest", |_: &StepContext<'_>| {
            b"frames from sat-7".to_vec()
        })
        .step_local("analyze", Analyze)
        .after("ingest")
        .step_local("report", |context: &StepContext<'_>| {
            let analyzed = context.outputs.get("analyze").cloned().unwrap_or_default();
            [b"report on ".to_vec(), analyzed].concat()
        })
        .after("analyze")
        .run()
        .await
}
```

A closure step is synchronous and returns `Vec<u8>`, so an `async` closure does not compile. A step that awaits is a type that implements `StepFn`, passed in place of the closure, as `Analyze` is.

The output looks like this in every language, with your own run ID. Python separates the fields with a space:

```json
{"run_id":"01JD3W8Q4M6V2X9TQK7R5N1B0C","status":"completed","completed_steps":["ingest","analyze","report"],"report":"report on analyzed frames from sat-7"}
```

A step body gets `outputs`, the earlier steps' outputs by label, each as bytes (`Uint8Array` in TypeScript, `Vec<u8>` in Rust), and returns its own output as text or bytes. In Python it is a plain function or a coroutine, in TypeScript a plain or async function, and in Rust a closure or a type that implements `StepFn`. It runs inside the step deadline, 30 seconds unless you set one. `status` is `completed` for every returned outcome, because a failed, canceled, or over-budget run raises an error instead. `completed_steps` (TypeScript: `completedSteps`) lists the finished steps in the order the journal recorded them, `outputs` holds each step's output as bytes, and `text(label)` returns one as text. The run creates the journal and session topics on its first write, so the program needs no `bootstrap`. The scratch stream is deleted with the journal and every other topic when its scope ends. To keep the journal so a run can resume, use a named stream, as in [Resume a stopped run](#resume-a-stopped-run). To delete a stream yourself, call `laser.stream(name).delete()`.

### Run steps on agents

A step can also be a request to an agent that offers a capability, so the work runs in another process or on another machine. This program starts one worker agent and runs the same three-step pipeline against it on the named stream `telemetry`. To resume a run, set `RUN_ID` to the run ID it printed. Local and routed steps mix in one workflow. The program keeps the stream so a run can resume. Delete it when you are done with `laser.stream("telemetry").delete()`.

```rust
// cargo add laser-sdk
// cargo add tokio --features macros,rt-multi-thread
use laser_sdk::prelude::full::*;
use laser_sdk::wire::agent::CapabilityDescriptor;
use std::time::Duration;

struct Worker;

impl AgentHandler for Worker {
    async fn handle(&self, message: &AgentMessage, ctx: &AgentCtx<'_>) -> Result<(), LaserError> {
        let task = String::from_utf8_lossy(message.body());
        ctx.respond(format!("done: {task}")).await
    }
}

#[tokio::main]
async fn main() -> Result<(), LaserError> {
    let laser = Laser::connect_env().await?.with_default_stream("telemetry");
    laser
        .bootstrap(1, TopicRetention::expire_after(Duration::from_secs(86_400)))
        .await?;

    let mut worker = Agent::builder()
        .id("telemetry-worker".parse()?)
        .listen_on(AgentTopic::Sessions)
        .respond_on(AgentTopic::Sessions)
        .capabilities(vec![CapabilityDescriptor {
            skill_id: "telemetry-step".to_owned(),
            ..Default::default()
        }])
        .ack_on_pickup(true)
        .handler(Worker)
        .build()
        .spawn(laser.clone());
    worker.ready().await?;

    let step = || Router::to_capable("telemetry-step", RoutePolicy::Any);
    let mut workflow = laser
        .workflow("telemetry-pipeline")
        .inbox_route(InboxRoute::Fixed(AgentTopic::Sessions))
        .budget(WorkflowBudget::unlimited().invocations(6).wall_clock(Duration::from_secs(60)));
    if let Ok(run_id) = std::env::var("RUN_ID") {
        workflow = workflow.run_id(run_id.parse()?);
    }

    let outcome = workflow
        .step("ingest", step(), |_ctx: &StepContext<'_>| b"ingest frames from sat-7".to_vec())
        .step("analyze", step(), |ctx: &StepContext<'_>| {
            let ingested = ctx.outputs.get("ingest").cloned().unwrap_or_default();
            [b"analyze ".to_vec(), ingested].concat()
        })
        .after("ingest")
        .step("report", step(), |ctx: &StepContext<'_>| {
            let analyzed = ctx.outputs.get("analyze").cloned().unwrap_or_default();
            [b"report ".to_vec(), analyzed].concat()
        })
        .after("analyze")
        .run()
        .await?;

    let report = outcome.outputs.get("report").cloned().unwrap_or_default();
    println!(
        "Run {} finished: {}",
        outcome.run_id,
        String::from_utf8_lossy(&report)
    );
    worker.shutdown().await
}
```

The output looks like this, with your own run ID. Each step's reply wraps the request it got:

```text
Run 01JD3W8Q4M6V2X9TQK7R5N1B0C finished: done: report done: analyze done: ingest frames from sat-7
```

## Common mistakes

* One connection advertises one agent. A second agent spawned on the same connection fails with `PresenceConflictError` (connection already advertises agent ...). In Python, `async with laser.spawn_agent(...)` and `ready()` report it as `agent stopped before ready`, and `shutdown()` then raises the `PresenceConflictError`. Serve every step from one agent whose handler reads the request, as the example does, or open one connection per agent.
* A worker replies on the topic it responds on. Without one, the agent refuses `ack_on_pickup` with `ack_on_pickup requires respond_on`, or a step fails because the agent has no respond\_on topic configured. Set it when you build the agent: `respond_on` in Python, `respondOn` in TypeScript, `respond_on` in Rust.
* In Python, `message.body()` is a method that returns the task body. `message.payload` is the whole encoded message, so decoding it as text fails.
* A step function called outside a workflow function is refused with an error that names both ways out: call it inside a workflow function, or call its `fn` for the plain function.
* In Python, a thread does not inherit its workflow, so a step called on a new thread is refused as a call outside a workflow. Run the step with `asyncio.to_thread(step, ...)`, or hand the thread `contextvars.copy_context().run` with the step as its first argument.

## Resume a stopped run

Every run has a run ID. The run writes each finished step to `agent.workflow_journal` under that ID, so a run resumes only on a stream that outlives the process, not on a scratch stream. When the process stops between steps, start it again on the same stream with the same run ID: `pipeline.resume(run_id)` for a workflow function, `run_id` on the builder, as the agent program above does with `RUN_ID`:

* A step recorded as finished does not run again. Its stored output feeds the next step.
* A step that runs in your process and stopped before its finished record runs again, so it runs at least once.
* A step that was sent but has no recorded reply is answered by its reply when one landed. Otherwise it is sent again with the same idempotency key. A worker can drop a duplicate while its deduplication record still exists. The default in-memory deduplication window does not survive every worker restart, so the handler must tolerate redelivery.
* A step copy that a worker dropped because its deadline had passed never ran, so it does not stop the resent step from running. That holds on a worker that refills its deduplication window on restart too, unless its warm dedup policy is `all`.
* When the worker's process stopped too, the streaming server keeps that worker's partitions until it ends the stopped process's session, 36 seconds or more after the stop with default server settings. A run resumed sooner can fail with a `timed_out` step error. Resume it again with the same run ID and the step runs once.
* A run whose journal was cut by topic retention fails with a journal truncated error instead of running every step again.

The journal records what the workflow did. An agent that changes something outside the log, such as a payment or an email, still needs its own protection against doing it twice. Make the step [exclusive](/laser-sdk/advanced/agents#exclusive-steps) and use a fenced write, or key the external call with the request's idempotency key.

## When a step fails

In a workflow function, a step that raises ends the run as failed and the same error reaches the caller unchanged. The steps that finished stay recorded, so a resume runs the failed step and what follows.

A step fails when its agent does not reply before the step deadline (30 seconds unless you set one), when the reply is an error, or when a verifier rejects the output. A step in your process fails when its body runs past the deadline, and an error its body raises comes back unchanged. The run then fails with a step failed error that names the run, the step, and the reason, and for a timed-out step also the target and the deadline in milliseconds. Steps that already finished run their compensations in reverse order. Only a `timed_out` failure is worth retrying as is.

| Error | Rust | TypeScript and Python | What to do |
| --- | --- | --- | --- |
| Step failed | `LaserError::StepFailed` | `StepFailedError` | Read the reason, fix the agent or the input, resume with the same run ID |
| Budget exceeded | `LaserError::BudgetExceeded` | `BudgetExceededError` | Raise the budget, or split the run |
| Journal truncated | `LaserError::JournalTruncated` | `JournalTruncatedError` | Start a new run, and keep the journal topic longer than your longest run |
| No capable agent | `LaserError::NoCapableAgent` | `NoCapableAgentError` | Start an agent that offers the capability and wait for `ready()`, then resume with the same run ID |

When no agent offers the capability a step asks for, the run fails at once with the no capable agent error instead of waiting for the step deadline. Start the agents first and wait for `ready()`, as the example does.

## Next steps

- [Workflow reference](/laser-sdk/advanced/agents#workflows): Step options, budgets, verifiers, compensations, cancel, and exclusive steps
- [Agents](/laser-sdk/fabric): Write the agents that run the steps
- [Sessions](/laser-sdk/session): Each run is a root session, and each step is a child session

Source: https://docs.laserdata.com/laser-sdk/workflow
