mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-08-17 21:25:46 +02:00
Follow-up to #8540, which turned on `PLC0415` (import-outside-top-level) for checkpoint-postgres and checkpoint-sqlite. This does the remaining six packages: checkpoint, checkpoint-conformance, langgraph, prebuilt, cli, sdk-py. Scoped to tests, per @sydney-runkle's call on #8540: library code is exempted with `per-file-ignores`, since it still has deferred imports nobody has reviewed and mixing that in would make this hard to read. ## What changed Function-level imports across 56 test files moved to module level. Nine could not move and carry an explicit `# noqa: PLC0415` with a reason: | File | Why it stays local | |---|---| | `libs/langgraph/tests/test_deprecation.py` (4) | the import has to run inside `pytest.warns` for the warning to be observed | | `libs/langgraph/tests/test_serde_allowlist.py` | try/except guard, skips when langchain_core is absent | | `libs/langgraph/tests/test_delta_channel_benchmark.py` | optional psycopg probe | | `libs/checkpoint/tests/test_conformance_delta.py` (3) | protected by a module-level `pytest.importorskip`; hoisting past the guard turns a skip into a collection error | That last one is the trap: an import moved above `pytest.importorskip` silently defeats the guard. I hit it locally and it turned the skip into a `ModuleNotFoundError` at collection. Every file with an `importorskip` or `except ImportError` was checked by hand for this. ## Verification `make lint` and `make test` in each of the six: | Package | Tests | |---|---| | checkpoint | 156 passed, 17 skipped | | checkpoint-conformance | 1 passed | | langgraph | 1968 passed, 4 skipped | | prebuilt | 284 passed | | cli | 336 passed | | sdk-py | 493 passed | Also confirmed the rule actually fires: a throwaway test file with a function-level import is flagged in all six packages, and the source exemption holds.
345 lines
11 KiB
Python
345 lines
11 KiB
Python
from __future__ import annotations
|
|
|
|
import sys
|
|
from typing import Any
|
|
|
|
import pytest
|
|
from langchain_core.callbacks.base import BaseCallbackHandler
|
|
from langchain_core.callbacks.manager import CallbackManager
|
|
from langgraph.checkpoint.memory import InMemorySaver
|
|
from typing_extensions import TypedDict
|
|
|
|
from langgraph.callbacks import (
|
|
GraphCallbackHandler,
|
|
GraphInterruptEvent,
|
|
GraphResumeEvent,
|
|
_GraphCallbackManager,
|
|
)
|
|
from langgraph.graph import START, StateGraph
|
|
from langgraph.types import Command, Interrupt, interrupt
|
|
|
|
NEEDS_CONTEXTVARS = pytest.mark.skipif(
|
|
sys.version_info < (3, 11),
|
|
reason="Python 3.11+ is required for async contextvars support",
|
|
)
|
|
|
|
|
|
class _GraphEventHandler(GraphCallbackHandler):
|
|
def __init__(self) -> None:
|
|
self.interrupt_events: list[GraphInterruptEvent] = []
|
|
self.resume_events: list[GraphResumeEvent] = []
|
|
|
|
def on_interrupt(self, event: GraphInterruptEvent) -> Any:
|
|
self.interrupt_events.append(event)
|
|
|
|
def on_resume(self, event: GraphResumeEvent) -> Any:
|
|
self.resume_events.append(event)
|
|
|
|
|
|
class _LangChainCustomEventHandler(BaseCallbackHandler):
|
|
run_inline = True
|
|
|
|
def __init__(self) -> None:
|
|
self.events: list[str] = []
|
|
|
|
def on_custom_event(self, name: str, data: Any, **kwargs: Any) -> Any:
|
|
self.events.append(name)
|
|
|
|
|
|
class _RaisingGraphEventHandler(GraphCallbackHandler):
|
|
def __init__(
|
|
self,
|
|
*,
|
|
raise_on_interrupt: bool = False,
|
|
raise_on_resume: bool = False,
|
|
raise_error: bool = False,
|
|
) -> None:
|
|
self.raise_on_interrupt = raise_on_interrupt
|
|
self.raise_on_resume = raise_on_resume
|
|
self.raise_error = raise_error
|
|
|
|
def on_interrupt(self, event: GraphInterruptEvent) -> Any:
|
|
if self.raise_on_interrupt:
|
|
raise ValueError("boom-interrupt")
|
|
|
|
def on_resume(self, event: GraphResumeEvent) -> Any:
|
|
if self.raise_on_resume:
|
|
raise ValueError("boom-resume")
|
|
|
|
|
|
class _AsyncRaisingGraphEventHandler(GraphCallbackHandler):
|
|
def __init__(
|
|
self,
|
|
*,
|
|
raise_on_interrupt: bool = False,
|
|
raise_on_resume: bool = False,
|
|
raise_error: bool = False,
|
|
) -> None:
|
|
self.raise_on_interrupt = raise_on_interrupt
|
|
self.raise_on_resume = raise_on_resume
|
|
self.raise_error = raise_error
|
|
|
|
async def on_interrupt(self, event: GraphInterruptEvent) -> Any:
|
|
if self.raise_on_interrupt:
|
|
raise ValueError("boom-interrupt")
|
|
|
|
async def on_resume(self, event: GraphResumeEvent) -> Any:
|
|
if self.raise_on_resume:
|
|
raise ValueError("boom-resume")
|
|
|
|
|
|
class _State(TypedDict):
|
|
answer: str | None
|
|
|
|
|
|
def _build_interrupt_graph() -> Any:
|
|
def ask(state: _State) -> _State:
|
|
answer = interrupt("Provide value")
|
|
return {"answer": answer}
|
|
|
|
builder = StateGraph(_State)
|
|
builder.add_node("ask", ask)
|
|
builder.add_edge(START, "ask")
|
|
return builder.compile(checkpointer=InMemorySaver())
|
|
|
|
|
|
def test_graph_callbacks_interrupt_and_resume_sync() -> None:
|
|
graph = _build_interrupt_graph()
|
|
handler = _GraphEventHandler()
|
|
langchain_handler = _LangChainCustomEventHandler()
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-sync"},
|
|
"callbacks": [langchain_handler, handler],
|
|
}
|
|
|
|
first = graph.invoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
|
|
assert len(handler.interrupt_events) == 1
|
|
assert handler.interrupt_events[0].interrupts
|
|
assert isinstance(handler.interrupt_events[0].interrupts[0], Interrupt)
|
|
assert handler.interrupt_events[0].checkpoint_ns == ()
|
|
assert langchain_handler.events == []
|
|
|
|
handler.resume_events.clear()
|
|
resumed = graph.invoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
|
|
assert len(handler.resume_events) == 1
|
|
assert handler.resume_events[0].checkpoint_ns == ()
|
|
assert langchain_handler.events == []
|
|
|
|
|
|
@pytest.mark.anyio
|
|
@NEEDS_CONTEXTVARS
|
|
async def test_graph_callbacks_interrupt_and_resume_async() -> None:
|
|
graph = _build_interrupt_graph()
|
|
handler = _GraphEventHandler()
|
|
langchain_handler = _LangChainCustomEventHandler()
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-async"},
|
|
"callbacks": [langchain_handler, handler],
|
|
}
|
|
|
|
first = await graph.ainvoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
|
|
assert len(handler.interrupt_events) == 1
|
|
assert handler.interrupt_events[0].interrupts
|
|
assert isinstance(handler.interrupt_events[0].interrupts[0], Interrupt)
|
|
assert handler.interrupt_events[0].checkpoint_ns == ()
|
|
assert langchain_handler.events == []
|
|
|
|
handler.resume_events.clear()
|
|
resumed = await graph.ainvoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
|
|
assert len(handler.resume_events) == 1
|
|
assert handler.resume_events[0].checkpoint_ns == ()
|
|
assert langchain_handler.events == []
|
|
|
|
|
|
def test_graph_callbacks_continue_when_interrupt_handler_raises_sync() -> None:
|
|
graph = _build_interrupt_graph()
|
|
raising_handler = _RaisingGraphEventHandler(raise_on_interrupt=True)
|
|
recording_handler = _GraphEventHandler()
|
|
|
|
first = graph.invoke(
|
|
{"answer": None},
|
|
{
|
|
"configurable": {"thread_id": "graph-callback-sync-raises"},
|
|
"callbacks": [raising_handler, recording_handler],
|
|
},
|
|
)
|
|
|
|
assert "__interrupt__" in first
|
|
assert len(recording_handler.interrupt_events) == 1
|
|
|
|
|
|
def test_graph_callbacks_continue_when_resume_handler_raises_sync() -> None:
|
|
graph = _build_interrupt_graph()
|
|
raising_handler = _RaisingGraphEventHandler(raise_on_resume=True)
|
|
recording_handler = _GraphEventHandler()
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-sync-raises-resume"},
|
|
"callbacks": [raising_handler, recording_handler],
|
|
}
|
|
|
|
first = graph.invoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
|
|
resumed = graph.invoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
assert len(recording_handler.resume_events) == 1
|
|
|
|
|
|
def test_graph_callbacks_raise_error_propagates_sync() -> None:
|
|
graph = _build_interrupt_graph()
|
|
raising_handler = _RaisingGraphEventHandler(
|
|
raise_on_interrupt=True,
|
|
raise_error=True,
|
|
)
|
|
|
|
with pytest.raises(ValueError, match="boom-interrupt"):
|
|
graph.invoke(
|
|
{"answer": None},
|
|
{
|
|
"configurable": {"thread_id": "graph-callback-sync-raise-error"},
|
|
"callbacks": [raising_handler],
|
|
},
|
|
)
|
|
|
|
|
|
@pytest.mark.anyio
|
|
@NEEDS_CONTEXTVARS
|
|
async def test_graph_callbacks_continue_when_handler_raises_async() -> None:
|
|
graph = _build_interrupt_graph()
|
|
raising_interrupt_handler = _AsyncRaisingGraphEventHandler(raise_on_interrupt=True)
|
|
recording_handler = _GraphEventHandler()
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-async-raises-interrupt"},
|
|
"callbacks": [raising_interrupt_handler, recording_handler],
|
|
}
|
|
|
|
first = await graph.ainvoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
assert len(recording_handler.interrupt_events) == 1
|
|
|
|
graph = _build_interrupt_graph()
|
|
raising_resume_handler = _AsyncRaisingGraphEventHandler(raise_on_resume=True)
|
|
recording_handler = _GraphEventHandler()
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-async-raises-resume"},
|
|
"callbacks": [raising_resume_handler, recording_handler],
|
|
}
|
|
|
|
first = await graph.ainvoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
resumed = await graph.ainvoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
assert len(recording_handler.resume_events) == 1
|
|
|
|
|
|
@pytest.mark.anyio
|
|
@NEEDS_CONTEXTVARS
|
|
async def test_graph_callbacks_raise_error_propagates_async() -> None:
|
|
graph = _build_interrupt_graph()
|
|
raising_handler = _AsyncRaisingGraphEventHandler(
|
|
raise_on_interrupt=True,
|
|
raise_error=True,
|
|
)
|
|
|
|
with pytest.raises(ValueError, match="boom-interrupt"):
|
|
await graph.ainvoke(
|
|
{"answer": None},
|
|
{
|
|
"configurable": {"thread_id": "graph-callback-async-raise-error"},
|
|
"callbacks": [raising_handler],
|
|
},
|
|
)
|
|
|
|
|
|
def test_graph_callbacks_accept_base_callback_manager() -> None:
|
|
graph = _build_interrupt_graph()
|
|
graph_handler = _GraphEventHandler()
|
|
custom_handler = _LangChainCustomEventHandler()
|
|
manager = CallbackManager.configure(inheritable_callbacks=[custom_handler])
|
|
manager.add_handler(graph_handler)
|
|
|
|
first = graph.invoke(
|
|
{"answer": None},
|
|
{
|
|
"configurable": {"thread_id": "graph-callback-base-manager"},
|
|
"callbacks": manager,
|
|
},
|
|
)
|
|
|
|
assert "__interrupt__" in first
|
|
assert len(graph_handler.interrupt_events) == 1
|
|
|
|
|
|
def test_non_graph_handler_via_add_handler_does_not_crash() -> None:
|
|
"""Non-GraphCallbackHandler added via add_handler should not raise.
|
|
|
|
Libraries like opentelemetry-instrumentation-langchain monkey-patch
|
|
BaseCallbackManager.__init__ and inject handlers via add_handler().
|
|
These handlers inherit from BaseCallbackHandler, not
|
|
GraphCallbackHandler. They must be silently accepted — graph lifecycle
|
|
events will simply not be dispatched to them.
|
|
"""
|
|
|
|
manager = _GraphCallbackManager()
|
|
plain_handler = _LangChainCustomEventHandler()
|
|
|
|
manager.add_handler(plain_handler, inherit=True)
|
|
assert plain_handler in manager.handlers
|
|
|
|
|
|
def test_non_graph_handler_does_not_receive_lifecycle_events() -> None:
|
|
"""Non-GraphCallbackHandler added alongside a GraphCallbackHandler
|
|
should not interfere with lifecycle event dispatch."""
|
|
graph = _build_interrupt_graph()
|
|
graph_handler = _GraphEventHandler()
|
|
plain_handler = _LangChainCustomEventHandler()
|
|
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-mixed-handlers"},
|
|
"callbacks": [plain_handler, graph_handler],
|
|
}
|
|
|
|
first = graph.invoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
|
|
assert len(graph_handler.interrupt_events) == 1
|
|
assert plain_handler.events == []
|
|
|
|
resumed = graph.invoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
assert len(graph_handler.resume_events) == 1
|
|
assert plain_handler.events == []
|
|
|
|
|
|
@pytest.mark.anyio
|
|
@NEEDS_CONTEXTVARS
|
|
async def test_non_graph_handler_does_not_receive_lifecycle_events_async() -> None:
|
|
"""Async variant: non-GraphCallbackHandler should not interfere."""
|
|
graph = _build_interrupt_graph()
|
|
graph_handler = _GraphEventHandler()
|
|
plain_handler = _LangChainCustomEventHandler()
|
|
|
|
config = {
|
|
"configurable": {"thread_id": "graph-callback-mixed-handlers-async"},
|
|
"callbacks": [plain_handler, graph_handler],
|
|
}
|
|
|
|
first = await graph.ainvoke({"answer": None}, config)
|
|
assert "__interrupt__" in first
|
|
|
|
assert len(graph_handler.interrupt_events) == 1
|
|
assert plain_handler.events == []
|
|
|
|
resumed = await graph.ainvoke(Command(resume="done"), config)
|
|
assert resumed == {"answer": "done"}
|
|
assert len(graph_handler.resume_events) == 1
|
|
assert plain_handler.events == []
|