Human-in-the-Loop and Checkpoints in Microsoft Agent Framework: Approvals, Crashes and Restarts

Andreas Nigg
Andreas Nigg · Co-Founder, Pondhouse Data
Published 18 min read
Human-in-the-Loop and Checkpoints in Microsoft Agent Framework: Approvals, Crashes and Restarts
On this page

An AI workflow that orders software licenses must not simply go ahead with 25 seats. It has to stop, ask a manager, wait for the answer, possibly overnight, and then continue exactly where it left off. If the server crashes or the container is redeployed in between, the approval must not get lost and the order must not go out twice. Microsoft Agent Framework has two building blocks for this: human-in-the-loop through ctx.request_info, and durable checkpoints. On November 30, 2026 we built both with agent-framework-core 1.26.0 (released November 12, 2026) and then broke them on purpose: with kill -9 in the middle of an LLM call, with crashes right after an order, with time travel to old checkpoints, and with the Azure AI Foundry host. This post shows every step with runnable code, the output from our runs and the measurements.

This is part 3 of our series. In part 1 we built an IT helpdesk agent with tools, DevUI, FastAPI and Docker, and in part 2 an IT ticket pipeline with WorkflowBuilder, executors and conditional edges. Part 2 only announced checkpoints and approvals. Now we build them. We assume you know executors, edges, supersteps and WorkflowContext.

Note on Azure AI Foundry: According to Microsoft Learn, the Foundry workflow designer and in-portal workflow execution are not supported after December 1, 2026. If you built workflows there, you end up with code-first workflows like the one in this post. Step 11 shows how to run exactly this workflow as a Foundry Hosted Agent.

What we build: a license approval with pause and revision

We automate the case part 2 named as an outlook: an employee requests software licenses, and above a certain amount a human has to approve. The workflow has three executors:

  1. intake: An agent reads the free text from the helpdesk and turns it into a structured LicenseRequest with product, seat count and justification.
  2. approval_gate: The price comes from a price list in code, not from the LLM. Up to €100 per month the workflow approves automatically. Above that it pauses with ctx.request_info and waits for a manager. If the manager rejects with feedback, the request goes back to intake (three rounds at most).
  3. provisioning: Orders the licenses in a simulated license shop, one line in orders.jsonl, and then sends the confirmation.

Architecture of the license approval: intake, approval_gate and provisioning, the pause through request_info, the loop on rejection and, below, the chain of checkpoints in FileCheckpointStorage

Every step runs as its own process through a small command line: start, inbox, decision, resume after a crash, and history. That way we test what happens in practice: hours pass between pause and answer, and the process that handles the answer has nothing in memory except the checkpoint.

The key results from our runs up front:

TestObservation
Pause, answer in a new processWorks across three processes, including rejection, LLM revision and approval
kill -9 during the LLM callResume repeats only this one LLM call (738 tokens); the first one (885 tokens) is kept
kill -9 after the orderWithout protection: two orders. With an idempotency check: one
Answering an old checkpoint againThe framework allows it and orders again. The Foundry host rejects it ("stale or forked")
Own types not allowedThe workflow pauses anyway, but without a checkpoint, with only a warning in the log
Overhead of FileCheckpointStorage1.65 ms instead of 0.47 ms up to the pause, about 2 KB per checkpoint
Restart in a fresh process until answerabout 340 ms, of which about 285 ms are Python imports

Prerequisites

  • Python 3.11 or newer. We tested with Python 3.13.13 and uv.
  • An LLM with an OpenAI-compatible API. We use nvidia/nemotron-3.5-lightning-30b-a3b through NVIDIA Build, because an API key is all it takes. According to its signature, OpenAIChatCompletionClient from agent-framework-openai also accepts azure_endpoint and credential for Azure OpenAI. We did not run that variant for this post.
  • For step 11: the agent-framework-foundry-hosting package. We ran the Foundry host locally. We did not run the deployment to Azure with azd; it needs an Azure subscription and a Foundry project.

The pinned versions from our test:

PackageVersionReleased
agent-framework-core1.26.02026-11-12
agent-framework-openai1.18.22026-11-12
agent-framework-devui1.0.0b2611122026-11-12
agent-framework-foundry-hosting1.0.0b2611122026-11-12

Step 1: Create an environment with pinned versions

1mkdir license-approval && cd license-approval
2uv venv --python 3.13 .venv && source .venv/bin/activate
3uv pip install "agent-framework-core==1.26.0" "agent-framework-openai==1.18.2" "agent-framework-devui==1.0.0b261112"
4export NVIDIA_API_KEY="nvapi-..." # or your own OpenAI-compatible endpoint

Since 2026, providers live in their own packages. The Python upgrade guide lists the changes since parts 1 and 2: ChatAgent is now Agent, the start node is passed to the constructor as WorkflowBuilder(start_executor=...), and streaming goes through workflow.run(..., stream=True); Workflow has no separate run_stream() in 1.26.0 anymore. Pin the whole set of packages, since the sub-packages have their own version numbers.

Step 2: Data models for request, approval and revision

Everything that flows between executors or waits in a pause ends up in a checkpoint later. That is why we use small Pydantic models with clear names. Create models.py:

1# models.py
2from pydantic import BaseModel, Field
3
4
5class TicketInput(BaseModel):
6 """Start message: the ticket ID from the helpdesk plus the user's text."""
7
8 ticket_id: str
9 text: str
10
11
12class LicenseRequest(BaseModel):
13 """Structured license request, extracted by the LLM."""
14
15 software: str = Field(description="Product name exactly as in the price list, or 'unknown'")
16 seats: int = Field(description="Number of licenses requested")
17 justification: str = Field(description="Business reason in one sentence")
18
19
20class ApprovalRequest(BaseModel):
21 """What the approver sees while the workflow is paused."""
22
23 request: LicenseRequest
24 monthly_total_eur: float
25 round: int
26
27
28class ApprovalDecision(BaseModel):
29 """The human answer that resumes the workflow."""
30
31 approved: bool = False
32 approver: str
33 comment: str = ""
34
35
36class RevisionRequest(BaseModel):
37 """Sent back to the intake agent when the approver asks for changes."""
38
39 previous: LicenseRequest
40 feedback: str
41 round: int
42
43
44class ProvisionOrder(BaseModel):
45 request: LicenseRequest
46 approved_by: str

We learned two details only while testing. DevUI builds a form from ApprovalDecision automatically and shows the docstring as its explanation (step 8). And without the default approved: bool = False, it marks the checkbox as required: the "Submit Response" button stays disabled until you tick the box, so a rejection is impossible in the form.

Step 3: Executors with request_info and @response_handler

The actual logic goes into workflow.py. We show the file in four parts; put together, they are exactly the file from our test.

Imports, price list and LLM client

1# workflow.py
2import asyncio
3import json
4import os
5import time
6from pathlib import Path
7
8from typing_extensions import Never
9
10from agent_framework import (
11 Agent,
12 Executor,
13 FileCheckpointStorage,
14 WorkflowBuilder,
15 WorkflowContext,
16 handler,
17 response_handler,
18)
19from agent_framework.openai import OpenAIChatCompletionClient
20from openai import AsyncOpenAI
21
22from models import (
23 ApprovalDecision,
24 ApprovalRequest,
25 LicenseRequest,
26 ProvisionOrder,
27 RevisionRequest,
28 TicketInput,
29)
30
31AUTO_APPROVE_LIMIT_EUR = 100.0 # monthly total below which no human is needed
32MAX_ROUNDS = 3
33ORDERS_FILE = Path("orders.jsonl")
34
35# Prices live in code, not in the LLM: EUR per seat and month (example values)
36PRICE_LIST = {"Figma Professional": 15.0, "Miro Business": 18.0, "Adobe Acrobat Pro": 23.0}
37
38INSTRUCTIONS = (
39 "You turn IT license requests into structured data. "
40 f"Known products: {', '.join(PRICE_LIST)}. "
41 "If the approver gives feedback, revise the request accordingly."
42)
43
44
45def make_client() -> OpenAIChatCompletionClient:
46 # NVIDIA Build is OpenAI-compatible. For Azure OpenAI: OpenAIChatCompletionClient(model=..., azure_endpoint=..., credential=...)
47 openai_client = AsyncOpenAI(
48 base_url=os.getenv("OPENAI_BASE_URL", "https://integrate.api.nvidia.com/v1"),
49 api_key=os.environ["NVIDIA_API_KEY"],
50 timeout=60, # a hanging LLM call must fail, not block the workflow forever
51 max_retries=2,
52 )
53 return OpenAIChatCompletionClient(
54 model=os.getenv("MODEL", "nvidia/nemotron-3.5-lightning-30b-a3b"),
55 async_client=openai_client,
56 )

We added the timeout after a failure: in our first runs, one LLM call hung for more than two minutes, without an error and without an answer. Without a timeout, such a call blocks the workflow indefinitely. With a timeout it fails, and you can restart the workflow from the last checkpoint.

The prices live in code on purpose. In early versions we let the LLM estimate the list price and got anything from €10.80 to €22 per seat for the same request. That is useless for an approval threshold.

Workflow step 1: intake with two handlers

1class IntakeExecutor(Executor):
2 """Step 1: the LLM turns free text (or reviewer feedback) into a LicenseRequest."""
3
4 def __init__(self) -> None:
5 super().__init__(id="intake")
6 self.agent = Agent(make_client(), instructions=INSTRUCTIONS, name="intake-agent")
7
8 async def _extract(self, prompt: str) -> LicenseRequest:
9 response = await self.agent.run(prompt, options={"response_format": LicenseRequest, "temperature": 0})
10 usage = response.usage_details or {}
11 print(f"[intake] LLM call, {usage.get('total_token_count')} tokens")
12 return response.value
13
14 @handler
15 async def from_ticket(self, ticket: TicketInput, ctx: WorkflowContext[ApprovalRequest]) -> None:
16 ctx.set_state("ticket_id", ticket.ticket_id) # shared state, part of every checkpoint
17 request = await self._extract(ticket.text)
18 await ctx.send_message(_to_approval(request, round=1))
19
20 @handler
21 async def revise(self, rev: RevisionRequest, ctx: WorkflowContext[ApprovalRequest]) -> None:
22 prompt = (
23 f"Previous request: {rev.previous.model_dump_json()}\n"
24 f"Approver feedback: {rev.feedback}\n"
25 "Return the revised request."
26 )
27 request = await self._extract(prompt)
28 await ctx.send_message(_to_approval(request, round=rev.round))
29
30
31def _to_approval(request: LicenseRequest, round: int) -> ApprovalRequest:
32 price = PRICE_LIST.get(request.software, float("inf")) # unknown product: always a human
33 return ApprovalRequest(request=request, monthly_total_eur=request.seats * price, round=round)

An executor can have several @handler methods. The framework picks one by message type: TicketInput goes to from_ticket, RevisionRequest to revise. ctx.set_state stores the ticket ID in the workflow's shared state. It is saved with every checkpoint, and provisioning reads it later for the idempotency check.

Workflow step 2: the approval with request_info

1class ApprovalGate(Executor):
2 """Step 2: auto-approve small requests, pause for a human above the limit."""
3
4 def __init__(self) -> None:
5 super().__init__(id="approval_gate")
6
7 @handler
8 async def check(
9 self, approval: ApprovalRequest, ctx: WorkflowContext[ProvisionOrder | RevisionRequest]
10 ) -> None:
11 if approval.monthly_total_eur <= AUTO_APPROVE_LIMIT_EUR:
12 print(f"[gate] {approval.monthly_total_eur} EUR <= limit, auto-approved")
13 await ctx.send_message(ProvisionOrder(request=approval.request, approved_by="auto-policy"))
14 return
15 print(f"[gate] {approval.monthly_total_eur} EUR > limit, waiting for a human")
16 await ctx.request_info(request_data=approval, response_type=ApprovalDecision)
17
18 @response_handler
19 async def on_decision(
20 self,
21 original_request: ApprovalRequest,
22 decision: ApprovalDecision,
23 ctx: WorkflowContext[ProvisionOrder | RevisionRequest, str],
24 ) -> None:
25 if decision.approved:
26 await ctx.send_message(ProvisionOrder(request=original_request.request, approved_by=decision.approver))
27 elif original_request.round < MAX_ROUNDS:
28 await ctx.send_message(
29 RevisionRequest(
30 previous=original_request.request,
31 feedback=decision.comment,
32 round=original_request.round + 1,
33 )
34 )
35 else:
36 await ctx.yield_output(f"Rejected after {original_request.round} rounds: {decision.comment}")

This class holds the human-in-the-loop part. ctx.request_info(request_data=..., response_type=...) emits an event of type request_info and ends the superstep. If there is nothing else to do, the workflow switches to IDLE_WITH_PENDING_REQUESTS and saves a checkpoint with the open request. The @response_handler method later receives both sides: the original request and the answer. The framework matches them through the type annotations of original_request and decision. So you do not have to keep anything in instance variables, which a restart would wipe anyway.

Workflow step 3: provisioning, graph and storage

1class ProvisioningExecutor(Executor):
2 """Step 3: call the (simulated) license shop API. Slow on purpose for the crash test."""
3
4 def __init__(self) -> None:
5 super().__init__(id="provisioning")
6
7 @handler
8 async def provision(self, order: ProvisionOrder, ctx: WorkflowContext[Never, str]) -> None:
9 ticket_id = ctx.get_state("ticket_id")
10 if os.getenv("IDEMPOTENT", "1") == "1" and _already_ordered(ticket_id):
11 await ctx.yield_output(f"{ticket_id}: already ordered, nothing to do")
12 return
13 print(f"[provisioning] {ticket_id}: ordering {order.request.seats}x {order.request.software}", flush=True)
14 with ORDERS_FILE.open("a") as f: # the side effect: a real order in the license shop
15 f.write(json.dumps({"ticket_id": ticket_id, "seats": order.request.seats, "ts": time.time()}) + "\n")
16 # e.g. confirmation mail and CMDB update, slow on purpose for the crash test
17 await asyncio.sleep(float(os.getenv("PROVISION_DELAY", "0")))
18 await ctx.yield_output(
19 f"{ticket_id}: ordered {order.request.seats}x {order.request.software}, approved by {order.approved_by}"
20 )
21
22
23def _already_ordered(ticket_id: str) -> bool:
24 if not ORDERS_FILE.exists():
25 return False
26 return any(json.loads(line)["ticket_id"] == ticket_id for line in ORDERS_FILE.read_text().splitlines())
27
28
29def build_workflow(storage: FileCheckpointStorage | None = None):
30 intake, gate, provisioning = IntakeExecutor(), ApprovalGate(), ProvisioningExecutor()
31 return (
32 WorkflowBuilder(name="license-approval", start_executor=intake, checkpoint_storage=storage)
33 .add_edge(intake, gate)
34 .add_edge(gate, provisioning, condition=lambda m: isinstance(m, ProvisionOrder))
35 .add_edge(gate, intake, condition=lambda m: isinstance(m, RevisionRequest))
36 .build()
37 )
38
39
40# Our own types that may appear in checkpoints ("module:qualname")
41CHECKPOINT_TYPES = [
42 "models:TicketInput",
43 "models:LicenseRequest",
44 "models:ApprovalRequest",
45 "models:ApprovalDecision",
46 "models:RevisionRequest",
47 "models:ProvisionOrder",
48]
49
50
51def make_storage(ticket_id: str) -> FileCheckpointStorage:
52 # one folder per ticket: get_latest() only sees this ticket's history
53 return FileCheckpointStorage(f"./checkpoints/{ticket_id}", allowed_checkpoint_types=CHECKPOINT_TYPES)

Three details in this part need an explanation:

  • The IDEMPOTENT environment variable only exists for our experiment in step 6. In your code, the check belongs in there permanently.
  • allowed_checkpoint_types: FileCheckpointStorage stores your own classes with pickle and, for security reasons, only loads allowed types. A missing type leads to something unpleasant that we show in step 9.
  • One folder per ticket: checkpoints carry no run ID, only the workflow name. In a shared folder, storage.get_latest() with the workflow name therefore returns the newest checkpoint of any ticket. In our first draft, exactly that matched an approval to the wrong run.

The gate -> intake loop is allowed; workflows may contain cycles. WorkflowBuilder caps supersteps at 100 by default (max_iterations), and our own limit of three rounds kicks in long before that.

Step 4: Start, inbox and decision in separate processes

The app.py command line stands in for what a web app or a Teams bot would do in production. Every command is its own process:

1# app.py
2import argparse
3import asyncio
4from pathlib import Path
5
6from models import ApprovalDecision, TicketInput
7from workflow import build_workflow, make_storage
8
9WORKFLOW = "license-approval"
10
11
12async def show(stream) -> list[str]:
13 """Print the interesting events, return the IDs of open approval requests."""
14 request_ids = []
15 async for event in stream:
16 if event.type == "request_info":
17 req = event.data
18 request_ids.append(event.request_id)
19 print(
20 f"[pause] approval needed: {req.request.seats}x {req.request.software}, "
21 f"{req.monthly_total_eur} EUR/month (round {req.round})"
22 )
23 elif event.type == "output":
24 print(f"[output] {event.data}")
25 return request_ids
26
27
28async def ensure_durable(workflow, request_ids: list[str]) -> None:
29 """Fail loudly if the pause did not reach the checkpoint storage."""
30 if request_ids and await workflow.resolve_pause_checkpoint_id(request_ids) is None:
31 raise RuntimeError("Pause is not checkpointed. Check allowed_checkpoint_types.")
32
33
34async def start(ticket_id: str, text: str) -> None:
35 storage = make_storage(ticket_id)
36 workflow = build_workflow(storage)
37 request_ids = await show(workflow.run(TicketInput(ticket_id=ticket_id, text=text), stream=True))
38 await ensure_durable(workflow, request_ids)
39 print(f"[state] {workflow.status.value}")
40
41
42async def inbox(ticket_id: str) -> None:
43 storage = make_storage(ticket_id)
44 latest = await storage.get_latest(workflow_name=WORKFLOW)
45 for request_id, event in latest.pending_request_info_events.items():
46 req = event.data
47 print(f"{ticket_id} checkpoint={latest.checkpoint_id[:8]} request={request_id[:8]} "
48 f"{req.request.seats}x {req.request.software} {req.monthly_total_eur} EUR/month")
49
50
51async def decide(ticket_id: str, approve: bool, approver: str, comment: str, checkpoint_id: str | None) -> None:
52 storage = make_storage(ticket_id)
53 if checkpoint_id is None:
54 checkpoint_id = (await storage.get_latest(workflow_name=WORKFLOW)).checkpoint_id
55 checkpoint = await storage.load(checkpoint_id)
56 (request_id,) = checkpoint.pending_request_info_events # exactly one open approval
57 decision = ApprovalDecision(approved=approve, approver=approver, comment=comment)
58
59 workflow = build_workflow(storage) # new process, new objects, same graph
60 stream = workflow.run(checkpoint_id=checkpoint_id, responses={request_id: decision}, stream=True)
61 await ensure_durable(workflow, await show(stream))
62
63
64async def resume(ticket_id: str, checkpoint_id: str | None) -> None:
65 storage = make_storage(ticket_id)
66 if checkpoint_id is None:
67 checkpoint_id = (await storage.get_latest(workflow_name=WORKFLOW)).checkpoint_id
68 workflow = build_workflow(storage)
69 await show(workflow.run(checkpoint_id=checkpoint_id, stream=True))
70
71
72async def history(ticket_id: str) -> None:
73 storage = make_storage(ticket_id)
74 checkpoints = sorted(await storage.list_checkpoints(workflow_name=WORKFLOW), key=lambda c: c.timestamp)
75 print(f"{'#':>2} {'checkpoint':<10} {'parent':<8} {'step':>4} {'bytes':>5} messages from / open request")
76 for i, cp in enumerate(checkpoints, 1):
77 size = Path(storage.storage_path, f"{cp.checkpoint_id}.json").stat().st_size
78 senders = ",".join(sorted(cp.messages)) or "-"
79 pending = " ".join(f"approval round {e.data.round}" for e in cp.pending_request_info_events.values())
80 parent = (cp.previous_checkpoint_id or "-")[:8]
81 print(f"{i:>2} {cp.checkpoint_id[:8]:<10} {parent:<8} {cp.iteration_count:>4} {size:>5} {pending or senders}")
82
83
84def main() -> None:
85 p = argparse.ArgumentParser()
86 p.add_argument("--ticket", required=True)
87 sub = p.add_subparsers(dest="cmd", required=True)
88 sub.add_parser("start").add_argument("text")
89 sub.add_parser("inbox")
90 d = sub.add_parser("decide")
91 d.add_argument("--approve", action="store_true")
92 d.add_argument("--approver", default="m.huber")
93 d.add_argument("--comment", default="")
94 d.add_argument("--checkpoint")
95 sub.add_parser("resume").add_argument("--checkpoint")
96 sub.add_parser("history")
97 a = p.parse_args()
98 match a.cmd:
99 case "start":
100 asyncio.run(start(a.ticket, a.text))
101 case "inbox":
102 asyncio.run(inbox(a.ticket))
103 case "decide":
104 asyncio.run(decide(a.ticket, a.approve, a.approver, a.comment, a.checkpoint))
105 case "resume":
106 asyncio.run(resume(a.ticket, a.checkpoint))
107 case "history":
108 asyncio.run(history(a.ticket))
109
110
111if __name__ == "__main__":
112 main()

The core is in decide. workflow.run(checkpoint_id=..., responses=...) restores the checkpoint and delivers the answer in a single call. The answer is a dictionary from request ID to response object. We read the request ID from the checkpoint's pending_request_info_events, so the process does not need to know anything from the first run.

Let's start the first ticket. The request text is German, as it would be in our helpdesk:

1python app.py --ticket IT-4711 start "Wir brauchen 25 Lizenzen Figma Professional für das neue Design-Team ab Jänner."
2python app.py --ticket IT-4711 inbox
1[intake] LLM call, 885 tokens
2[gate] 375.0 EUR > limit, waiting for a human
3[pause] approval needed: 25x Figma Professional, 375.0 EUR/month (round 1)
4[state] IDLE_WITH_PENDING_REQUESTS
5
6IT-4711 checkpoint=42f435e0 request=fdf3e978 25x Figma Professional 375.0 EUR/month

The first run took 6.3 seconds, nearly all of it the LLM call. Then the process ends. The folder checkpoints/IT-4711/ now holds three JSON files. The checkpoint of the pause looks like this, shortened:

1{
2 "workflow_name": "license-approval",
3 "graph_signature_hash": "59a645c01d3ef3183112bc8ac057d7d9f3c15180f8c30313522d84c6e2a37544",
4 "checkpoint_id": "42f435e0-056e-4531-a55b-2ca1d8acf9f6",
5 "previous_checkpoint_id": "21ed4824-2833-4906-ba48-6c74cfcf7699",
6 "messages": {},
7 "state": {
8 "_executor_state": {
9 "intake": {},
10 "approval_gate": {},
11 "provisioning": {}
12 },
13 "ticket_id": "IT-4711"
14 },
15 "pending_request_info_events": {
16 "fdf3e978-ef24-4ea7-829c-bf1c0bcb9963": {
17 "__pickled__": "gAWVcQMAAAAAAACMImFnZW50...",
18 "__type__": "agent_framework._workflows._events:WorkflowEvent"
19 }
20 },
21 "iteration_count": 2
22}

You can see the shared state (ticket_id), the graph hash and the open request. The request itself is embedded as a base64 pickle. So the file is only partly readable, and anyone with write access to the folder can inject code that the next restore will execute. Microsoft states this explicitly in the checkpoint documentation: the storage is a trust boundary, never load checkpoints from untrusted sources.

Step 5: Reject with feedback, the LLM revises the request

The manager wants only 10 seats for now. The command for that, again in a new process:

1python app.py --ticket IT-4711 decide --comment "Bitte zuerst nur 10 Plätze, der Rest nach der Probezeit."

If you want to reproduce the crash test from step 6 on this ticket, do not run this command yet. In step 6 we send exactly this rejection through crash.sh and kill the process halfway.

The @response_handler sends a RevisionRequest back to intake, the LLM revises the request, and the gate pauses again with 10 seats and €150 per month. The history shows when the framework saves along the way. The output below is from the end, after the rejection, crash, resume, approval and order from steps 5 and 6 had all run:

1python app.py --ticket IT-4711 history
1 # checkpoint parent step bytes messages from / open request
2 1 4f917931 - 0 1443 internal:intake
3 2 21ed4824 4f917931 1 1876 intake
4 3 42f435e0 21ed4824 2 2032 approval round 1
5 4 78778162 42f435e0 2 2532 internal:approval_gate
6 5 c7e65f78 78778162 3 1947 approval_gate
7 6 be85bd14 c7e65f78 4 1644 intake
8 7 fdfe068f be85bd14 5 1800 approval round 2
9 8 65a1d291 fdfe068f 5 2228 internal:approval_gate
10 9 00757d8c 65a1d291 6 1639 approval_gate
1110 4b80f7d0 00757d8c 7 691 -

The right-hand column shows which executor still has messages in flight or which approval is open. Since version 1.13.0 the framework writes, in addition to the checkpoints at the end of each superstep, an entry checkpoint at the start (#1) and one whenever a response arrives (#4 and #8). That is why #3 and #4 share the same step number. The 1.13.0 migration guide warns about exactly this: order comes from previous_checkpoint_id and the timestamp, not from iteration_count. All files are between 0.7 and 2.5 KB.

Step 6: Simulate a crash with kill -9

A cleanly exiting process tells you little about recovery. So we kill the process in the middle of its work with SIGKILL, with no chance to clean up. A small script does that:

1#!/usr/bin/env bash
2# crash.sh <seconds> <app.py arguments...>: start app.py, then SIGKILL it
3secs=$1; shift
4python -u app.py "$@" &
5PID=$!
6sleep "$secs"
7kill -9 "$PID" && echo "[kill -9] python pid $PID after ${secs}s"
8wait "$PID" 2>/dev/null

Make it executable with chmod +x crash.sh. The delay has to be shorter than your model's response time. Our LLM calls took 6 to 8 seconds, so 2.5 seconds reliably hit the running call.

Crash 1: in the middle of the LLM call

The rejection from step 5 actually went like this: after 2.5 seconds, while intake was still waiting for the LLM, we killed the process.

1./crash.sh 2.5 --ticket IT-4711 decide --comment "Bitte zuerst nur 10 Plätze, der Rest nach der Probezeit."
2python app.py --ticket IT-4711 history
3python app.py --ticket IT-4711 resume
1[kill -9] python pid 1002596 after 2.5s
2
3 # checkpoint parent step bytes messages from / open request
4 1 4f917931 - 0 1443 internal:intake
5 2 21ed4824 4f917931 1 1876 intake
6 3 42f435e0 21ed4824 2 2032 approval round 1
7 4 78778162 42f435e0 2 2532 internal:approval_gate
8 5 c7e65f78 78778162 3 1947 approval_gate
9
10[intake] LLM call, 738 tokens
11[gate] 150.0 EUR > limit, waiting for a human
12[pause] approval needed: 10x Figma Professional, 150.0 EUR/month (round 2)

The manager's decision was not lost; it is stored in #4 and #5. resume starts at #5 and runs only the interrupted superstep: one LLM call with 738 tokens. The first call with 885 tokens from the start does not run again, and above all nobody has to repeat the approval.

Crash 2: after the order, before the checkpoint

Now the unpleasant case. The manager approves 10 seats, provisioning writes the order and then needs 5 seconds for the confirmation. After 2 seconds we kill the process. For this test, the idempotency protection is switched off:

1IDEMPOTENT=0 PROVISION_DELAY=5 ./crash.sh 2 --ticket IT-4711 decide --approve --approver m.huber
2IDEMPOTENT=0 python app.py --ticket IT-4711 resume
3cat orders.jsonl
1[provisioning] IT-4711: ordering 10x Figma Professional
2[kill -9] python pid 1003819 after 2s
3
4[provisioning] IT-4711: ordering 10x Figma Professional
5[output] IT-4711: ordered 10x Figma Professional, approved by m.huber
6
7{"ticket_id": "IT-4711", "seats": 10, "ts": 1796042362.5599663}
8{"ticket_id": "IT-4711", "seats": 10, "ts": 1796042364.5984783}

The file now holds two orders for one ticket. The cause is when checkpoints are written: at the end of a superstep. The last checkpoint (#9) contains the message to provisioning, but not the fact that the order already went out. On resume, the whole step runs again. So the framework guarantees "at least once", not "exactly once".

Pause, crash and resume for ticket IT-4711 across five processes: two pauses, one crash during the LLM call, one crash after the order and the resulting duplicate order

With the protection switched on, we repeat the same thing with a second ticket:

1python app.py --ticket IT-4712 start "Für den Workshop-Raum brauchen wir 12 Miro Business Lizenzen."
2PROVISION_DELAY=5 ./crash.sh 2 --ticket IT-4712 decide --approve --approver m.huber
3python app.py --ticket IT-4712 resume
1[intake] LLM call, 861 tokens
2[gate] 216.0 EUR > limit, waiting for a human
3[pause] approval needed: 12x Miro Business, 216.0 EUR/month (round 1)
4[state] IDLE_WITH_PENDING_REQUESTS
5
6[provisioning] IT-4712: ordering 12x Miro Business
7[kill -9] python pid 1005407 after 2s
8
9[output] IT-4712: already ordered, nothing to do

This time there is exactly one order. In real systems, the idempotency key (here the ticket ID) belongs in the license shop's API or in a database with a unique index, not in a local file. Also keep in mind that our guard skips the confirmation mail after the restart as well. Every side effect needs its own protection, or you split it into its own executor so that a checkpoint lands in between. We cover more failure modes of agent systems in our post on high-quality AI agent systems.

A ticket below the threshold runs through without a pause:

1[intake] LLM call, 842 tokens
2[gate] 72.0 EUR <= limit, auto-approved
3[provisioning] IT-4713: ordering 4x Miro Business
4[output] IT-4713: ordered 4x Miro Business, approved by auto-policy
5[state] IDLE

Step 7: Time travel to an old checkpoint

Every checkpoint stays on disk, and every one can be loaded again. That is useful for debugging and what-if questions. We load the first pause (#3, 25 seats), even though the ticket was closed long ago, and approve it as the CFO:

1python app.py --ticket IT-4711 decide --approve --approver cfo --checkpoint 42f435e0-056e-4531-a55b-2ca1d8acf9f6
2IDEMPOTENT=0 python app.py --ticket IT-4711 decide --approve --approver cfo --checkpoint 42f435e0-056e-4531-a55b-2ca1d8acf9f6
1[output] IT-4711: already ordered, nothing to do
2
3[provisioning] IT-4711: ordering 25x Figma Professional
4[output] IT-4711: ordered 25x Figma Professional, approved by cfo

The full checkpoint ID is the file name under checkpoints/IT-4711/; history only shows the first eight characters. Use the ID of your own round 1 pause checkpoint.

With protection, nothing happens. Without it, the workflow orders another 25 seats, although the request was rejected in round 1 and closed with 10 seats in round 2. The history shows two new branches, both with #3 as their parent:

111 f84badf3 42f435e0 2 2452 internal:approval_gate
212 46333913 f84badf3 3 1863 approval_gate
313 ed7236c4 46333913 4 691 -
414 1cb1ee31 42f435e0 2 2452 internal:approval_gate
515 1e5aea7f 1cb1ee31 3 1863 approval_gate
616 87c385ba 1e5aea7f 4 691 -

Time travel: two new runs branch off checkpoint 3, with the guard nothing is ordered, without it 25 more seats are ordered, and the Foundry host rejects a repeated answer

So the checkpoint storage does not stop anyone from answering the same pause twice. If you accept approvals through a web app, mark each request ID as "answered" the first time you process it and reject every later answer. The Foundry host from step 11 already does this on its own.

Step 8: Approve in DevUI

For development and demos you do not need to build your own UI. The DevUI from parts 1 and 2 can now show and answer approvals. devui_app.py:

1# devui_app.py: show the workflow graph in the DevUI
2from agent_framework.devui import serve
3
4from workflow import build_workflow, make_storage
5
6workflow = build_workflow(make_storage("devui"))
7
8if __name__ == "__main__":
9 serve(entities=[workflow], port=8091, auto_open=False, auth_token="local-demo")

In agent-framework-devui 1.0.0b261112, the API requires a bearer token by default. Without auth_token, serve generates a random token at startup and writes it to the log. The web UI asks for it on first load. Through "Configure & Run", DevUI builds a form with the fields ticket_id and text from TicketInput. As soon as the workflow pauses, "Workflow is waiting for your input" appears, with the form generated from ApprovalDecision below it:

DevUI with a paused workflow: the approval request shows the product, 25 seats and 375 euros per month, with the generated form for approver, checkbox and comment below

With "approved" unticked and the comment "Bitte zuerst nur 10 Plätze." ("only 10 seats for now"), the request goes back to intake. A few seconds later, round 2 with 10 seats and €150 shows up in the form:

DevUI after the rejection: round 2 of the approval request with 10 seats and 150 euros per month, again with an open form

The "Checkpoint Storage" selector in the top right shows that DevUI also works with checkpoints. We did not test that feature further. For production, DevUI is no replacement for an approval front end: it has no roles, no notifications and no inbox across tickets.

Step 9: Four pitfalls when resuming

What happens when something does not fit on resume? We triggered the most common errors on purpose:

1# edge_cases.py: four ways a resume goes wrong
2import asyncio
3
4from agent_framework import FileCheckpointStorage, WorkflowBuilder
5
6from models import ApprovalDecision, ProvisionOrder, RevisionRequest, TicketInput
7from workflow import ApprovalGate, IntakeExecutor, ProvisioningExecutor, build_workflow, make_storage
8
9
10async def missing_types() -> None:
11 storage = FileCheckpointStorage("./checkpoints/IT-9001") # no allowed_checkpoint_types
12 workflow = build_workflow(storage)
13 ticket = TicketInput(ticket_id="IT-9001", text="Wir brauchen 25 Lizenzen Figma Professional.")
14 ids = [e.request_id async for e in workflow.run(ticket, stream=True) if e.type == "request_info"]
15 print("1) pause checkpoint:", await workflow.resolve_pause_checkpoint_id(ids))
16
17
18async def try_resume(label: str, workflow, checkpoint_id: str, responses: dict) -> None:
19 try:
20 await workflow.run(checkpoint_id=checkpoint_id, responses=responses)
21 except Exception as ex:
22 print(f"{label}: {type(ex).__name__}: {ex}")
23
24
25async def main() -> None:
26 await missing_types()
27
28 storage = make_storage("IT-4711")
29 pause_id = "42f435e0-056e-4531-a55b-2ca1d8acf9f6" # checkpoint #3 from the main run
30 request_id = next(iter((await storage.load(pause_id)).pending_request_info_events))
31 ok = ApprovalDecision(approved=True, approver="m.huber")
32
33 # 2) refactoring: same IDs and edges, but the gate class got a new name
34 class ApprovalGateV2(ApprovalGate):
35 pass
36
37 intake, gate, provisioning = IntakeExecutor(), ApprovalGateV2(), ProvisioningExecutor()
38 changed = (
39 WorkflowBuilder(name="license-approval", start_executor=intake, checkpoint_storage=storage)
40 .add_edge(intake, gate)
41 .add_edge(gate, provisioning, condition=lambda m: isinstance(m, ProvisionOrder))
42 .add_edge(gate, intake, condition=lambda m: isinstance(m, RevisionRequest))
43 .build()
44 )
45 await try_resume("2) changed graph", changed, pause_id, {request_id: ok})
46 # 3) wrong response type, 4) unknown request ID
47 await try_resume("3) wrong type", build_workflow(storage), pause_id, {request_id: True})
48 await try_resume("4) unknown ID", build_workflow(storage), pause_id, {"abc": ok})
49
50
51asyncio.run(main())

Set pause_id to a pause checkpoint from your own run. The output, with the three long warnings shortened:

1Failed to create checkpoint at iteration 0: Failed to decode pickled checkpoint data: Checkpoint deserialization blocked for type 'models:TicketInput'. [...] Note that this does not fail the workflow run.
2[intake] LLM call, 1085 tokens
3[gate] 375.0 EUR > limit, waiting for a human
41) pause checkpoint: None
52) changed graph: WorkflowCheckpointException: Workflow graph has changed since the checkpoint was created. Please rebuild the original workflow before resuming.
63) wrong type: ValueError: Response type mismatch for request ID fdf3e978-ef24-4ea7-829c-bf1c0bcb9963: expected <class 'models.ApprovalDecision'>, got <class 'bool'>
74) unknown ID: ValueError: Response provided for unknown request ID: abc
CaseBehavior in 1.26.0What to do
Own types not allowedNot a single checkpoint, the run pauses anyway, only warnings in the logMaintain allowed_checkpoint_types, check the pause with resolve_pause_checkpoint_id
Executor class renamed or edge addedWorkflowCheckpointException, nothing runsFinish old runs with old code, version graph changes
Answer with the wrong typeValueError before anything runsValidate answers before sending (Pydantic)
Unknown request IDValueError before anything runsAlways read the request ID from the checkpoint
Logic inside an executor changedNo error: the hash only covers IDs, class names and edgesDecide deliberately whether old runs may continue with new logic

The first case is the most dangerous. Since a fix that the source code records as issue #8181, the framework already checks at save time whether a checkpoint could be loaded again, and refuses to save it. But the run goes on and ends with a normal IDLE_WITH_PENDING_REQUESTS. If the process exits now, the approval is lost. That is why our app.py calls ensure_durable after every pause: resolve_pause_checkpoint_id returns None if no saved checkpoint contains the open request. As for the graph hash: according to the source (_compute_graph_signature), it covers executor IDs, the module and class name of each executor, the edges and the names of the conditions. It does not notice a changed approval threshold.

Step 10: What checkpoints cost

We ran the workflow 40 times with an LLM stub and no network: once without checkpoints, once with InMemoryCheckpointStorage and once with FileCheckpointStorage on a local SSD. We measured the time up to the pause and from the answer to the end. Every run starts with fresh executor objects. In the two checkpointed variants we also rebuild the workflow between pause and answer; without checkpoints, the same instance receives the answer.

Two charts: at the top the overhead per run, 0.47 milliseconds without checkpoints and 1.65 milliseconds with FileCheckpointStorage up to the pause; at the bottom the checkpoint size, which grows with the payload from 2.1 KB to 1.3 MB per file

StorageUp to the pause (median)Answer to end (median)
No checkpoints0.47 ms0.49 ms
InMemoryCheckpointStorage0.69 ms0.84 ms
FileCheckpointStorage1.65 ms1.84 ms

Next to an LLM call of 6 to 8 seconds, that does not register. The cold start costs more: a fresh Python process that loads a paused run and handles the approval took about 340 ms across five runs. About 285 ms of that were imports, 34 ms loading the checkpoint and building the graph, and 19 ms restore and execution.

Size depends almost entirely on the payload. With a short justification, the largest checkpoint was 2.1 KB and all six of one run together 8.9 KB. With a 1 MB document inside the message, each checkpoint grows to 1.3 MB (pickle plus base64) and the run takes 5.3 MB, because the message sits in several checkpoints. Large documents therefore belong in blob storage, and only the URL travels through the workflow. For workflows with many steps, a cleanup rule pays off as well, because FileCheckpointStorage never deletes anything on its own.

Step 11: The same workflow as a Foundry Hosted Agent

So far we hosted the workflow ourselves, as in part 1 with FastAPI and Docker. The alternative is Microsoft Foundry Hosted Agents: Microsoft runs the container, the sessions, the identity and the endpoints. According to the documentation, the service is generally available, while the Python package agent-framework-foundry-hosting is a prerelease. It can host a Workflow directly, without wrapping it in an agent.

We installed the package in a second virtual environment and ran it locally:

1uv pip install "agent-framework-core==1.26.0" "agent-framework-openai==1.18.2" "agent-framework-foundry-hosting==1.0.0b261112"
1# host.py: the same workflow behind the Foundry Responses protocol
2from agent_framework_foundry_hosting import (
3 CheckpointStoreProvider,
4 HostedResponseRequest,
5 ResponsesHostServer,
6 WorkflowTurn,
7)
8
9from models import TicketInput
10from workflow import CHECKPOINT_TYPES, build_workflow
11
12
13def workflow_factory(request: HostedResponseRequest):
14 # fresh graph per request; the host manages checkpoints, so no storage here
15 return build_workflow()
16
17
18async def parse_response(request: HostedResponseRequest) -> WorkflowTurn[TicketInput]:
19 items = await request.get_input_items()
20 if any(item.get("type") == "function_call_output" for item in items):
21 return WorkflowTurn(responses=await request.get_workflow_responses())
22 return WorkflowTurn(input=TicketInput.model_validate_json(await request.get_input_text() or ""))
23
24
25server = ResponsesHostServer(
26 workflow=workflow_factory,
27 parse_response=parse_response,
28 checkpoint_store_provider=CheckpointStoreProvider(allowed_checkpoint_types=CHECKPOINT_TYPES),
29)
30
31if __name__ == "__main__":
32 server.run() # http://localhost:8088/responses

workflow.py and models.py stay unchanged. Two rules from the documentation matter here: the factory must return a fresh graph for every request, and the workflow itself gets no checkpoint storage, because the host manages it. Locally, the host writes files under ~/.agentserver/; in Foundry it uses the Foundry State Store.

A new ticket with curl:

1python host.py &
2sleep 5 # wait for imports and the port binding
3curl -s localhost:8088/responses -H "Content-Type: application/json" -d '{
4 "store": true,
5 "input": "{\"ticket_id\": \"IT-4740\", \"text\": \"Wir brauchen 12 Miro Business Lizenzen für den Workshop-Raum.\"}"
6}' > h1.json
7jq '{id, agent_session_id, status, output: [.output[] | {type, name, call_id, arguments}]}' h1.json
1{
2 "id": "caresp_354f0b702ba2b47c00M3UhAUcGavY111btUFv48jjVdACvGZbH",
3 "agent_session_id": "34bf1ffe9c0db7bc19db42d843998059c766ec6832bf3278ccc0a9bc72f74a0",
4 "status": "completed",
5 "output": [
6 {
7 "type": "function_call",
8 "name": "request_info",
9 "call_id": "call_354f0b702ba2b47c00S1Br7y5HuuI5O13TA5L9yuJlWJMt9zyH",
10 "arguments": "{\"request_id\": \"call_354f0b702ba2b47c00S1Br7y5HuuI5O13TA5L9yuJlWJMt9zyH\", \"request\": {\"request\": {\"software\": \"Miro Business\", \"seats\": 12, \"justification\": \"Workshop room setup (German: Workshop-Raum requester context assumed internal/team use status pending approval)\"}, \"monthly_total_eur\": 216.0, \"round\": 1}}"
11 }
12 ]
13}

The pause shows up as a regular function_call named request_info, which any OpenAI-compatible client understands. Then we killed the host with kill -9, restarted it and sent the approval as a function_call_output:

1REPLY=$(jq -n --slurpfile r h1.json '{
2 store: true,
3 previous_response_id: $r[0].id,
4 agent_session_id: $r[0].agent_session_id,
5 input: [{type: "function_call_output", call_id: $r[0].output[0].call_id,
6 output: ({approved: true, approver: "m.huber", comment: "Passt."} | tojson)}]}')
7curl -s localhost:8088/responses -H "Content-Type: application/json" -d "$REPLY" | jq '{status, text: .output[0].content[0].text, error}'
8curl -s localhost:8088/responses -H "Content-Type: application/json" -d "$REPLY" | jq '{status, error}'
1{ "status": "completed", "text": "IT-4740: ordered 12x Miro Business, approved by m.huber", "error": null }
2{ "status": "failed", "error": { "code": "server_error", "message": "This workflow continuation is stale or forked; use its current response." } }

The restart caused no trouble, and the host rejects the repeated answer. That is the protection we had to build by hand in step 7. One pitfall cost us some time: locally, the Foundry platform context is missing, so the host derives the session from agent_session_id. Without that field in the second request, it only answers "Native workflow scoped continuation failed", and the log says "The previous response has no completed workflow checkpoint in this trusted scope". In Foundry, the platform sets the session itself.

The actual deployment follows the guide on Microsoft Learn with azd ext install azure.ai.agents, azd ai agent init, azd provision and azd deploy. We did not run this part for this post. Check model availability, quota and region for your Foundry project first.

CriterionSelf-hosted (FastAPI, Docker)Foundry Hosted AgentDurable Extension (Azure Functions)
CheckpointsYour own storage, e.g. files or Cosmos DBManaged by the host (Foundry State Store)Durable Task Scheduler
Duplicate answersLock them yourself (step 7)Rejected ("stale or forked")Not tested
Interface for approvalsYour choiceResponses API: function_call and function_call_outputHTTP and function triggers
Identity and scalingBuild it yourselfOwn Entra identity, scaling by FoundryAzure Functions
Package status (Nov 2026)agent-framework-core stableService GA, Python package prereleaseagent-framework-azurefunctions 1.0.0, Python 3.13+
Tested in this postYesLocally yes, deployment noNo

The Durable Extension makes sense if you already run on Azure Functions and spread long orchestrations across many workers. For most approval workflows, one of the first two options is enough.

Limits and when you need something else

  • Exactly-once does not come for free. Checkpoints secure the state between steps. Anything with a side effect needs an idempotency key, no matter where you host. Microsoft says so explicitly for the Durable Extension: durable checkpointing does not make writes "exactly-once". According to the documentation, the same applies to the Foundry host.
  • Pickle is a trust boundary. Make the checkpoint folder writable only for the service. If your security model rules out pickle entirely, your only option is a custom CheckpointStorage with a different serialization.
  • Multiple instances. A Workflow instance handles one run at a time; a second run() raises an error. Build a fresh graph per request, as the Foundry host requires anyway.
  • No inbox. The framework knows the open requests of a run, but not a list of every pending approval in the company. You need that as your own table or as part of your ticketing system.
  • Observability. Who approved what and when belongs in an audit log and in traces. We show how to do that with OpenTelemetry in our post on Langfuse for LLM observability.

Conclusion

Human-in-the-loop and checkpoints worked in all our tests with Microsoft Agent Framework 1.26.0. A workflow pauses with one line of code, survives kill -9 at every point we tried, and picks up again in a new process in about 340 milliseconds. Expensive LLM calls and, above all, human decisions are not lost, and the overhead is about one millisecond per run.

Most of the effort sits outside the framework: making side effects idempotent, locking answers to old checkpoints, allowing your own types and checking that every pause really was saved. These are exactly the places where our tests produced duplicate orders and pauses without a saved checkpoint. If you would rather not build that yourself, the Foundry host gives you part of it out of the box.

If you want to automate approval processes or other long-running AI workflows in your company, Pondhouse Data can help, from architecture to production. Talk to us about your workflow.

Frequently asked questions

What is human-in-the-loop in Microsoft Agent Framework?
An executor calls ctx.request_info with a request object and the expected response type. The workflow then emits a request_info event and waits in the IDLE_WITH_PENDING_REQUESTS state. The answer comes back through workflow.run(responses=...) and lands in the method marked with @response_handler.
How do I resume a workflow after a crash?
Rebuild the same graph and call workflow.run(checkpoint_id=..., checkpoint_storage=...). storage.get_latest(workflow_name=...) returns the right checkpoint. If an approval is pending, pass responses as well, and the framework restores and delivers the answer in one call.
Why does something run twice after resuming?
Checkpoints are only written at the end of a superstep. If the process dies in the middle of a step, that whole step runs again on resume. Actions with side effects, such as orders or emails, therefore need their own idempotency key, for example the ticket ID.
Why does saving a checkpoint fail with 'deserialization blocked'?
FileCheckpointStorage serializes your own classes with a restricted pickle and only accepts allowed types. Add your classes as 'module:qualname' to allowed_checkpoint_types or register them with register_checkpoint_type. The run itself does not stop, so check with resolve_pause_checkpoint_id that the pause really was saved.
Can I run a workflow with approvals on Azure AI Foundry?
Yes. The agent-framework-foundry-hosting package serves a workflow as a Foundry Hosted Agent through ResponsesHostServer. The approval shows up as a function_call named request_info, and the answer comes back as a function_call_output. The Foundry Hosted Agents service is generally available; the Python hosting package is still a prerelease.
How much time and storage do checkpoints cost?
In our test with agent-framework-core 1.26.0, a run up to the pause took 1.65 instead of 0.47 milliseconds with FileCheckpointStorage, and each checkpoint was about 2 KB. A restart in a fresh process took about 340 milliseconds, almost all of it Python imports. With a 1 MB document inside the messages, one run grows to 5.3 MB of checkpoints.
Andreas Nigg

About the author

Andreas Nigg

Co-Founder, Pondhouse Data

Andreas has spent more than eight years building data applications. At Pondhouse Data he designs and ships AI systems and integrates them into complex, real-world environments.