Control Flow¶
Scatter¶
Return Scatter([event1, event2, ...]) to fan out into multiple events. Each dispatches separately in the next round. Annotate the return as Scatter[WorkItem], or Scatter[A | B] for heterogeneous targets. It renders as a dashed edge in graph.namespaces().mermaid(). Bare Scatter, Scatter[Any], Scatter[Event] and Scatter[T] (TypeVar) are rejected at graph construction with TypeError.
from langgraph_events import EventLog, IntegrationEvent, Scatter, on
class Batch(IntegrationEvent):
items: tuple[str, ...]
class WorkItem(IntegrationEvent):
item: str
class WorkDone(IntegrationEvent):
result: str
class BatchResult(IntegrationEvent):
results: tuple[str, ...]
@on(Batch)
def split(event: Batch) -> Scatter[WorkItem]:
return Scatter([WorkItem(item=i) for i in event.items])
@on(WorkItem)
def process(event: WorkItem) -> WorkDone:
return WorkDone(result=f"done:{event.item}")
@on(WorkDone)
def gather(event: WorkDone, log: EventLog) -> BatchResult | None:
all_done = log.filter(WorkDone)
batch = log.latest(Batch)
if len(all_done) >= len(batch.items):
return BatchResult(results=tuple(e.result for e in all_done))
return None
See the Map-Reduce pattern.
Invariants¶
Declare invariants={InvariantClass: predicate, ...} as a class-level attribute on a Command, or via invariants= on @on() for an external handler. Each predicate runs twice per matching event:
| Phase | Timing | Log scope | On failure |
|---|---|---|---|
| Pre-check | Before handler body | Committed events | Skip handler, emit InvariantViolated (would_emit empty) |
| Post-check | After handler returns | Committed + buffered by the current node call | Drop emissions, emit InvariantViolated (would_emit = handler's events) |
from __future__ import annotations
from langgraph_events import Command, DomainEvent, IntegrationEvent, Invariant
from langgraph_events import InvariantViolated, Namespace, on
class CustomerBanned(IntegrationEvent):
customer_id: str = ""
class CustomerNotBanned(Invariant):
"""Customer must not be on the banned list.""" # pre-check catches
class OrderTotalWithinLimit(Invariant):
"""Cumulative placed amount must stay under a daily limit.""" # post-check catches
class Order(Namespace):
class Place(Command):
customer_id: str = ""
amount: int = 0
invariants = {
CustomerNotBanned: lambda log: not log.has(CustomerBanned),
OrderTotalWithinLimit: lambda log: (
sum(e.amount for e in log.filter(Order.Place.Placed)) < 100
),
}
class Placed(DomainEvent):
order_id: str = ""
amount: int = 0
def handle(self) -> Order.Place.Placed:
return Order.Place.Placed(
order_id=f"o-{self.customer_id}", amount=self.amount
)
class Rejected(DomainEvent):
"""Sibling to ``Place``, emitted by a recovery handler."""
reason: str = ""
@on(InvariantViolated, invariant=OrderTotalWithinLimit)
def rolled_back(event: InvariantViolated) -> Order.Rejected:
rolled = event.would_emit[0] # the Placed the handler would have emitted
return Order.Rejected(reason=f"over limit (would emit {rolled.amount})")
- Subclass
Invariantonce per rule. Reference the class on the declaration side and on the handler side.Invariantsubclasses must be zero-arg instantiable. The library callsCls()at emission time forisinstancematching. - Catch all:
@on(InvariantViolated). Pin to a class:@on(InvariantViolated, invariant=SomeInvariant). A pinned class that no declaration names raisesTypeErrorat graph construction ("would never fire"). A pinned handler fires for both pre-check and post-check failures. Inspectevent.would_emitto tell them apart. - A recovery handler emits a namespace-level event. Command-private outcomes are reserved for the inline command handler.
- A predicate receives
EventLog. It must be sync and a pure function oflog. An async predicate raisesTypeErrorat@ondecoration, or at graph construction for aCommandattribute. Predicate exceptions propagate. They are not converted to violations. - Multiple invariants short-circuit. One
InvariantViolatedper phase. - Invariants run around
raises=. The pre-check gates the body entirely. The post-check is skipped on a caught exception, which emitsHandlerRaisedinstead. Post-check is a no-op when the handler returnedNoneor declares no invariants.
Modeling errors¶
| Situation | Vehicle |
|---|---|
| Expected domain outcome (including failure) | DomainEvent (Order.Place.Rejected) |
| Consistency rule gating a command (pre and/or post) | invariants= → InvariantViolated |
| Infrastructure failure (rate limit, timeout, parse error) | Exception + raises= → HandlerRaised |
Warnings from graph.namespaces()¶
The first graph.namespaces() call emits two warnings that flag structural smells. graph.reflect() and a Reflection injected into a handler build the same model, so they emit them too. When the structure is intentional, filter with warnings.filterwarnings("ignore", category=...).
CommandChainWarning: achain-causation edge, an inline command handler that returns anotherCommand. Prefer to emit a fact and react to it.DomainPatternWarning: two or more events in the same namespace fan out to identical target sets. A shared base or a common handler is missing.
Interrupted / Resumed¶
Subclass Interrupted with typed fields to pause for human input. Resume with graph.resume(event), which requires a checkpointer. A Resumed event emits alongside the dispatched event.
from langgraph.checkpoint.memory import MemorySaver
from langgraph_events import EventGraph, EventLog, IntegrationEvent, Interrupted, on
class OrderPlaced(IntegrationEvent):
order_id: str
total: float
class OrderConfirmed(IntegrationEvent):
order_id: str
class OrderCancelled(IntegrationEvent):
reason: str
class OrderConfirmationRequested(Interrupted):
order_id: str
total: float
class ApprovalSubmitted(IntegrationEvent):
approved: bool
@on(OrderPlaced)
def confirm(event: OrderPlaced) -> OrderConfirmationRequested:
return OrderConfirmationRequested(order_id=event.order_id, total=event.total)
@on(ApprovalSubmitted)
def handle_approval(event: ApprovalSubmitted, log: EventLog) -> OrderConfirmed | OrderCancelled:
request = log.latest(OrderConfirmationRequested)
if event.approved:
return OrderConfirmed(order_id=request.order_id)
return OrderCancelled(reason="User declined")
graph = EventGraph([confirm, handle_approval], checkpointer=MemorySaver())
config = {"configurable": {"thread_id": "order-1"}}
graph.invoke(OrderPlaced(order_id="A1", total=99.99), config=config)
state = graph.get_state(config)
if state.is_interrupted:
print(f"Approve {state.interrupted.order_id} for ${state.interrupted.total}?")
log = graph.resume(ApprovalSubmitted(approved=True), config=config)
The resume value must be an Event. Another value raises TypeError before the graph runs, so the thread stays paused and a later resume() can answer it. A handler that pauses two times in one run is resumed two times. After the first resume, the thread is paused again and get_state(config).is_interrupted is True. Under the default on_unresumable="raise", resume() raises UnresumableError only when no registered handler waits for an answer.
Answers by interrupt id¶
When two handlers pause in parallel, one resume can answer both. Pass a mapping of LangGraph interrupt ids to answers to resume(), aresume(), stream_resume() or astream_resume(). Read the ids from graph.compiled.get_state(config).interrupts:
...
snapshot = graph.compiled.get_state(config)
ids = {type(i.value): i.id for i in snapshot.interrupts}
graph.resume(
{
ids[OrderConfirmationRequested]: ApprovalSubmitted(approved=True),
ids[AddressRequested]: Dismissed(interrupted=snapshot.interrupts[1].value),
},
config=config,
)
- An open interrupt that the mapping does not name stays open. The run stores the answers that it got, and the thread stays paused. The handlers of those answers run when a resume answers the last open interrupt of the round.
- A key that names no open interrupt raises
ValueErrorbefore the graph runs. The thread keeps every question. - An empty mapping, or a value that is not an
Event, raisesTypeError. - A single
Eventstill answers a thread with one open interrupt. With more than one open interrupt, LangGraph refuses it withRuntimeError.
Dismissed(interrupted=...) is the answer to a question that a person dismissed without an answer. The run dispatches it like any answer. Subscribe with @on(Dismissed, interrupted=AddressRequested) to react to one question. Unlike abandon(), it closes one question and the thread goes on.
For an interrupt whose frontend needs an action-discriminated dict, subclass langgraph_events.agui.InterruptedWithPayload[PayloadT]. See Typed Interrupt Payloads.
See the approval pattern and What changes safely.
Ending a pause without answering it — abandon()¶
graph.event_store.abandon(config, reason=...) or aabandon() ends the pause without answering it. graph.event_store requires a checkpointer. abandon() settles one thread per call. Find the paused threads with graph.event_store.threads_paused_on(EventClass, thread_ids=...) or athreads_paused_on():
...
# candidates: thread ids from a server-side query.
paused = graph.event_store.threads_paused_on(OrderConfirmationRequested, thread_ids=candidates)
for config in paused:
graph.event_store.abandon(config, reason="retiring OrderConfirmationRequested")
thread_ids= is required. The library does not read the whole store. See Finding candidates server-side. Omit the class to get every listed thread that is paused. To check one thread, pass thread_ids=[tid].
abandon() never dispatches the interrupt, and the interrupt never joins the event log. That is why it retires an Interrupted subclass: resuming every paused thread first would append the identity you are deleting. It appends a terminal Abandoned event, a Halted subtype. It leaves nothing scheduled. It preserves the writes of any completed sibling handler from the same fanned-out superstep. Abandoned is recorded, not dispatched. .discarded holds the qualnames of the discarded interrupts, joined with ", ". It settles the latest checkpoint only. A historic checkpoint of the thread keeps its own __interrupt__ write, so a replay against it still sees the pause. For a class that is already deleted, and for the threads that already answered the interrupt, see Retiring an Interrupted subclass.
WARNING: A release older than 0.29.0 cannot read an Abandoned event. A deployment rolled back below 0.29.0 raises Cannot revive on every read of an abandoned thread. Before you call abandon() in production, confirm that the previous production image also runs 0.29.0 or later.
WARNING: A run that is running on the thread overwrites what abandon() did, or the reverse, depending on ordering. Call abandon() only on a thread that is that no run uses.
abandon() raises ValueError if the thread has no events to settle (never run, or only pre_seed()ed), or if the thread has no pending interrupt, naming the thread. Pass require_interrupt=False to settle such a thread anyway. It records Abandoned(discarded="").
abandon() does not consult on_unresumable. That setting governs an accidental no-op resume(), not a deliberate abandonment. A later resume() on an abandoned thread still raises UnresumableError under the default setting, naming the abandonment.
Soft-timeout — RunPaused¶
Pass deadline=time.monotonic() + budget to any graph entry point (invoke, ainvoke, astream_events, stream_events, resume, aresume, astream_resume, stream_resume, or AGUIAdapter.stream). When the router observes a wall-clock time past the deadline between dispatch rounds, it emits a RunPausedOnDeadline(elapsed_seconds=…) and the run terminates cleanly.
RunPaused is the base class of every pause. It names no cause, so RunPaused(...) raises TypeError. RunPausedOnDeadline is the deadline pause. RunPausedOnSignal is the signal pause. Match RunPaused to see every pause, or match a subclass to see one cause.
...
from time import monotonic
log = graph.invoke(Started(data="job-42"), deadline=monotonic() + 25.0)
if log.latest(RunPaused):
# Paused. The next `invoke()` or stream call on the same `thread_id`
# continues from the LangGraph checkpoint, the same mechanism as a
# normal follow-up turn. No Command(resume=...) is needed.
...
Unlike MaxRoundsExceeded, RunPaused is not terminal across runs. The router advances the cursor past it, so the next call excludes the old RunPaused from new_events. Unlike Interrupted, which writes a pending interrupt task that resume() answers with Command(resume=value), RunPaused writes no checkpoint task. The caller makes the next call with the same thread_id and a fresh deadline, and LangGraph replays from the last completed node.
Rules, shared with the signal pause:
- Set
deadlinestrictly tighter than any hard cancellation the caller already has, such asasyncio.wait_foror LangGraph'stimeout=, so that the pause fires first. - Events emitted in the paused round are persisted in the event log but not dispatched, the same drop-on-pause semantic as
MaxRoundsExceeded. Write handlers so that a stop at a round boundary leaves recoverable state. - The first round of a run always dispatches, also with
deadline=0.0. The resume round always dispatches: the router dispatches the resume value before it checks the deadline or the signal, so a pause does not lose the answer. RunPausedis emitted at most once per run, even when many parallel handlers are that is running when the deadline fires. A downstream projection can rely on one entry per pause.- The check happens only between rounds, never inside a handler, so a handler that blocks cannot be preempted. The one exception is a
RetryPolicybackoff, which reads the deadline and the signal before every wait and gives up instead of sleeping past them.
RunPaused has no default AG-UI wire mapping. See Deadline and signal pauses.
Pause on a signal — RunPausedOnSignal¶
A deadline is fixed when the run starts. To stop a live run early, pass pause_on= to the same entry points. The value is an object with an is_set() method, for example an asyncio.Event or a threading.Event. The PauseSignal protocol states this contract. The router calls is_set() between dispatch rounds. When it returns True, the router emits RunPausedOnSignal(elapsed_seconds=…) and the run ends cleanly.
...
import asyncio
stopping = asyncio.Event()
log = await graph.ainvoke(seed, config=config, pause_on=stopping)
# At shutdown, the process sets the event. Each live run stops at its next round boundary.
stopping.set()
RunPausedOnSignalis a subclass ofRunPaused. Code that matchesRunPausedalso matches a signal pause. MatchRunPausedOnSignalto tell the two causes apart.- When the deadline has also expired, the router emits
RunPausedOnSignal, notRunPausedOnDeadline. elapsed_secondscounts from the start of the run, also when the run has no deadline.- The handler calls of the current round finish first. Give the run an outer grace period that is longer than one round.
- The value must be an instance with a callable
is_set. Otherwise the entry point raisesTypeErrorbefore any round runs. The common mistakes arepause_on=stopping.is_setandpause_on=asyncio.Event, the class. Pass the event itself. A type checker also rejects these values, because each entry point declarespause_on: PauseSignal | None. - A
RetryPolicybackoff reads the signal before every wait and gives up with aHandlerAbandonedOnSignal, which reaches no handler. See Retries. Three rules apply to that give-up:- The router pauses over it instead of dispatching it. Two cases end the run without a
RunPausedOnSignal, and the router still does not dispatch the give-up. A sibling handler interrupts in the same round: the run ends at the interrupt, the resume round dispatches the resume value and skips the give-up, and the resumed run reads its ownpause_on=. The give-up lands in the last round thatmax_roundsallows: the run halts withMaxRoundsExceeded. - The first set read commits the run to a pause, also when the caller clears the signal between the two reads.
- A backoff wait that is already in progress when the signal is set runs to its end, and
max_delaybounds it. The policy gives up before the next wait.
- The router pauses over it instead of dispatching it. Two cases end the run without a
Stop on a signal — CancelledOnSignal¶
A pause waits for the current round to finish. A stop is immediate. To end a run at once, for example when a user stops it, pass stop_on= to ainvoke(), aresume(), astream_events(), astream_resume() or AGUIAdapter.stream(). The value follows the same PauseSignal contract as pause_on=. When is_set() returns True, the library cancels each running async handler, and the run ends on CancelledOnSignal.
stopping = asyncio.Event()
log = await graph.ainvoke(seed, config=config, stop_on=stopping)
# When the user stops the run, the request handler sets the event.
stopping.set()
- The cancel goes to the handler step only, never to the run task. The checkpoint write is never cancelled.
- After the first cancel, the handler has a grace period of 1 second to clean up. After the grace period, the cancel repeats every 0.05 seconds until the handler ends.
- WARNING: a cleanup that takes longer than 1 second is cancelled again. To keep a longer cleanup, run it under
asyncio.shield(). - With
stop_on=given, a cancel of the run task also gets the grace period and the repeated cancels. The run then stores a plainCancelled. - The step of a stopped handler discards all the events of that handler. A sync handler is not interrupted, but its step also discards its events.
CancelledOnSignal.discardednames each handler whose step the stop cut, joined with", ". It is""when the signal was set after the last handler step.- When a sibling handler interrupts in the same round, the interrupt wins. The thread stores the question and no
CancelledOnSignal. The resume stores oneHandlerCutOnSignalfor each cut handler, then dispatches the answer. No handler runs onHandlerCutOnSignal, and no laterCancelledOnSignal.discardednames its handler. - A stream (
astream_resume(),stream_resume(),AGUIAdapter.stream()) does not yieldHandlerCutOnSignal, because the resume command writes it. Only the stored log shows it. - A stop can come before a resume applies its answers.
aresume()andastream_resume()then raiseResumeStoppedError. The two cases are:- The signal is already set at the call. The resume runs nothing.
- The signal is set while the resume replays a paused handler. The replay is cut, and its step fails, so LangGraph commits no checkpoint for it.
- After
ResumeStoppedError, each cut question stays open with the same interrupt id, and its answer is not stored. Resume again to answer it. This holds for the durability"sync"(the default),"async"and"exit". - Each question is applied whole or not at all. When a resume answers several questions, a replay that ended before the stop keeps its answer. Only the cut questions stay open.
- The
seeds=ofastream_resume()andstream_resume()ride in the answer. The paused handler stores them, before the answer, when it applies the answer. So a resume thatResumeStoppedErrorstops stores no seed, also after several stopped resumes in a row. A handler that pauses again in the resume stores the seeds of each resume when it finishes. - A paused handler that called
langgraph.types.interrupt()in its body receives the resume value as it is, so it cannot take seeds. A resume withseeds=raisesValueErrorbefore the run when each answered interrupt comes from such a call. lge reads this from the paused handler: an interrupt is returned when the handler declares its class, or declares no return type, and the code of the handler does not namelanggraph.types.interrupt. A call tointerrupt()in a helper function that the handler calls is not seen. Such a handler receives the internal carrier of the seeds, and the seeds are lost. Do not callinterrupt()from a helper of a handler that gets client state. - A resume with
seeds=that answers no open interrupt raisesValueErrorbefore the run. A thread that is not paused gets theon_unresumablepolicy first. - The
HandlerCutOnSignalrecords stay afterResumeStoppedError. Each one states a fact of the paused round, no handler runs on it, and a later resume does not store it again. - The resume of
AGUIAdapter.stream()does not raise. It ends onRUN_FINISHEDwithRunFinishedCancelledOutcome, and the thread stays paused. See Run outcomes. - A stop set after the replay commits ends the run as any stop does, with
CancelledOnSignal. abandon()on a thread paused after a cut stores noHandlerCutOnSignal. The next run clears the name of the cut handler.- The cursor moves past
CancelledOnSignal, so a new run on the samethread_idcontinues.
The router reads the signal between rounds, before it checks max_rounds:
- When the signal is set, the router stores
CancelledOnSignal, also when no step discarded events. The events already stored stay, and no handler gets them. - When the round already stores a
Halted, for example theCancelledof a cancelled run task, the router stores noCancelledOnSignal. - When the signal is set after the last read of the router, the run ends normally.
- The first set read commits the run to the stop, also when the caller clears the signal later.
Surfacing the pause inline¶
To turn a RunPaused into a user-visible system message in the same channel as the chat history, register a custom reducer that handles both MessageEvent and RunPaused:
from langchain_core.messages import BaseMessage, SystemMessage
from langgraph.graph.message import add_messages
from langgraph_events import Event, MessageEvent, Reducer, RunPaused
def project(event: Event) -> list[BaseMessage]:
if isinstance(event, MessageEvent):
return event.as_messages()
if isinstance(event, RunPaused):
return [SystemMessage(
id=f"sys-paused-{event.elapsed_seconds:.6f}",
content=f"Paused after {round(event.elapsed_seconds)}s. "
f"Send a follow-up to continue.",
)]
return []
messages = Reducer[MessageEvent | RunPaused, BaseMessage](
name="messages",
event_type=(MessageEvent, RunPaused),
fn=project,
reducer=add_messages,
)
Field Matchers¶
@on(Event, field=Type) dispatches only when event.field is a Type instance. When the handler signature includes a parameter named field, the value is injected:
...
@on(Resumed, interrupted=OrderConfirmationRequested)
def handle(event: Resumed, interrupted: OrderConfirmationRequested) -> OrderConfirmed:
# `interrupted` is guaranteed to be OrderConfirmationRequested.
...
- A matcher value is an
Event,ExceptionorInvariantsubclass, matched byisinstance, or astr, matched by equality. - Field names are validated at graph construction. A typo raises
TypeError. - Omit the parameter to filter dispatch without injection.
Handler Exceptions¶
Declare raises=(ExceptionClass, ...) on a Command, or via raises= on @on(...). A caught exception emits HandlerRaised with the exception, the handler name and source_event. Subscribe with @on(HandlerRaised, exception=…) to react.
...
class RateLimitError(Exception):
def __init__(self, retry_after: float) -> None:
super().__init__(f"retry after {retry_after}s")
self.retry_after = retry_after
class Question(Namespace):
class Ask(Command):
question: str = ""
raises = (RateLimitError,)
class Answered(DomainEvent):
answer: str = ""
def handle(self) -> Question.Ask.Answered:
if upstream_rate_limited():
# Honored only under respect_retry_after=True; decorative here.
raise RateLimitError(retry_after=0.2)
return Question.Ask.Answered(answer=...)
class RetriesExhausted(Halted):
reason: str = ""
@on(HandlerRaised, exception=RateLimitError)
def backoff(event: HandlerRaised, exception: RateLimitError) -> Question.Ask:
return Question.Ask(question=event.source_event.question) # retry
- Every type in
raises=must be covered by at least one handler, or graph construction fails withTypeError. A handler coversXwhen it has no field matchers, or onlyexception=Xor a superclass. A non-exceptionmatcher does not count. A handler counts only when it subscribes toHandlerRaiseditself, not to a subtype such asHandlerAbandonedOnSignal. - Only
Exceptionsubclasses are allowed.BaseException,KeyboardInterrupt,SystemExit,GeneratorExitandasyncio.CancelledErrorare rejected.CancelledErrorsurfaces asCancelled, aHaltedsubtype. - An unhandled raise propagates and crashes the run. A handler of
HandlerRaisedcan itself declareraises=to escalate. - Use
HandlerRaised.source_event, notevent, for the triggering event. This avoids a kwarg collision.
Retries¶
Declare retry=RetryPolicy(...) alongside raises=, as a class attribute on a Command or via retry= on @on(...). The library calls the handler again in place with exponential backoff. HandlerRaised fires only when the budget is spent, or when the run's deadline= or pause_on= cuts the backoff short. So a handler of HandlerRaised is an escalation handler.
...
from langgraph_events import RetryPolicy
class Question(Namespace):
class Ask(Command):
... # the fields, `raises` and the handler, as above
retry = RetryPolicy(max_attempts=3, base_delay=0.1, max_delay=10.0)
@on(HandlerRaised, exception=RateLimitError)
def give_up(event: HandlerRaised) -> Question.RetriesExhausted:
return Question.RetriesExhausted(reason=str(event.exception)) # budget spent, or out of time
max_attemptscounts the initial call:3means one call plus two retries.- Delay before retry n is
base_delay * 2 ** (n - 1), capped atmax_delay.strategy="constant"usesbase_delayas that ceiling on every retry. jitter=True(the default) samples the wait uniformly from[0, ceiling], whatever the strategy. Sostrategy="constant", jitter=Truestill varies per retry, averagingbase_delay / 2. Passjitter=Falsefor a flat wait.on=(...)narrows which exceptions retry. Each entry must overlapraises=: a subclass of a declared raise (raises=(OSError,),on=(ConnectionResetError,)) or a superclass of one (raises=(ConnectionResetError,),on=(OSError,)). Scope is decided at runtime byisinstance(exc, on). Anything declared inraises=but outsideon=surfaces on its first raise.respect_retry_after=Trueprefers a server-suppliedexception.retry_afterover the computed curve, clamped to[0, max_delay]and never jittered. A non-numeric orboolhint is ignored.- Each wait emits a
HandlerRetried(handler,source_event, exception,attempt,delay_seconds).observe="log"records aWARNINGwith the exception's type and message instead, andobserve="silent"records neither. Onlyobserve="emit"(the default) writes the event to the log, so only it contributes theretryedge toHandlerRetriedingraph.namespaces(). Theretry xNannotation on the command shows under every setting. - Declaring
retry=withoutraises=, or anon=entry disjoint from every type inraises=, fails at graph construction withTypeError. - Retries happen inside the handler node. They consume no
max_roundsbudget and write no checkpoint between attempts. - A sleep is never started when it would land on or past the run's
deadline=. The policy gives up at that point, even with attempts left. Nothing is clamped. An attempt that cannot finish before the deadline only delays the pause. A setpause_on=signal gives up the same way. See Pause on a signal. - A deadline give-up is a
HandlerAbandonedOnDeadline. It is aHandlerAbandoned, which is aHandlerRaised, so an@on(HandlerRaised, exception=X)handler runs for it. An exhausted attempt budget, an out-of-on=exception and a handler with no policy each emit a plainHandlerRaised. Useisinstance(event, HandlerAbandonedOnDeadline)to tell "ran out of time" from "ran out of tries".HandlerAbandonednames no cause, soHandlerAbandoned(...)raisesTypeError. The abandoned attempt emits noHandlerRetried, because no wait happened. - Handlers must be idempotent. A retried handler re-runs from the top, including any
emit_customit fired before raising. HandlerRetriedcarries the exception without its traceback. Matchers and field injection work on the live instance, but__traceback__is detached. The terminalHandlerRaisedkeeps its own. For a per-attempt stack, capture it inside the handler while the frames are still live.- Not to be confused with
langgraph.types.RetryPolicy, which re-runs an entire LangGraph node. Import this one fromlanggraph_events.
See the Error Recovery pattern.