Skip to content

Interrupts and human-in-the-loop

An interrupt pauses a run inside a node and hands a payload to the caller. The caller resumes the thread later with an answer. Interrupts need a checkpointer, because the paused thread is saved.

Call ctx.interrupt(payload)? in a node. Always propagate it with ?: that is how the node stops.

use std::sync::Arc;
use warpra::*;
use serde_json::{json, Value};
fn build() -> Result<Pregel, GraphError> {
let mut g = StateGraph::new().last_value("draft").last_value("approved").last_value("sent");
g.add_node("write", node_fn(|_s: Value, _c: NodeCtx| async move {
Ok::<Value, NodeError>(json!({"draft": "Dear customer, your refund is on its way."}))
}))?;
g.add_node_with(
"review",
node_fn(|s: Value, ctx: NodeCtx| async move {
// The node re-runs from the top on resume; `interrupt` returns the human's answer then.
let decision = ctx.interrupt(json!({"question": "Send this email?", "draft": s["draft"]}))?;
let approved = decision == json!("approve");
Ok::<_, NodeError>(Command::new().update(json!({"approved": approved})).goto(if approved { "send" } else { END }))
}),
NodeOpts::new().destinations(["send"]),
)?;
g.add_node("send", node_fn(|s: Value, _c: NodeCtx| async move {
println!(" -> sending: {}", s["draft"]);
Ok::<Value, NodeError>(json!({"sent": true}))
}))?;
g.add_edge(START, "write")?.add_edge("write", "review")?.add_edge("send", END)?;
g.compile(CompileOpts::new().checkpointer(Arc::new(InMemorySaver::new())))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let app = build()?;
let cfg = RunConfig::thread("approved-thread");
let out = app.invoke(json!({}), cfg.clone()).await?;
println!("paused with: {}", out.interrupts[0].value);
let state = app.get_state(&cfg, false).await?;
println!("next = {:?}", state.next); // ["review"]
let out = app.invoke(Command::new().resume("approve"), cfg.clone()).await?;
println!("final state: {}", out.value);
Ok(())
}

This is the human_approval example: cargo run -p warpra --example human_approval.

How it works:

  • Warpra uses an unwind-and-re-run model. On resume, the interrupted node runs again from the top. This time ctx.interrupt returns the answer instead of stopping.
  • Tasks that already finished in the interrupted step are not re-run.
  • out.interrupts holds each Interrupt with its value and id. get_state shows the pending node in next and the interrupts in tasks and interrupts.
  • ctx.interrupt_as::<T>(payload) deserialises the answer into T.

When several interrupts are pending, for example from parallel nodes, resume them by id:

use std::collections::BTreeMap;
let mut answers = BTreeMap::new();
answers.insert(out.interrupts[0].id.clone(), json!("yes"));
answers.insert(out.interrupts[1].id.clone(), json!("no"));
app.invoke(Command::new().resume_map(answers), cfg.clone()).await?;

Interrupt ids are deterministic xxh3-128 hashes.

Strict resume is opt-in. Turn it on with RunConfig::with_strict_resume(true), or configurable["__pregel_strict_resume"] = true. A resume is then refused before anything is written when it:

  • names an unknown or already answered interrupt,
  • is an empty map,
  • or is a single value while several interrupts are pending.

The error is GraphError::UnknownInterrupt { reason, interrupt_ids, pending_ids, .. } with reason one of NotPending, EmptyMap or Ambiguous. Strict resume applies to the root graph only, and not to a checkpoint the thread has moved past.

Pause before or after named nodes without code in the node:

let app = g.compile(CompileOpts::new().checkpointer(saver).interrupt_before(["tools"]))?;

interrupt_after([..]), interrupt_before_all() and interrupt_after_all() also exist. StreamOpts can override them per run. To continue from a breakpoint, invoke with () as input:

let out = agent.invoke((), cfg.clone()).await?;

Before resuming you can edit the state with update_state. See Checkpoints and time travel.

ctx.interrupt works inside an Entrypoint and inside a task. See Functional API.

Interrupts inside a subgraph bubble up to the root run and resume there. When a parent graph time-travels, each subgraph’s first invocation restores its latest checkpoint from before the replay point (ReplayState). Later invocations, for example in a loop, load normally.

An interrupt is never routed to an error-handler node.

Warpra is open source under Apache-2.0. Made by Liceron.