Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Runs that survive a kill

You start a long agent run. A few steps in, the process dies: a deploy restarts it, the machine reboots, the container runs out of memory. Without checkpoints you have two bad options. You can start the run over and pay for every finished step again. Or you can write your own bookkeeping of what already happened, which is harder than it sounds once a step can die halfway through.

Troupekit's answer is the checkpoint. A graph run saves its state after every step. Point the checkpoints at a SQLite file, and a new process can pick the run up where the old one stopped.

This lesson does it for real: one process dies inside a step, and a second process finishes the run. It needs no API key, so you can run it as often as you like.

The pipeline

Three steps, each a #[tool] function. The first stands in for slow, paid work:

#![allow(unused)]
fn main() {
/// Collects notes on the topic. Stands in for a slow, paid step.
#[tool]
fn gather(input: String) -> String {
    log("gather");
    format!("three notes on {input}")
}
}

log appends the step's name to a file, so at the end we can count how often each step ran across both processes.

The second step is where we pull the plug:

#![allow(unused)]
fn main() {
/// Condenses the notes. In the crash process it saves the run id and then
/// kills its own process in the middle of the step.
#[tool]
fn condense(notes: String, ctx: ToolContext) -> String {
    log("condense");
    if std::env::var(MODE).as_deref() == Ok("crash") {
        let run_id = ctx.run_id.expect("graph steps carry their run id");
        std::fs::write(dir().join("run-id"), run_id.to_string()).expect("write run-id");
        std::process::abort();
    }
    format!("the gist of {notes}")
}
}

A tool can take one ToolContext argument, and troupekit fills it in. ctx.run_id names the run this step belongs to. We write it to a file, because the next process needs it to find the run, and then std::process::abort() ends the process on the spot. No destructor runs, no cleanup, nothing flushed: as close to a crash as a program can do to itself.

The graph puts the three steps in a line, with checkpoints in SQLite:

#![allow(unused)]
fn main() {
async fn pipeline(db: &Path) -> Result<BuiltGraph, KitError> {
    Graph::new("research")
        .step("notes", gather)
        .step("gist", condense)
        .step("report", publish)
        .checkpoints(Storage::sqlite(db))
        .build()
        .await
}
}

The node ids are notes, gist and report, and the arguments follow them: condense reads notes, publish reads gist. That is the wiring from the Graphs lesson. One detail: a #[tool] function becomes a type with the function's name, so an argument cannot share a name with a tool function. That is why the ids differ from the function names here.

Storage::sqlite(db) is the line that makes the run durable. With the default, Storage::memory(), the checkpoints die with the process.

Two processes

The program starts itself twice. The first child runs the pipeline and dies in condense. The second child resumes:

#![allow(unused)]
fn main() {
Ok("resume") => {
    let id = std::env::var(RUN)?;
    let run_id: RunId = serde_json::from_value(serde_json::Value::String(id))?;
    let output = pipeline(&dir().join("runs.db"))
        .await?
        .resume(run_id)
        .await?;
    println!("resumed: {}", output.as_str().unwrap_or_default());
    Ok(())
}
}

It builds the same graph on the same file and calls resume(run_id). The run continues from its latest checkpoint. Resuming needs the graph that started the run: a graph with different steps is refused, because its checkpoints would mean something else.

Try it

cargo run -p troupekit --example course_resume

You should see the first process end uncleanly, the id of the run it left halfway, the resumed report, and then the counts:

  • gather ran once. Its checkpoint was saved before the crash, so the second process did not run it again.
  • condense ran twice. It died halfway the first time, and a step that never finished has no checkpoint, so it runs again.
  • publish ran once, in the second process.

That second point is the one to remember. Resume replays the step that was in flight. For a step with side effects, such as sending an email or charging a card, that replay matters. ToolContext also carries an idempotency_key, which is the same for a replayed call and new for every other call, so your tool can tell a replay from a new request and skip the side effect.

Agents resume too

Everything here works for a single agent as well. Give it .checkpoints(Storage::sqlite(path)), start the run with start(input), which saves the first checkpoint and returns the run id before any model call, and keep that id. Then call resume(run_id) to run the agent, and call BuiltAgent::resume(run_id) again after a restart to finish it. For workflows on a job queue, with a worker killed by a real SIGKILL, see Kill and resume a workflow.

Next: Budgets across runs.