From 9cf81664fde2ab515c62fedfc0fb9c2689b6617b Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:22:22 +0100 Subject: [PATCH 01/13] Agents: a LangGraph run whose last step's writes are stored but not its checkpoint goes on from them --- python/restate/agents/langgraph/_graph.py | 5 +- python/restate/agents/langgraph/nodes.py | 2 +- tests/agents_langgraph_crash.py | 152 ++++++++++++++++++++++ 3 files changed, 157 insertions(+), 2 deletions(-) create mode 100644 tests/agents_langgraph_crash.py diff --git a/python/restate/agents/langgraph/_graph.py b/python/restate/agents/langgraph/_graph.py index 8047b940..0c6492e0 100644 --- a/python/restate/agents/langgraph/_graph.py +++ b/python/restate/agents/langgraph/_graph.py @@ -476,7 +476,10 @@ async def _run(conversation: Conversation) -> str: # Inherited by the nodes' own runs: the models they call keep the attempt alive while they request. "callbacks": [alive], } - if asked and not snapshot.next: + # ``next`` leaves out the tasks whose writes are stored, so a step whose writes were stored before its + # checkpoint (a crash between them) has no ``next`` but still has tasks: that run goes on, from those writes, + # without running the tasks again. A finished run has no tasks. + if asked and not snapshot.tasks: # The run had finished, but its answer was not stored: that is the answer, rather than run again. await _copied(ctx, turn, known, messages, prompt_id) await saver.aprune([THREAD_ID]) diff --git a/python/restate/agents/langgraph/nodes.py b/python/restate/agents/langgraph/nodes.py index bd099611..e31ca5ab 100644 --- a/python/restate/agents/langgraph/nodes.py +++ b/python/restate/agents/langgraph/nodes.py @@ -36,7 +36,7 @@ async def refund(ctx: sessions.SessionContext, refund: Refund) -> State: app: Any = graph.compile(checkpointer=SqlCheckpointSaver(ctx.db)) # Any: LangGraph types no Restate context config: RunnableConfig = {"configurable": {"thread_id": "refunds"}} - resuming = (await app.aget_state(config)).next + resuming = (await app.aget_state(config)).tasks return await app.ainvoke(None if resuming else {"refund": refund}, config, context=ctx, durability="sync") Each node does its step once. A crash re-runs a node from the checkpoint it diff --git a/tests/agents_langgraph_crash.py b/tests/agents_langgraph_crash.py new file mode 100644 index 00000000..0ff413d4 --- /dev/null +++ b/tests/agents_langgraph_crash.py @@ -0,0 +1,152 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A graph of your own through crashes (``langgraph.prompt(ctx, text, graph=...)``): a transfer moves money once, and +the prompt is answered once, wherever the attempt crashes. In process: a crash is a sync of the object's state that +fails, with the writes it had not yet stored lost.""" + +# pylint: disable=missing-function-docstring,missing-class-docstring + +import collections +from typing import Annotated, Any + +import pytest + +pytest.importorskip("langgraph") + +from langchain_core.messages import AIMessage, HumanMessage, ToolMessage # noqa: E402 +from langchain_core.tools import InjectedToolCallId, tool # noqa: E402 +from langgraph.graph import END, START, MessagesState, StateGraph # noqa: E402 +from langgraph.prebuilt import ToolNode, tools_condition # noqa: E402 + +from restate import sessions # noqa: E402 +from restate.agents import langgraph # noqa: E402 +from restate.agents.langgraph import SqlCheckpointSaver # noqa: E402 +from sessions_database import Backend # noqa: E402 # pylint: disable=import-error +from sessions_object import Host, request # noqa: E402 # pylint: disable=import-error +from restate.sessions.internal import invoke # noqa: E402 + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +pytestmark = [pytest.mark.anyio] + +moved: collections.Counter[str] = collections.Counter() +"""The transfers made, by the call that asked for each: a transfer is made once per call, as a journaled effect is.""" + + +@tool +def transfer(to: str, tool_call_id: Annotated[str, InjectedToolCallId]) -> str: + """Move 10 to an account.""" + moved[tool_call_id] += 1 + return f"moved 10 to {to}" + + +def teller(state: MessagesState) -> dict[str, Any]: + """The scripted model: it asks for a transfer, and once it has its result, answers.""" + messages = state["messages"] + asked = next(m for m in reversed(messages) if isinstance(m, HumanMessage)) + after = messages[messages.index(asked) + 1 :] + if any(isinstance(m, ToolMessage) for m in after): + return {"messages": [AIMessage("all done")]} + call = {"id": f"call-{asked.id}", "name": "transfer", "args": {"to": "bob"}} + return {"messages": [AIMessage("", tool_calls=[call])]} + + +def banking() -> StateGraph: + """A graph of a model and a node of tools, as LangChain's ``create_agent`` builds.""" + graph = StateGraph(MessagesState) + graph.add_node("model", teller) + graph.add_node("tools", ToolNode([transfer])) + graph.add_edge(START, "model") + graph.add_conditional_edges("model", tools_condition, {"tools": "tools", END: END}) + graph.add_edge("tools", "model") + return graph + + +def desk(graph: StateGraph, name: str = "asker") -> sessions.SessionObject: + obj = sessions.SessionObject(name) + + @obj.handler + async def ask(ctx: sessions.SessionContext, text: str) -> str: + return await langgraph.prompt(ctx, text, graph=graph) + + return obj + + +async def test_a_graph_answers_a_prompt_once_after_a_crash_at_any_of_its_syncs(): + obj = desk(banking()) + crashed = 0 + for syncs in range(200): + moved.clear() + backend, invocation = Backend(), request() + crashing = Host(backend, service="asker") + crashing.crash_after(syncs) + try: + assert await invoke(obj, "ask", crashing, invocation, "pay bob") == "all done" + break + except RuntimeError as error: + assert str(error) == "the sync failed" + crashed += 1 + answer = await invoke(obj, "ask", Host(backend, service="asker"), invocation, "pay bob") + # One call, one transfer: a tool that a crash cut off runs again with the same call id (Restate's journal + # answers it), but no second call is made. + assert (syncs, answer, len(moved)) == (syncs, "all done", 1) + assert crashed > 0 + + +async def test_a_run_whose_last_steps_writes_are_stored_but_not_its_checkpoint_goes_on_from_them(): + """The state of a crash between a step's writes and its checkpoint: the task's writes are stored (here in place of + the error it stored), and no checkpoint follows them.""" + ran: list[str] = [] + crash = [True] + + def node(name: str) -> Any: + def step(state: MessagesState) -> dict[str, Any]: + ran.append(name) + if name == "second" and crash[0]: + crash[0] = False + raise RuntimeError("the process died") + return {"messages": [AIMessage(f"{name} done")]} + + return step + + graph = StateGraph(MessagesState) + for name in ("first", "second", "third"): + graph.add_node(name, node(name)) + graph.add_edge(START, "first") + graph.add_edge("first", "second") + graph.add_edge("second", "third") + graph.add_edge("third", END) + obj = desk(graph) + + @obj.handler + async def seed(ctx: sessions.SessionContext) -> list[str]: + saver = SqlCheckpointSaver(ctx.db) + snapshot = await graph.compile(checkpointer=saver).aget_state({"configurable": {"thread_id": "chat"}}) + assert [task.name for task in snapshot.tasks] == ["second"] + await ctx.db.execute("DELETE FROM restate_langgraph_writes WHERE channel = '__error__'") + # What a node's task writes: its update, and the trigger of the node that follows. + writes: list[tuple[str, Any]] = [ + ("messages", [AIMessage("second done", id="second_done")]), + ("branch:to:third", None), + ] + await saver.aput_writes(snapshot.config, writes, snapshot.tasks[0].id) + return [task.name for task in snapshot.tasks] + + backend, invocation = Backend(), request() + with pytest.raises(RuntimeError, match="the process died"): + await invoke(obj, "ask", Host(backend, service="asker"), invocation, "go") + await invoke(obj, "seed", Host(backend, service="asker"), request()) + assert await invoke(obj, "ask", Host(backend, service="asker"), invocation, "go") == "third done" + assert ran == ["first", "second", "third"] From f5871dc935008300c0e1e2786a9a3069fcdf393c Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:24:36 +0100 Subject: [PATCH 02/13] Shared core 8.7.3: SQL calls run where they are polled, sessions share compiled statements Also 8.7.2: a transaction that changed the schema drops the kept statements when it ends. --- Cargo.lock | 4 ++-- Cargo.toml | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 602672d0..be353809 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2490,9 +2490,9 @@ dependencies = [ [[package]] name = "restate-sdk-shared-core" -version = "8.7.1" +version = "8.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed583844d652c40185869483ef35370c5780ff15f0bb8e2adf2f5c25a494aefc" +checksum = "f426f433f7697026c2ae27d22c086e11a00d8f79d1fbe22e108d15e4b3360b05" dependencies = [ "base64 0.22.1", "bs58", diff --git a/Cargo.toml b/Cargo.toml index a84f7da4..afa8cde7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,7 +22,9 @@ tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] } # directory); `tunnel` is Restate Cloud's. `aws_lc_rs` is the crypto of all of them (the # tunnel's TLS, request identity's signatures), as the object stores' must be aws-lc. # 8.7.1: a cancellation resumes an invocation shut down while it waits for a call (sdk-shared-core#120). -restate-sdk-shared-core = { version = "8.7.1", features = [ +# 8.7.3: SQL calls run where they are polled; compiled statements are shared between the sessions of one +# schema (sdk-shared-core#121, #123). +restate-sdk-shared-core = { version = "8.7.3", features = [ "request_identity", "sha2_random_seed", "aws_lc_rs", From 0ab779a1c26e8d8dfd95bc29d2eb29c0bc75f51e Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:26:28 +0100 Subject: [PATCH 03/13] Agents: the calls of an invocation's prompts are kept apart --- docs/agents/conversation.md | 8 +++- python/restate/agents/_calls.py | 53 ++++++++++++++++++++++---- python/restate/agents/_conversation.py | 6 +-- tests/agents_conversation.py | 41 ++++++++++++++++++++ tests/agents_tools.py | 50 ++++++++++++++++++++++++ 5 files changed, 147 insertions(+), 11 deletions(-) diff --git a/docs/agents/conversation.md b/docs/agents/conversation.md index 4d959e84..4cc12e23 100644 --- a/docs/agents/conversation.md +++ b/docs/agents/conversation.md @@ -525,6 +525,7 @@ invocation (the next invocation's first call replaces it): | `attempt` | the attempt that last made it | | `done`, `failed` | whether the Restate call returned, and the terminal error it returned, if any | | `approval` | the call is an approval that its tool call waited for (`wait_for(..., approval=True)`) | +| `prompt` | the prompt whose turn made the call; absent for a call made outside a prompt, and in a row an earlier version stored | - **Matching a call.** A tool call finds the record it made before by its id and its tool: one tool call may make two calls (an approval, then the @@ -533,6 +534,10 @@ invocation (the next invocation's first call replaces it): input: a framework that tells the model its call was cut off gets the call again under a new id, and that is the same Restate call, with the same idempotency key, which it waits for again or whose result it gets. +- **Per prompt.** An invocation can prompt more than once (``, `:2`, ...). `answer_once` keeps the + calls its run makes as its prompt's, and a call is matched, and rejoined, among its prompt's records only: a + second prompt that makes the call the first made (the same tool and input) takes a call of its own, not the + first's, which a crash left stored. - **A framework's own wait is its tool call's alone** (`wait_for`). The framework stored the tool call before it waits, so a retried attempt waits again under the same id; a new call with the same input (the model asking @@ -550,7 +555,8 @@ invocation (the next invocation's first call replaces it): - **Closing a turn.** A turn that closes with open calls gives each a result: the error its Restate call returned, or `RETURNED_UNRECORDED` ("Done, but the turn was stopped before this call's result was recorded: it did - happen…") if it returned, or else the note that closes the turn. The + happen…") if it returned (a call of its own prompt: another prompt's call of the invocation is not its), + or else the note that closes the turn. The results, the note and the answer are one transaction: a crash between them would leave the turn open, and closing it again would add a second note. An approval returning is not the call: a denied call is closed with the note. diff --git a/python/restate/agents/_calls.py b/python/restate/agents/_calls.py index 80d7f017..007312b5 100644 --- a/python/restate/agents/_calls.py +++ b/python/restate/agents/_calls.py @@ -35,6 +35,11 @@ the same id, and a new call with the same input waits anew. An approval that a tool call waited for is not the call itself: a stopped turn does not report the call as done because its approval returned (``outcomes``). + +A call made while ``answer_once`` answers a prompt is kept as that prompt's (``for_prompt``), so that an +invocation that prompts more than once keeps the calls of each apart: a call is matched, and rejoined, among +its prompt's alone. Without it, a second prompt that makes the call the first made (the same tool and input) +would take the first's after a crash, while its record is not yet forgotten, and never make its own. """ from __future__ import annotations @@ -43,7 +48,7 @@ import json import typing import uuid -from collections.abc import Callable, Iterable +from collections.abc import Awaitable, Callable, Iterable from dataclasses import dataclass, field from restate.agents._common import flush_held @@ -81,6 +86,8 @@ class _Call(_Made, total=False): approval: bool """Whether the call is an approval that its tool call waited for (``wait_for``): its returning is not the tool call's.""" + prompt: str + """The prompt whose turn made the call (``for_prompt``); absent for a call made outside a prompt.""" @dataclass @@ -134,6 +141,29 @@ async def _calls_of(ctx: SessionContext) -> tuple[_Attempt, _Calls]: return attempt, attempt.calls +T = typing.TypeVar("T") + +_PROMPT: ScopeKey[str] = ScopeKey("the prompt of the calls") + + +async def for_prompt(ctx: SessionContext, prompt: str, work: Callable[[], Awaitable[T]]) -> T: + """Run ``work``, a turn's, with the calls its tools make kept as prompt ``prompt``'s. + + They are matched, and rejoined, within the prompt only. An invocation that prompts twice, its second prompt + making the call its first made (the same tool and input), would otherwise take the first's after a crash (its + record not yet forgotten), and never make its own. + """ + outer = _PROMPT.get(ctx) + _PROMPT.set(ctx, prompt) + try: + return await work() + finally: + if outer is None: + _PROMPT.delete(ctx) + else: + _PROMPT.set(ctx, outer) + + @dataclass class Call: """The call a tool call makes: its id (possibly from an earlier attempt), and a way to record that it returned.""" @@ -159,15 +189,18 @@ async def call_of( That is the call it made to ``tool`` before (if it runs again), or else, if ``rejoin``, the call an earlier attempt made with the same tool and input (if the model made it again under a new id), or else a new call. A - new call is an ``approval`` that its tool call waits for, if so. + new call is an ``approval`` that its tool call waits for, if so. Only the + calls of the current prompt (``for_prompt``) are matched. """ attempt, state = await _calls_of(ctx) encoded = json.dumps(input, sort_keys=True) + prompt = _PROMPT.get(ctx) + ours = [c for c in state.calls if c.get("prompt") == prompt] # A tool call may make more than one call (an approval, then the tool's own), each to a tool of its own. - call = next((c for c in state.calls if call_id in c["ids"] and c["tool"] == tool), None) + call = next((c for c in ours if call_id in c["ids"] and c["tool"] == tool), None) if call is None and rejoin: call = next( - (c for c in state.calls if c["attempt"] != attempt.id and c["tool"] == tool and c["input"] == encoded), + (c for c in ours if c["attempt"] != attempt.id and c["tool"] == tool and c["input"] == encoded), None, ) if call is not None: @@ -178,6 +211,8 @@ async def call_of( call = _Call(tool=tool, input=encoded, ids=[call_id], attempt=attempt.id) if approval: call["approval"] = True + if prompt is not None: + call["prompt"] = prompt state.calls.append(call) await _store(ctx, state) return Call(id=call["ids"][0], _ctx=ctx, _state=state, _call=call) @@ -199,7 +234,7 @@ async def settle(ctx: SessionContext, stored: Callable[[str, str | None], bool]) async def outcomes( - ctx: SessionContext, call_ids: Iterable[str], invocation: str | None = None + ctx: SessionContext, call_ids: Iterable[str], invocation: str | None = None, prompt: str | None = None ) -> dict[str, str | None]: """Return which of ``call_ids`` made a Restate call that returned in this invocation, or in ``invocation``. @@ -208,7 +243,8 @@ async def outcomes( one whose only returned call is its approval, which the tool call ran (or was denied) after. An earlier ``invocation``'s calls are read only while they are still stored: until an invocation of - the key makes calls of its own. They are read, never changed. + the key makes calls of its own. They are read, never changed. With ``prompt``, only the calls of its turn + count. """ if invocation is not None and invocation != ctx.request.id: state = await _load(ctx, invocation) @@ -218,7 +254,10 @@ async def outcomes( return { i: call.get("failed") for call in state.calls - if call.get("done") and not call.get("approval") + if call.get("done") + and not call.get("approval") + # Another prompt's call, of the same invocation: not this turn's. + and (prompt is None or call.get("prompt") in (None, prompt)) for i in call["ids"] if i in wanted } diff --git a/python/restate/agents/_conversation.py b/python/restate/agents/_conversation.py index 31210d1f..ac4226c2 100644 --- a/python/restate/agents/_conversation.py +++ b/python/restate/agents/_conversation.py @@ -97,7 +97,7 @@ from restate.agents._api import Steer from restate.agents._calls import SCHEMA as CALLS_SCHEMA -from restate.agents._calls import outcomes +from restate.agents._calls import for_prompt, outcomes from restate.agents._common import ( BUDGET, CANCELLED, @@ -991,7 +991,7 @@ async def close(self, ctx: SessionContext, status: Status, note: str) -> None: return self._check_writable() calls = self.open_calls() - returned = await outcomes(ctx, [call.id for call in calls], invocation_of(self.id)) + returned = await outcomes(ctx, [call.id for call in calls], invocation_of(self.id), self.id) closing = [ *items.results([(call, cut_off_result(returned, call.id, note)) for call in calls]), items.reply(note), @@ -1719,7 +1719,7 @@ def stored(call_id: str, failed: str | None) -> bool: return running is not None and running.id == prompt_id and running.stored(call_id, failed) try: - answered = await answering(ctx, stored, work) + answered = await for_prompt(ctx, prompt_id, lambda: answering(ctx, stored, work)) except TerminalError: # The turn ended for good, closed with the error (`_answer`): its answer is stored, so what follows the # answer runs, and a follower hears the turn end. An attempt that failed otherwise ends no turn, and runs diff --git a/tests/agents_conversation.py b/tests/agents_conversation.py index 2df72d2e..aa7969fb 100644 --- a/tests/agents_conversation.py +++ b/tests/agents_conversation.py @@ -694,6 +694,47 @@ def host() -> Host: assert results == {"c1": RETURNED_UNRECORDED, "c2": ENDED} +async def test_a_turn_left_without_an_answer_gets_the_outcomes_of_its_own_prompts_calls_only(): + from restate.agents._calls import call_of # pylint: disable=import-outside-toplevel + from restate.agents._common import ENDED # pylint: disable=import-outside-toplevel + + seen: list[Conversation] = [] + obj = sessions.SessionObject("asker") + + @obj.handler + async def ask(ctx: sessions.SessionContext) -> str: + async def first(conversation: Conversation) -> str: + seen.append(conversation) + await conversation.turn.append_reply(_calling("c1")) + # The first prompt's call returned, and its result was never stored. + await (await call_of(ctx, "lookup", {}, "c1")).answered() + return "one" + + async def second(conversation: Conversation) -> str: + seen.append(conversation) + # The second prompt's tool call has the same id, and its call did not return. + await conversation.turn.append_reply(_calling("c1")) + raise RuntimeError("the invocation is gone") + + await answer_once(ctx, "one", ITEMS, first) + return await answer_once(ctx, "two", ITEMS, second) + + @obj.handler + async def again(ctx: sessions.SessionContext, text: str) -> str: + async def run(conversation: Conversation) -> str: + seen.append(conversation) + return "fine" + + return await answer_once(ctx, text, ITEMS, run) + + backend = Backend() + with pytest.raises(RuntimeError): + await invoke(obj, "ask", Host(backend, service="asker", answers=PUBLISHED), request()) + await invoke(obj, "again", Host(backend, service="asker", answers=PUBLISHED), request(), "third") + results = {r.id: r.output for e in seen[-1].entries for r in e.results} + assert results == {"c1": ENDED} + + async def test_a_turn_left_without_an_answer_is_closed_once_however_a_crash_cuts_the_close(): from restate.agents.internal import ENDED # pylint: disable=import-outside-toplevel diff --git a/tests/agents_tools.py b/tests/agents_tools.py index 41be1ecd..177088b0 100644 --- a/tests/agents_tools.py +++ b/tests/agents_tools.py @@ -267,6 +267,56 @@ async def records(ctx: sessions.SessionContext) -> list[Any]: assert await internal.invoke(obj, "records", Host(backend, service="crashed_caller"), req) == [] +async def test_an_invocation_that_prompts_twice_keeps_the_calls_of_each_prompt_apart(): + """A crash in the second prompt, whose tool makes the call the first prompt's tool made (the same tool and input). + + The first prompt's record is still stored, its result never was. The retry's second prompt makes a call of its + own, under its own idempotency key, and does not take the first's. + """ + from agents_conversation import ITEMS, PUBLISHED # pylint: disable=import-error,import-outside-toplevel + + from restate.agents._conversation import Conversation, answer_once # pylint: disable=import-outside-toplevel + + lookup = call(status, description="The status of an order.") + args = {"key": "eu", "order": "o1"} + obj = sessions.SessionObject("two_prompts") + runs: list[str] = [] + + async def calling(conversation: Conversation, call_id: str) -> None: + calls = [{"id": call_id, "name": lookup.name, "input": args}] + await conversation.turn.append_reply({"role": "assistant", "text": "", "calls": calls}) + + @obj.handler + async def ask(ctx: sessions.SessionContext) -> str: + async def first(conversation: Conversation) -> str: + runs.append("first") + await calling(conversation, "t1") + await lookup.run(args, ToolCall(ctx, "t1")) + return "one" # the model ended without the result being stored + + async def second(conversation: Conversation) -> str: + runs.append("second") + await calling(conversation, "t2") + if runs.count("second") == 1: + raise RuntimeError("the process crashed") + await lookup.run(args, ToolCall(ctx, "t2")) + return "two" + + assert await answer_once(ctx, "one", ITEMS, first) == "one" + return await answer_once(ctx, "two", ITEMS, second) + + backend, req = Backend(), request() + answers = {**PUBLISHED, "status": b'{"order": "o1", "status": "shipped"}'} + first_attempt = Host(backend, service="two_prompts", answers=answers) + with pytest.raises(RuntimeError, match="crashed"): + await internal.invoke(obj, "ask", first_attempt, req) + retry = Host(backend, service="two_prompts", answers=answers) + assert await internal.invoke(obj, "ask", retry, req) == "two" + + made = [c for c in [*first_attempt.calls, *retry.calls] if c[1] == "status"] + assert [c[4] for c in made] == [f"{req.id}:t1", f"{req.id}:t2"] + + # --- Waits need an agent ------------------------------------------------------------------------------------------ NEEDS_AGENT = "needs an agent, whose companion holds its waits: 'desk' is a plain session object" From 14c4ad5202f7c7781113cfcf9753ae3a87f13c93 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:30:35 +0100 Subject: [PATCH 04/13] Agents: tests of what a turn's Restate tools cost in commits --- tests/agents_commits.py | 394 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 394 insertions(+) create mode 100644 tests/agents_commits.py diff --git a/tests/agents_commits.py b/tests/agents_commits.py new file mode 100644 index 00000000..0003c52a --- /dev/null +++ b/tests/agents_commits.py @@ -0,0 +1,394 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""What a turn costs in commits of ``ctx.db`` when its tools are Restate tools, per framework. + +A commit is an acknowledged round trip to Restate. Each framework's real adapter runs the same scripted turn (the +model's requests and tool calls below), once with plain tools and once with the same tools as Restate ``call`` tools, +over the in-process host that counts its syncs. The cost of the Restate tools is the difference. +""" + +# pylint: disable=missing-function-docstring,missing-class-docstring + +import json +import typing +from collections.abc import Awaitable, Callable +from dataclasses import dataclass, field +from typing import Any + +import pytest + +import restate +from restate import sessions +from restate.agents import call, tool +from restate.agents._tools import Tool +from restate.sessions.internal import invoke +from sessions_database import Backend # pylint: disable=import-error +from sessions_object import Host, request # pylint: disable=import-error + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +EXTRA_COMMITS_PER_RESTATE_CALL = 3 +"""What each Restate tool call costs in commits, over the same call of a plain tool. The call's record, in +``restate_agent_calls``, is committed: (1) before the call is made, (2) when it answered, and (3) when the record is +forgotten, after the framework stored the tool's result.""" + +REQUESTS = 4 +TOOL_CALLS = 3 +"""The turn: a tool call after each of the first ``TOOL_CALLS`` model requests, then the final answer.""" + +PLAIN_COMMITS = { + "adk": 8, + "langgraph agent": 8, + "langgraph graph": 26, + "openai": 8, + "pydantic_ai": 8, +} +"""The commits of the second turn of a key, with plain tools, as measured. Each framework's own: the conversation +stores the user's message (1), each model request's response that calls a tool (3) and each tool's result (3), and +the last commit has the final response and the turn's answer (1). A graph of your own has more: LangGraph's +checkpointer commits a checkpoint and the writes of each node of each step of the graph, besides the conversation's +items.""" + + +# --- The callee, the tools, and the host that counts ------------------------------------------------ + +shipping = restate.VirtualObject("commits_shipping") + + +@shipping.handler() +async def status(ctx: restate.ObjectContext, order: str) -> str: + return f"shipped {order}" + + +def result_of(order: str) -> str: + """What both kinds of tool answer for an order: the callee's, as it is faked here.""" + return f"shipped {order}" + + +@tool(name="lookup") +async def plain_lookup(key: str, input: str) -> str: + """The status of an order.""" + return result_of(input) + + +restated_lookup = call(status, name="lookup", description="The status of an order.") + + +TURN: list[str] = [""] +"""The turn that runs: its text, which its tool calls' ids are made of.""" + + +def call_id(index: int) -> str: + """A tool call's id, new for each turn: the same id is the same call, and each turn's calls are its own.""" + return f"call-{TURN[0]}-{index}" + + +def order_of(index: int) -> str: + """The order that the ``index``-th tool call of the turn asks about: its own, in each turn.""" + return f"{TURN[0]}-o{index}" + + +def arguments_of(index: int) -> dict[str, str]: + """The model's arguments of its ``index``-th tool call: both tools take them.""" + return {"key": "eu", "input": order_of(index)} + + +@dataclass +class Counting(Host): + """A host that counts its syncs (each a commit), keeps what each committed, and answers the faked callee.""" + + syncs: int = 0 + committed: list[dict[str, bytes]] = field(default_factory=list[dict[str, bytes]]) + + async def sync(self) -> None: + await super().sync() + self.syncs += 1 + self.committed.append(dict(self.backend.stored)) + + def generic_call(self, service, handler, arg, key=None, idempotency_key=None, headers=None, name=None): + if handler == "status": + self.answers[handler] = json.dumps(result_of(json.loads(arg))).encode() + return super().generic_call(service, handler, arg, key, idempotency_key, headers, name) + + +@dataclass +class Measured: + commits: int + """The commits of the second turn.""" + committed: list[dict[str, bytes]] + """What each of them committed (the store's entries).""" + calls_made: int + """The calls the Restate tools made.""" + answer: str = "" + backend: Backend = field(default_factory=Backend) + + +Ask = Callable[[sessions.SessionContext, str, list[Tool]], Awaitable[str]] + + +async def measure(ask: Ask, restated: bool) -> Measured: + """Run the turn twice on the same key, and return what the second cost.""" + asker = sessions.SessionObject("asker") + + @asker.handler + async def run(ctx: sessions.SessionContext, text: str) -> str: + return await ask(ctx, text, [restated_lookup if restated else plain_lookup]) + + backend = Backend() + + async def turn(text: str) -> tuple[Counting, str]: + TURN[0] = text + host = Counting(backend, service="asker", answers={"publish": b'{"revision": 1}'}) + return host, await invoke(asker, "run", host, request(), text) + + await turn("first") + host, answer = await turn("second") + made = [c for c in host.calls if c[1] == "status"] + return Measured(host.syncs, host.committed, len(made), answer, backend) + + +# --- Reading what a commit held ----------------------------------------------------------------- + + +async def held(committed: dict[str, bytes]) -> tuple[str, list[dict[str, Any]]]: + """What a commit held: all the stored tables but the calls' as text, and the calls' records.""" + reader = sessions.SessionObject("asker") + + @reader.handler + async def read(ctx: sessions.SessionContext) -> tuple[str, list[dict[str, Any]]]: + tables = [str(row["name"]) for row in await ctx.db.query("SELECT name FROM sqlite_master WHERE type = 'table'")] + text = "" + for table in tables: + if table != "restate_agent_calls": + text += repr(await ctx.db.query(f'SELECT * FROM "{table}"')) + records: list[dict[str, Any]] = [] + if "restate_agent_calls" in tables: + row = await ctx.db.get("SELECT calls FROM restate_agent_calls") + records = json.loads(typing.cast(str, row["calls"])) if row else [] + return text, records + + copy = Backend() + copy.stored = dict(committed) + return await invoke(reader, "read", Host(copy, service="asker"), request()) + + +async def assert_no_result_ahead_of_its_record(measured: Measured) -> None: + """At no commit does the committed state hold a tool's real result while that call's record is not marked done. + + A call whose record was forgotten (after it was marked done) may hold its result.""" + done: set[int] = set() + seen_result = [False] * TOOL_CALLS + for committed in measured.committed: + text, records = await held(committed) + present = {i for i in range(TOOL_CALLS) for r in records if f'"{order_of(i)}"' in r["input"]} + for i in range(TOOL_CALLS): + for r in records: + if f'"{order_of(i)}"' in r["input"] and r.get("done"): + done.add(i) + if result_of(order_of(i)) in text: + seen_result[i] = True + assert i in done, f"the result of call {i} is committed while its record is not done: {records}" + assert i not in present or i in done + # The check is not vacuous: every result was committed, and each record was seen done. + assert all(seen_result) + assert done == set(range(TOOL_CALLS)) + + +async def assert_costs(name: str, ask: Ask) -> None: + plain = await measure(ask, restated=False) + restated = await measure(ask, restated=True) + assert plain.calls_made == 0 and restated.calls_made == TOOL_CALLS + for measured in (plain, restated): + assert measured.answer == "done" + # Every tool call's result reached the transcript. + text, _ = await held(measured.committed[-1]) + assert all(result_of(order_of(i)) in text for i in range(TOOL_CALLS)) + assert plain.commits == PLAIN_COMMITS[name] + assert restated.commits == plain.commits + EXTRA_COMMITS_PER_RESTATE_CALL * TOOL_CALLS + await assert_no_result_ahead_of_its_record(restated) + + +# --- Each framework's turn ----------------------------------------------------------------------- + + +async def test_adk_turn(): + pytest.importorskip("google.adk") + from collections.abc import AsyncGenerator # pylint: disable=import-outside-toplevel + + from google.adk.models import BaseLlm # pylint: disable=import-outside-toplevel + from google.adk.models.llm_request import LlmRequest # pylint: disable=import-outside-toplevel + from google.adk.models.llm_response import LlmResponse # pylint: disable=import-outside-toplevel + from google.genai import types # pylint: disable=import-outside-toplevel + + from restate.agents import adk # pylint: disable=import-outside-toplevel + + class Scripted(BaseLlm): + model: str = "scripted" + asked: list[int] = [] + + async def generate_content_async( + self, llm_request: LlmRequest, stream: bool = False + ) -> AsyncGenerator[LlmResponse, None]: + n = len(self.asked) + self.asked.append(n) + if n < TOOL_CALLS: + part = types.Part(function_call=types.FunctionCall(id=call_id(n), name="lookup", args=arguments_of(n))) + else: + part = types.Part(text="done") + yield LlmResponse(content=types.Content(role="model", parts=[part])) + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + return await adk.prompt(ctx, text, model=Scripted(asked=[]), tools=[*tools]) + + await assert_costs("adk", ask) + + +async def test_langgraph_agent_turn(): + pytest.importorskip("langgraph") + from langchain_core.language_models import BaseChatModel # pylint: disable=import-outside-toplevel + from langchain_core.messages import AIMessage, BaseMessage # pylint: disable=import-outside-toplevel + from langchain_core.outputs import ChatGeneration, ChatResult # pylint: disable=import-outside-toplevel + + from restate.agents import langgraph # pylint: disable=import-outside-toplevel + + class Scripted(BaseChatModel): + asked: list[int] = [] + + @property + def _llm_type(self) -> str: + return "scripted" + + def bind_tools(self, tools: Any, **kwargs: Any) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] + return self + + def _generate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> ChatResult: + raise AssertionError("the requests are async") + + async def _agenerate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> ChatResult: + n = len(self.asked) + self.asked.append(n) + if n < TOOL_CALLS: + reply = AIMessage("", tool_calls=[{"id": call_id(n), "name": "lookup", "args": arguments_of(n)}]) + else: + reply = AIMessage("done") + return ChatResult(generations=[ChatGeneration(message=reply)]) + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + return await langgraph.prompt(ctx, text, model=Scripted(asked=[]), tools=[*tools]) + + await assert_costs("langgraph agent", ask) + + +async def test_langgraph_graph_turn(): + pytest.importorskip("langgraph") + from langchain_core.messages import AIMessage # pylint: disable=import-outside-toplevel + from langgraph.graph import END, START, MessagesState, StateGraph # pylint: disable=import-outside-toplevel + from langgraph.prebuilt import ToolNode # pylint: disable=import-outside-toplevel + + from restate.agents import langgraph # pylint: disable=import-outside-toplevel + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + asked: list[int] = [] + + async def model(state: MessagesState) -> dict[str, Any]: + n = len(asked) + asked.append(n) + if n < TOOL_CALLS: + reply = AIMessage("", tool_calls=[{"id": call_id(n), "name": "lookup", "args": arguments_of(n)}]) + else: + reply = AIMessage("done") + return {"messages": [reply]} + + def route(state: MessagesState) -> str: + last = state["messages"][-1] + return "tools" if getattr(last, "tool_calls", None) else END + + builder = StateGraph(MessagesState) + builder.add_node("model", model) + builder.add_node("tools", ToolNode(langgraph.tools([*tools]))) + builder.add_edge(START, "model") + builder.add_conditional_edges("model", route, ["tools", END]) + builder.add_edge("tools", "model") + return await langgraph.prompt(ctx, text, graph=builder) + + await assert_costs("langgraph graph", ask) + + +async def test_openai_turn(): + pytest.importorskip("agents") + from agents import Model, ModelResponse, Usage, set_tracing_disabled # pylint: disable=import-outside-toplevel + from openai.types.responses import ( # pylint: disable=import-outside-toplevel + ResponseFunctionToolCall, + ResponseOutputMessage, + ResponseOutputText, + ) + + from restate.agents import openai # pylint: disable=import-outside-toplevel + + set_tracing_disabled(True) + + class Scripted(Model): + def __init__(self) -> None: + self.asked = 0 + + async def get_response(self, *args: Any, **kwargs: Any) -> ModelResponse: + n = self.asked + self.asked += 1 + output: Any + if n < TOOL_CALLS: + output = ResponseFunctionToolCall( + type="function_call", call_id=call_id(n), name="lookup", arguments=json.dumps(arguments_of(n)) + ) + else: + text: list[Any] = [ResponseOutputText(type="output_text", text="done", annotations=[])] + output = ResponseOutputMessage( + id="msg", type="message", role="assistant", status="completed", content=text + ) + return ModelResponse(output=[output], usage=Usage(), response_id=None) + + def stream_response(self, *args: Any, **kwargs: Any) -> Any: + raise NotImplementedError + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + return await openai.prompt(ctx, text, model=Scripted(), tools=[*tools]) + + await assert_costs("openai", ask) + + +async def test_pydantic_ai_turn(): + pytest.importorskip("pydantic_ai") + from pydantic_ai.messages import ( # pylint: disable=import-outside-toplevel + ModelMessage, + ModelResponse, + TextPart, + ToolCallPart, + ) + from pydantic_ai.models.function import AgentInfo, FunctionModel # pylint: disable=import-outside-toplevel + + from restate.agents import pydantic_ai # pylint: disable=import-outside-toplevel + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + asked: list[int] = [] + + def scripted(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: + n = len(asked) + asked.append(n) + if n < TOOL_CALLS: + return ModelResponse(parts=[ToolCallPart("lookup", arguments_of(n), tool_call_id=call_id(n))]) + return ModelResponse(parts=[TextPart("done")]) + + return await pydantic_ai.prompt(ctx, text, model=FunctionModel(scripted), tools=[*tools]) + + await assert_costs("pydantic_ai", ask) From c8035898569ce2ed4ed387374d766faf93821510 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:31:19 +0100 Subject: [PATCH 05/13] Agents: LangGraph's model sees an empty answer, and a blank reply of its own, as (no answer) --- docs/agents/turns.md | 5 ++- python/restate/agents/_common.py | 4 ++ python/restate/agents/langgraph/_agent.py | 29 ++++++++++-- tests/agents_langgraph.py | 54 +++++++++++++++++++++++ 4 files changed, 88 insertions(+), 4 deletions(-) diff --git a/docs/agents/turns.md b/docs/agents/turns.md index 1af853ac..b80850c9 100644 --- a/docs/agents/turns.md +++ b/docs/agents/turns.md @@ -691,7 +691,10 @@ tool calls, and no call or result after it), the note that closed it, or else its answer, stored as its reply, from the agent the turn is with (a turn that ended with a tool's output that is the answer, say). That message is the answer's in the summary, under the same id. Only an empty answer gets -no message. A LangGraph graph, which keeps its own messages, is given only a +no message. A LangGraph agent's model sees an empty answer, and a reply of +its own with nothing in it (stored as it came), as `(no answer)` in the +conversation that goes on: a model provider may refuse an empty message. A +LangGraph graph, which keeps its own messages, is given only a closed turn's closing record, never an answer the conversation stored. **Asking again within a turn.** A turn can ask the model again before it diff --git a/python/restate/agents/_common.py b/python/restate/agents/_common.py index 1a301fdc..66884650 100644 --- a/python/restate/agents/_common.py +++ b/python/restate/agents/_common.py @@ -292,6 +292,10 @@ def is_cancellation(error: BaseException) -> bool: return isinstance(error, TerminalError) and error.status_code == CANCELLATION and error.message == "cancelled" +NO_ANSWER = "(no answer)" +"""What an empty answer says, as the model sees it later in the conversation: a model provider may refuse an empty +text (Anthropic's does).""" + CANCELLED = "Cancelled: the turn was stopped before it finished." """The answer of a cancelled turn, and the result of each tool call it cut off, which the model sees later in the conversation.""" diff --git a/python/restate/agents/langgraph/_agent.py b/python/restate/agents/langgraph/_agent.py index d52434f9..818852a4 100644 --- a/python/restate/agents/langgraph/_agent.py +++ b/python/restate/agents/langgraph/_agent.py @@ -42,7 +42,9 @@ - The model sees the earlier turns as their messages and answers, and the latest turns whole (the agent's ``window``), as many as its ``budget`` holds; the built-in agent has its model summarize the earliest once they - outgrow it, after a turn's answer (``_conversation.py``). + outgrow it, after a turn's answer (``_conversation.py``). A reply of the + model with nothing in it is stored as it came, and sent as ``(no answer)``, + as an empty answer is: a model provider may refuse an empty message. - The model sees the latest messages of a conversation that lives long: as many as fit in ``WINDOW`` of its context window, by LangChain's ``trim_messages`` (starting with a prompt, never with a message steered to @@ -90,6 +92,7 @@ from restate.agents._common import ( MODEL_ENV, + NO_ANSWER, Check, ModelError, PerSession, @@ -240,6 +243,25 @@ def _text(message: BaseMessage) -> str: return str(message.text) +def _blank(message: BaseMessage) -> bool: + """Return whether ``message`` is a reply of the model with nothing in it: no text, no tool call, no other content.""" + if not isinstance(message, AIMessage) or message.tool_calls or message.invalid_tool_calls: + return False + if isinstance(message.content, str): + return not message.content.strip() + return all( + (isinstance(block, str) and not block.strip()) + or (isinstance(block, dict) and block.get("type") == "text" and not str(block.get("text") or "").strip()) + for block in message.content + ) + + +def _sendable(messages: Sequence[BaseMessage]) -> list[BaseMessage]: + """Return ``messages`` as a model provider takes them: a reply of the model with nothing in it (stored as it came) + says so, as an empty answer does. Anthropic's API refuses an empty message but the last.""" + return [AIMessage(NO_ANSWER, id=m.id) if _blank(m) else m for m in messages] + + STEER = "steer:" """The prefix of the id that a message steered to a turn has in the graph: ``steer:``.""" @@ -267,7 +289,8 @@ def steered(self, text: str, steer_id: str) -> Item: return HumanMessage(text, id=f"{STEER}{steer_id}") def reply(self, text: str, agent: str | None = None) -> Item: - return AIMessage(text) + # A model provider may refuse an empty message: an empty answer, as the model sees it later, says so. + return AIMessage(text if text.strip() else NO_ANSWER) def results(self, results: Sequence[tuple[Call, str]]) -> list[Item]: return [ToolMessage(text, tool_call_id=call.id, name=call.name, status="error") for call, text in results] @@ -391,7 +414,7 @@ async def run(conversation: Conversation) -> str: return final graph = _graph(ctx, conversation, chat_model, tools, system) try: - state = typing.cast(State, await graph.ainvoke({"messages": conversation.history()})) + state = typing.cast(State, await graph.ainvoke({"messages": _sendable(conversation.history())})) except Exception as error: if (terminal := terminal_of(error)) is not None: # LangGraph's own error, which a retry would meet again: its recursion limit, say. diff --git a/tests/agents_langgraph.py b/tests/agents_langgraph.py index 0a00595e..e21da0bf 100644 --- a/tests/agents_langgraph.py +++ b/tests/agents_langgraph.py @@ -822,3 +822,57 @@ async def test_a_stopped_or_failed_request_leaves_no_scope_open(): await asked("fail x") assert scopes == [("model", 1)] assert now[0].open_scopes == 0 + + +async def test_a_blank_reply_of_the_model_is_sent_later_as_no_answer(): + seen: list[list[BaseMessage]] = [] + + class Blank(Scripted): + def _generate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> ChatResult: + seen.append(list(messages)) + prompt = next(m for m in reversed(messages) if isinstance(m, HumanMessage)) + if str(prompt.content).startswith("blank"): + return ChatResult(generations=[ChatGeneration(message=AIMessage(" "))]) + return ChatResult(generations=[ChatGeneration(message=AIMessage("done"))]) + + ask = asking(model=Blank()) + assert (await ask("blank 1")).strip() == "" + assert await ask("next 2") == "done" + # The model's blank reply, in the middle of the next request, says so: a provider may refuse it. + assert [(type(m).__name__, m.content) for m in seen[-1]] == [ + ("HumanMessage", "blank 1"), + ("AIMessage", "(no answer)"), + ("HumanMessage", "next 2"), + ] + + +async def test_an_empty_answer_is_sent_later_as_no_answer_and_a_reply_with_tool_calls_is_not_blank(): + from restate.agents.langgraph import _agent # pylint: disable=import-outside-toplevel + + # The reply of an earlier turn that fell out of the window is made of its answer. + assert _agent._Items().reply(" ") == AIMessage("(no answer)") # pyright: ignore[reportPrivateUsage] + assert _agent._Items().reply("hi") == AIMessage("hi") # pyright: ignore[reportPrivateUsage] + call = AIMessage("", tool_calls=[{"id": "c1", "name": "get_weather", "args": {"city": "x"}}]) + text = AIMessage([{"type": "text", "text": "hi"}]) + blank = AIMessage([{"type": "text", "text": " "}], id="m1") + assert _agent._sendable([call, text, blank]) == [call, text, AIMessage("(no answer)", id="m1")] # pyright: ignore[reportPrivateUsage] + + +async def test_a_blank_reply_that_is_not_the_answer_asked_for_is_asked_again_without_being_sent_blank(): + import pydantic # pylint: disable=import-outside-toplevel + + class Weather(pydantic.BaseModel): + city: str + + seen: list[list[BaseMessage]] = [] + + class Blank(Scripted): + def _generate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> ChatResult: + seen.append(list(messages)) + text = "" if len(seen) == 1 else '{"city": "Rome"}' + return ChatResult(generations=[ChatGeneration(message=AIMessage(text))]) + + ask = asking(model=Blank(), output=Weather) + assert await ask("where") == Weather(city="Rome") + assert len(seen) == 2 + assert [m.content for m in seen[-1] if isinstance(m, AIMessage)] == ["(no answer)"] From 1e034b6938d100ff6358755b5a9654ea7b544e22 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:40:56 +0100 Subject: [PATCH 06/13] Sessions: one heartbeat timer across back-to-back working scopes; RESTATE_SESSIONS_HEARTBEAT sets the interval --- docs/agents/turns.md | 3 +- python/restate/sessions/_api.py | 4 +- python/restate/sessions/_driver.py | 90 ++++++++++++++++---- tests/sessions_driver.py | 127 +++++++++++++++++++++++++++++ 4 files changed, 205 insertions(+), 19 deletions(-) diff --git a/docs/agents/turns.md b/docs/agents/turns.md index 1af853ac..68f22685 100644 --- a/docs/agents/turns.md +++ b/docs/agents/turns.md @@ -467,7 +467,8 @@ sequenceDiagram after the timeout, so that a wait of days holds no process, and the next attempt gets the cancellation as it starts. A deployment that sets an inactivity timeout under 20 seconds is shut down between two of those - messages. + messages, unless it shortens the interval with `RESTATE_SESSIONS_HEARTBEAT` + (in milliseconds). - A cancellation that comes once the turn answered changes nothing: the answer stands. - A tool cut short by the stop raises the stop's reason, so the model never diff --git a/python/restate/sessions/_api.py b/python/restate/sessions/_api.py index 25a3ac77..f46c74f0 100644 --- a/python/restate/sessions/_api.py +++ b/python/restate/sessions/_api.py @@ -369,7 +369,9 @@ def working(self) -> AbstractAsyncContextManager[None]: done again. Inside it, the attempt sends a heartbeat every 20 seconds, whatever it waits for: keep a long wait on Restate (a call, a signal) out of it. The database's own calls keep the attempt alive by - themselves. + themselves. A deployment that shortens Restate's inactivity timeout + must shorten the interval with it: ``RESTATE_SESSIONS_HEARTBEAT`` sets + it, in milliseconds. """ ... diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 4bc9c3e2..734d7673 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -31,7 +31,9 @@ import asyncio import contextlib import logging +import math import operator +import os import traceback import typing from collections.abc import AsyncIterator, Awaitable, Callable, Generator @@ -70,9 +72,25 @@ waits for (or, waiting for nothing, starts again at once), and a wait of days holds no process. Work that must not be cut off (a model request) says so with ``working``: while any of it runs, the attempt heartbeats, whatever else it -waits for. A deployment that shortens the timeout must shorten this with it. +waits for. A deployment that shortens the timeout must shorten this with it +(``RESTATE_SESSIONS_HEARTBEAT``, in milliseconds, sets it). """ + +def heartbeat_interval() -> float: + """The heartbeat interval in seconds: ``RESTATE_SESSIONS_HEARTBEAT`` (milliseconds), or ``HEARTBEAT_INTERVAL``. + + A value that is not a positive, finite number is ignored. + """ + default = HEARTBEAT_INTERVAL.total_seconds() + raw = os.environ.get("RESTATE_SESSIONS_HEARTBEAT", "") + try: + millis = float(raw) if "_" not in raw else math.nan + except ValueError: + return default + return millis / 1000 if math.isfinite(millis) and millis > 0 else default + + SYNC_KEY = "v22/sync" """The state key a sync clears with an ack, under the state format's prefix, which tooling hides.""" @@ -144,7 +162,16 @@ def __init__( self._handler: asyncio.Future[bytes] | None = None # The ``working`` scopes open: the attempt heartbeats while there is one. self._scopes: int = 0 - self._heartbeats: asyncio.Task[None] | None = None + # The one timer of the heartbeats, armed for ``_beat_due``. It outlives a run of scopes, so the database's + # scopes (one a statement) do not start and cancel a timer each: it fires, finds no scope open, and is not + # armed again. + self._heartbeats: asyncio.TimerHandle | None = None + self._beat_due: float = 0.0 + # The run of scopes now open: its interval, and when its next heartbeat is due. + self._run_every: float = 0.0 + self._next_beat: float = 0.0 + # The heartbeat interval, read from the environment on first use. + self._beat_every: float | None = None # When the attempt last wrote to Restate, which restarts Restate's inactivity timer. self._wrote_at: float = self._loop.time() self._end_listeners: list[Callable[[], None]] = [] @@ -484,7 +511,7 @@ async def working(self) -> AsyncIterator[None]: closing. The first comes once the attempt has been silent for an interval (at once, if it already has), so the silence never reaches more than that; a scope that closes sooner (the database's, around each of its - calls) sends nothing. + calls) sends nothing. One timer serves scopes that follow one another. Raises: RuntimeError: Entered on another event loop than the attempt's (a @@ -492,28 +519,57 @@ async def working(self) -> AsyncIterator[None]: """ if asyncio.get_running_loop() is not self._loop: raise RuntimeError("ctx.working() must be entered on the attempt's own event loop, not another thread's") + if self._beat_every is None: + self._beat_every = heartbeat_interval() self._scopes += 1 - if self._scopes == 1 and self.ended is None: - self._heartbeats = asyncio.ensure_future(self._heartbeat()) + if self._scopes == 1: + self._start_heartbeats(self._beat_every) try: yield finally: self._scopes -= 1 - if self._scopes == 0 and self._heartbeats is not None: - self._heartbeats.cancel() - self._heartbeats = None - async def _heartbeat(self) -> None: - """Tell Restate the attempt makes progress, while a ``working`` scope is open.""" - interval = HEARTBEAT_INTERVAL.total_seconds() + def _start_heartbeats(self, every: float) -> None: + """A run of scopes opens: its beats are ``every`` after it opened, and every ``every`` while a scope stays open. + + The timer is armed for the first. On firing it beats if the run it finds is that old, waits out the rest if a + run that opened later is younger, and is let go if no scope is open. + """ + if self.ended is not None: + return + now = self._loop.time() # The first once the silence reaches an interval: at once, if it already has. - await asyncio.sleep(max(0.0, interval - (self._loop.time() - self._wrote_at))) - while True: - try: - self.act(lambda vm: vm.heartbeat()) - except SdkInternalBaseException: + if now - self._wrote_at >= every: + self._heartbeat() + self._run_every = every + self._next_beat = now + every + self._arm(self._next_beat) + + def _arm(self, due: float) -> None: + """Arm the timer for ``due``, unless it is armed for that or earlier.""" + if self._heartbeats is not None: + if self._beat_due <= due: return - await asyncio.sleep(interval) + self._heartbeats.cancel() + self._beat_due = due + self._heartbeats = self._loop.call_at(due, self._beat) + + def _beat(self) -> None: + """The timer fired.""" + self._heartbeats = None + if self.ended is not None or self._scopes == 0: + return + now = self._loop.time() + if now >= self._next_beat: + self._heartbeat() + self._next_beat = now + self._run_every + self._arm(self._next_beat) + + def _heartbeat(self) -> None: + """Tell Restate the attempt makes progress.""" + # If the attempt ended, the tick notices. + with contextlib.suppress(SdkInternalBaseException): + self.act(lambda vm: vm.heartbeat()) def _cancelled_error() -> TerminalError: diff --git a/tests/sessions_driver.py b/tests/sessions_driver.py index b8b27369..83106324 100644 --- a/tests/sessions_driver.py +++ b/tests/sessions_driver.py @@ -159,6 +159,17 @@ async def works_alone(ctx: sessions.SessionContext, kept: bool) -> str: return "done" +@notes.handler() +async def scopes_then_waits(ctx: sessions.SessionContext, scopes: int) -> str: + """Opens and closes ``scopes`` scopes of ``ctx.working`` back to back (the database opens one a statement), then + waits outside Restate, in no scope, until the test lets it go on.""" + for _ in range(scopes): + async with ctx.working(): + await asyncio.sleep(0) + await gate_of().wait() + return "done" + + @notes.handler() async def works_beside_a_call(ctx: sessions.SessionContext, how: str) -> str: """Waits for a call that is never answered, working meanwhile: in ``ctx.working`` (``kept``), in an annotation @@ -660,6 +671,122 @@ async def test_an_open_annotation_is_a_trace_and_keeps_nothing_alive(gate: Gate, assert await beats_while_at(gate, "works_beside_a_call", side) == 0, describe(side) +class Scheduling: + """What the driver schedules for its heartbeats while a test runs: the tasks it creates, and the timers it arms.""" + + def __init__(self) -> None: + self.tasks = 0 + self.timers = 0 + + +@pytest.fixture +async def scheduling(monkeypatch) -> typing.AsyncIterator[Scheduling]: + loop = asyncio.get_running_loop() + seen = Scheduling() + previous = loop.get_task_factory() + arm = loop.call_at + + def factory(loop_: asyncio.AbstractEventLoop, coro: Any, **kwargs: Any) -> asyncio.Future[Any]: + if "heartbeat" in getattr(coro, "__qualname__", ""): + seen.tasks += 1 + if previous is not None: + return previous(loop_, coro, **kwargs) + return asyncio.Task(coro, loop=loop_, **kwargs) + + def call_at(when: float, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> asyncio.TimerHandle: + if "beat" in getattr(callback, "__name__", ""): + seen.timers += 1 + return arm(when, callback, *args, **kwargs) + + loop.set_task_factory(factory) + monkeypatch.setattr(loop, "call_at", call_at) + try: + yield seen + finally: + loop.set_task_factory(previous) + + +@pytest.fixture +def slow_heartbeats(monkeypatch) -> None: + # Long enough that the scopes all close before the first beat is due. + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.2)) + + +async def idle_after_scopes(gate_: Gate, side: RestateSide, scheduling: Scheduling) -> tuple[int, int, int]: + """Run ``scopes_then_waits``, leave it waiting outside any scope for ten heartbeat intervals, then let it end. + + Returns the heartbeats it sent, and the tasks and timers it created, up to the end of that wait (the end of the + attempt opens scopes of the database's own). + """ + running = asyncio.ensure_future(run(notes, "scopes_then_waits", side)) + await gate_.reached.wait() + await asyncio.sleep(10 * _driver.HEARTBEAT_INTERVAL.total_seconds()) + seen = (heartbeats(side), scheduling.tasks, scheduling.timers) + gate_.opened.set() + await running + return seen + + +async def test_scopes_that_follow_one_another_share_one_timer( + gate: Gate, slow_heartbeats: None, scheduling: Scheduling +): + # The database opens a scope for each statement: none of them starts and cancels a task or a timer of its own. + side = RestateSide() + side.start("kt1", 50) + beats, tasks, timers = await idle_after_scopes(gate, side, scheduling) + assert (tasks, timers) == (0, 1), describe(side) + assert beats == 0, describe(side) + assert output_of(side.sent()) == "done", describe(side) + + +async def test_after_the_last_scope_closed_nothing_beats_and_nothing_is_left_running( + gate: Gate, slow_heartbeats: None, scheduling: Scheduling +): + side = RestateSide() + side.start("kt2", 5) + # Ten intervals after the scopes closed: the timer fired once, found no scope open, and was not armed again. + beats, tasks, timers = await idle_after_scopes(gate, side, scheduling) + assert (beats, tasks, timers) == (0, 0, 1), describe(side) + + +@pytest.mark.parametrize("value", ["", "abc", "0", "-5", "nan", "inf", "1_0", "1e999"]) +def test_an_invalid_heartbeat_setting_is_the_default(monkeypatch, value: str): + monkeypatch.setenv("RESTATE_SESSIONS_HEARTBEAT", value) + assert _driver.heartbeat_interval() == _driver.HEARTBEAT_INTERVAL.total_seconds() + + +@pytest.mark.parametrize("value,seconds", [("20", 0.02), ("1500", 1.5), (" 250 ", 0.25), ("0.5", 0.0005)]) +def test_the_heartbeat_setting_is_in_milliseconds(monkeypatch, value: str, seconds: float): + monkeypatch.setenv("RESTATE_SESSIONS_HEARTBEAT", value) + assert _driver.heartbeat_interval() == seconds + + +def test_an_unset_heartbeat_setting_is_twenty_seconds(monkeypatch): + monkeypatch.delenv("RESTATE_SESSIONS_HEARTBEAT", raising=False) + assert _driver.heartbeat_interval() == 20.0 + + +async def test_the_heartbeat_setting_sets_the_interval_of_an_attempt(gate: Gate, monkeypatch): + monkeypatch.setenv("RESTATE_SESSIONS_HEARTBEAT", "20") + side = RestateSide() + side.start("kt3", True) + # The interval is 20 ms from the environment, not the 20 s default. + running = asyncio.ensure_future(run(notes, "works_alone", side)) + await gate.reached.wait() + await asyncio.sleep(0.4) + gate.opened.set() + await running + assert heartbeats(side) >= 3, describe(side) + + +async def test_a_heartbeat_setting_that_is_invalid_leaves_the_default_interval(gate: Gate, monkeypatch): + monkeypatch.setenv("RESTATE_SESSIONS_HEARTBEAT", "soon") + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.02)) + side = RestateSide() + side.start("kt4", True) + assert await beats_while_at(gate, "works_alone", side) >= 3, describe(side) + + async def test_a_read_that_asks_restate_nothing_sees_a_carried_cancellation_too_once(gate: Gate): # A read of pages the session holds is answered without a wait on Restate, so a cancellation delivered at the # store's waits had nothing to land on. It is delivered where the handler calls. From 9e17a5aa34db0f85323188e7e29d85faa9eea761 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:42:36 +0100 Subject: [PATCH 07/13] Sessions: RESTATE_SQL_L0_BYTES sets how much of a database's checkpoints Restate keeps --- src/sessions.rs | 77 ++++++++++++++++++----- tests/sessions_object_store.py | 108 +++++++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 14 deletions(-) diff --git a/src/sessions.rs b/src/sessions.rs index 6ab20e00..aaa42985 100644 --- a/src/sessions.rs +++ b/src/sessions.rs @@ -43,7 +43,8 @@ //! Every database of the process is kept warm in one page cache //! ([`page_cache`]), and keeps the checkpoints it outgrows Restate with in //! the object store `RESTATE_SQL_OBJECT_STORE` names, if any -//! ([`object_store`]). That store's requests are reqwest's, which need a +//! ([`object_store`]), past the share `RESTATE_SQL_L0_BYTES` leaves Restate +//! ([`state_options`]). That store's requests are reqwest's, which need a //! tokio runtime: they alone are polled inside one ([`InRuntime`]). use crate::explicit_recovery::{vm_error, PyExplicitRecoveryVM}; use bytes::Bytes; @@ -59,6 +60,7 @@ use restate_sdk_shared_core::explicit_recovery::ExplicitRecoveryVM; use restate_sdk_shared_core::sql::{self, Numeric, Value}; use restate_sdk_shared_core::state::{ self, BlobStore, KvStore, ObjectStoreBlobs, ObjectStoreL1, PageCache, PageCacheConfig, + StateOptions, }; use restate_sdk_shared_core::NotificationHandle; use restate_sdk_shared_core::Value as VmValue; @@ -644,28 +646,74 @@ async fn page_cache() -> io::Result> { /// The page cache's configuration, from the environment: `None` when it is off. fn cache_config() -> io::Result> { - let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); let off = var("RESTATE_SQL_CACHE").map(|v| v.to_ascii_lowercase()); if matches!(off.as_deref(), Some("off" | "0" | "false" | "no")) { return Ok(None); } - let size = |name: &str, default: usize| match var(name) { - Some(value) => state::parse_size(&value).ok_or_else(|| { - io::Error::other(format!( - "{name}={value}: not a size (bytes, or with KiB, MiB or GiB)" - )) - }), - None => Ok(default), - }; Ok(Some(PageCacheConfig { file: std::env::var_os("RESTATE_SQL_CACHE_FILE").map(std::path::PathBuf::from), ..PageCacheConfig::sized( - size("RESTATE_SQL_CACHE_MEMORY", 256 << 20)?, - size("RESTATE_SQL_CACHE_DISK", 1 << 30)?, + size("RESTATE_SQL_CACHE_MEMORY")?.unwrap_or(256 << 20), + size("RESTATE_SQL_CACHE_DISK")?.unwrap_or(1 << 30), ) })) } +/// The environment variable `name`, unless unset or empty. +fn var(name: &str) -> Option { + std::env::var(name).ok().filter(|v| !v.is_empty()) +} + +/// The size the environment variable `name` gives, if set: bytes, or with +/// KiB, MiB or GiB ([`state::parse_size`]). One that is not a size is an +/// error that says so. +fn size(name: &str) -> io::Result> { + let Some(value) = var(name) else { + return Ok(None); + }; + match state::parse_size(&value) { + Some(size) => Ok(Some(size)), + None => Err(io::Error::other(format!( + "{name}={value}: not a size (bytes, or with KiB, MiB or GiB)" + ))), + } +} + +/// How the process's databases flush: shared-core's defaults +/// ([`StateOptions::default`]), with L0's share from `RESTATE_SQL_L0_BYTES`, +/// read once: a database keeps its checkpoints' packs in the object's state +/// (L0) until they hold this many bytes, and the checkpoint after that moves +/// them, with its own, to the object store ([`StateOptions::l0_bytes`], 4 +/// MiB by default; bytes, or with KiB, MiB or GiB). `0` puts every +/// checkpoint's pack in the object store. Without an object store it changes +/// nothing: every pack stays in the state. A size that is not one fails +/// every open, with its message, as a page cache size that is not one does. +/// +/// It may differ from one process, or open, to the next: it never changes +/// what is stored, only where the next checkpoint puts its pack. Every +/// pack's name says its tier, which is where reads and garbage collection +/// look for it, so a lower one moves what L0 holds at the next checkpoint, +/// and a higher one keeps more packs in the state from then on; packs never +/// move back from the object store. +fn state_options() -> io::Result { + static L0_BYTES: Mutex> = Mutex::new(None); + let mut l0 = L0_BYTES + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + let defaults = StateOptions::default(); + let l0_bytes = match *l0 { + Some(bytes) => bytes, + None => { + let set = size("RESTATE_SQL_L0_BYTES")?; + *l0.insert(set.map_or(defaults.l0_bytes, |bytes| bytes as u64)) + } + }; + Ok(StateOptions { + l0_bytes, + ..defaults + }) +} + /// The process's object store, the one `RESTATE_SQL_OBJECT_STORE` names /// ([`ObjectStoreL1::from_env`]: `s3://bucket/path`, `gs://bucket/path`, /// `az://container/path` or `file:///a/directory`, with the provider's own @@ -724,7 +772,7 @@ fn in_runtime<'a, T: 'a>(mut future: BoxFuture<'a, T>) -> BoxFuture<'a, T> { } /// Open the database of `namespace`, kept warm in the process's page cache, -/// with its packs past L0 in the process's object store, if any ([`object_store`]), +/// with its packs past L0 ([`state_options`]) in the process's object store, if any ([`object_store`]), /// over the invocation's `vm` if given (with `name`, the key's database /// `name`), or else over the store behind `dispatch` (`lists_keys` if it has /// `keys`): see the module's doc. See [`sql::Open::reader`] for a `reader`. @@ -755,7 +803,8 @@ pub(crate) fn sql_open<'py>( }), }; answer(py, async move { - let mut open = sql::Database::open(store); + let options = state_options().map_err(|e| PyRuntimeError::new_err(e.to_string()))?; + let mut open = sql::Database::open(store).options(options); let cache = page_cache() .await .map_err(|e| PyRuntimeError::new_err(e.to_string()))?; diff --git a/tests/sessions_object_store.py b/tests/sessions_object_store.py index 4f136f31..03bac289 100644 --- a/tests/sessions_object_store.py +++ b/tests/sessions_object_store.py @@ -21,6 +21,8 @@ import sys from pathlib import Path +import pytest + SCENARIO = """ import asyncio, hashlib, os from pathlib import Path @@ -124,3 +126,109 @@ async def main(): """ ran = subprocess.run([sys.executable, "-c", scenario], env=env, capture_output=True, text=True, check=False) assert ran.returncode == 0, ran.stdout + ran.stderr + + +SMALL = """ +import asyncio, os, re +from pathlib import Path + +from restate.sessions._database import open +from sessions_database import Backend, listing + + +def files(path): + if not path.exists(): + return [] + return [str(f.relative_to(path)) for f in path.rglob("*") if f.is_file()] + + +def store(backend): + request = backend.request() + request.keys = listing(backend) + return request + + +async def main(): + packs = Path(os.environ["PACKS"]) / "_4cedger_2fsmall" + backend = Backend() + db = await open("Ledger/small", store(backend)) + await db.execute("CREATE TABLE blobs (id INTEGER PRIMARY KEY, data BLOB NOT NULL)") + await db.execute("CREATE TABLE counter (n INTEGER NOT NULL)") + await db.execute("INSERT INTO counter VALUES (0)") + # 2 MiB that does not compress, 64 KiB a commit, then small commits: a checkpoint at each 128 of them. + for i in range(32): + await db.execute("INSERT INTO blobs VALUES (?, ?)", [i, os.urandom(64 << 10)]) + for _ in range(300): + await db.execute("UPDATE counter SET n = n + 1") + await db.save() + + packs_in_restate = [k for k in backend.stored if not re.match(r"^v22/(head$|tail/|manifest/)", k)] + print("L1", len([f for f in files(packs) if f.startswith("l1/")])) + print("OTHER", len([f for f in files(packs) if not f.startswith("l1/")])) + print("RESTATE", len(packs_in_restate)) + + again = await open("Ledger/small", store(backend)) + assert await again.values("SELECT n FROM counter") == [[300]] + assert await again.values("SELECT count(*) FROM blobs") == [[32]] + +asyncio.run(main()) +""" + + +def small_database(tmp_path: Path, **variables: str) -> dict[str, int]: + """Run ``SMALL`` in a process of its own with ``variables`` (an empty value unsets one): the packs it left in the + object store's ``l1/``, elsewhere in it, and in Restate.""" + env = { + **os.environ, + "RESTATE_SQL_OBJECT_STORE": f"file://{tmp_path / 'packs'}", + "RESTATE_SQL_CACHE": "off", + "RESTATE_SQL_L0_BYTES": "", + "PACKS": str(tmp_path / "packs"), + "PYTHONPATH": os.pathsep.join(filter(None, [str(Path(__file__).parent), os.environ.get("PYTHONPATH")])), + **variables, + } + ran = subprocess.run([sys.executable, "-c", SMALL], env=env, capture_output=True, text=True, check=False) + assert ran.returncode == 0, ran.stdout + ran.stderr + return {name.lower(): int(count) for name, count in (line.split() for line in ran.stdout.splitlines())} + + +def test_l0_bytes_of_zero_keeps_every_pack_of_a_small_database_in_the_object_store(tmp_path: Path): + kept = small_database(tmp_path, RESTATE_SQL_L0_BYTES="0") + assert kept["l1"] > 0, kept + # Restate holds no pack, only the head, the tail and the manifests. + assert kept["other"] == 0 and kept["restate"] == 0, kept + + +def test_without_l0_bytes_a_small_database_keeps_its_packs_in_restate(tmp_path: Path): + kept = small_database(tmp_path) + assert kept["l1"] == 0 and kept["restate"] > 0, kept + + +@pytest.mark.parametrize("value,store", [("4MB", True), ("-1", True), ("1.5MiB", False)]) +def test_an_l0_bytes_that_is_not_a_size_fails_every_open_with_its_message(tmp_path: Path, value: str, store: bool): + # With an object store, or without one, where it would change nothing. + env = { + **os.environ, + "RESTATE_SQL_L0_BYTES": value, + "RESTATE_SQL_OBJECT_STORE": f"file://{tmp_path}" if store else "", + "PYTHONPATH": os.pathsep.join(filter(None, [str(Path(__file__).parent), os.environ.get("PYTHONPATH")])), + } + scenario = """ +import asyncio, os +from restate.sessions._database import open +from sessions_database import Backend + +async def main(): + expected = f"RESTATE_SQL_L0_BYTES={os.environ['RESTATE_SQL_L0_BYTES']}: not a size (bytes, or with KiB, MiB or GiB)" + for _ in range(2): + try: + await open("Ledger/c", Backend().request()) + except Exception as error: + assert expected in str(error), error + else: + raise AssertionError("the open succeeded") + +asyncio.run(main()) +""" + ran = subprocess.run([sys.executable, "-c", scenario], env=env, capture_output=True, text=True, check=False) + assert ran.returncode == 0, ran.stdout + ran.stderr From 8753f18c627bb1fa8d97c77b92a9d3ac7a790cb5 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:44:27 +0100 Subject: [PATCH 08/13] Agents: the records of a Restate call ride the commit that stores its result Sessions: ride_commit and flush_riders, internal. A write that rides the next commit of a database, and an urgent one that is written alone once no commit has started within a number of event-loop iterations. --- docs/agents/conversation.md | 9 + python/restate/agents/_calls.py | 61 ++++- python/restate/agents/_turn.py | 9 +- python/restate/sessions/_session.py | 217 +++++++++++++-- python/restate/sessions/internal.py | 6 +- tests/agents_calls_ride.py | 216 +++++++++++++++ tests/agents_commits.py | 206 +++++++++++--- tests/sessions_ride.py | 407 ++++++++++++++++++++++++++++ 8 files changed, 1057 insertions(+), 74 deletions(-) create mode 100644 tests/agents_calls_ride.py create mode 100644 tests/sessions_ride.py diff --git a/docs/agents/conversation.md b/docs/agents/conversation.md index 4cc12e23..3df753b5 100644 --- a/docs/agents/conversation.md +++ b/docs/agents/conversation.md @@ -543,6 +543,15 @@ invocation (the next invocation's first call replaces it): again under the same id; a new call with the same input (the model asking again after the first's answer) waits anew, and never gets an earlier call's approval or denial. +- **When it is written.** Only the record of a new call commits of its own, before the call is made. That a call + returned (`done`) rides a commit that is under way or starts at once: the one that stores the call's result, + so that the transcript never has a result of a call that is not recorded as returned. If none does (a slow + tool of the round still runs, another call waits), it is written in a transaction of its own once no commit has + started for `URGENT_HOPS` event-loop iterations, so it is never left unrecorded for long. That a record is + forgotten rides the next commit, whenever it comes, and a turn's end writes what is still pending. A crash in + the few moments before the return is written reads the call as one that did not return: it is made again under + the same key, and a stopped turn that another invocation closes reports it as cut off. This is + `restate.sessions.internal.ride_commit`. - **Forgetting.** After each write of steps that commits (once, before the publish an agent's turn makes there, and in a plain session object's turn too, which publishes nothing) and before each tool call, a record whose diff --git a/python/restate/agents/_calls.py b/python/restate/agents/_calls.py index 007312b5..821d66be 100644 --- a/python/restate/agents/_calls.py +++ b/python/restate/agents/_calls.py @@ -30,6 +30,15 @@ turn's steps that commits, and before each tool call). An error in the transcript does not count as the result, unless the call itself returned that error. +Only the record of a new call commits of its own, before the call is made. That a call answered rides a commit +that is under way or starts at once (``ride_commit``): the one that stores the call's result, so that the +transcript never has a result of a call that is not recorded as answered. If none does (a slow tool of the round +is still running, another call waits), it is written on its own once no transaction has started for a while (see +``URGENT_HOPS``), so it is never left unrecorded for long. That its record is forgotten rides the next commit, +whenever it comes. A crash in the few moments before an answer is written reads the call as one that did not +answer, as a crash just before a commit of its own would have: it is made again, under the same key, and cut off +for a stopped turn that another invocation closes. + A framework's own wait (``wait_for``) is its tool call's alone: the framework stored the tool call before it waits, so a retried attempt waits again under the same id, and a new call with the same input waits anew. An approval that a @@ -52,8 +61,8 @@ from dataclasses import dataclass, field from restate.agents._common import flush_held -from restate.sessions import SessionContext -from restate.sessions.internal import Schema, ScopeKey +from restate.sessions import SessionContext, Transaction +from restate.sessions.internal import Schema, ScopeKey, flush_riders, ride_commit SCHEMA = Schema( "restate-agents.calls", @@ -98,17 +107,41 @@ class _Calls: calls: list[_Call] = field(default_factory=list[_Call]) +_UPSERT = "INSERT OR REPLACE INTO restate_agent_calls (row, invocation, calls) VALUES (0, ?, ?)" + +_RIDER = "restate-agents.calls" +"""The slot of the calls' write that rides the next commit (``_ride``).""" + + async def _store(ctx: SessionContext, state: _Calls) -> None: """Store ``state``; it is committed before the call it records is made. The rows the conversation holds back are written first: the call outlives the attempt, and what led to it must - too. + too. It is the whole row: what rides the next commit is written, and no longer pending. """ await flush_held(ctx) - await ctx.db.execute( - "INSERT OR REPLACE INTO restate_agent_calls (row, invocation, calls) VALUES (0, ?, ?)", - [state.invocation, json.dumps(state.calls)], - ) + ride_commit(ctx.db, _RIDER, None) + await ctx.db.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) + + +async def _ride(ctx: SessionContext, state: _Calls, urgent: bool = False) -> None: + """Store ``state`` with the next commit of the database, rather than commit it, as it is then. + + A later change replaces it, and the latest state is written. An ``urgent`` one (an answer) is written on its + own unless a commit starts soon to write it; one that is pending and urgent stays so. A database that cannot + ride (a view's) commits it at once. + """ + + async def write(tx: Transaction) -> None: + await tx.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) + + if not ride_commit(ctx.db, _RIDER, write, urgent=urgent): + await _store(ctx, state) + + +async def flush_calls(ctx: SessionContext) -> None: + """Write what rides the next commit (``_ride``) now, if it is pending: at the end of a turn, when no commit follows.""" + await flush_riders(ctx.db) async def _load(ctx: SessionContext, invocation: str) -> _Calls: @@ -174,11 +207,19 @@ class Call: _call: _Call async def answered(self, failed: str | None = None) -> None: - """Record that the call returned, with ``failed`` if it returned a terminal error.""" + """Record that the call returned, with ``failed`` if it returned a terminal error. + + It is kept until the transcript has the call's result. It rides the commit that stores the result, and is + otherwise written on its own soon (``_ride``): a call that answered must not stay unrecorded while + something else runs (a slow tool of the same round, a call that waits for a signal). A crash before it is + written reads the call as one that did not answer: made again under the same key, and cut off for a stopped + turn that another invocation closes (``outcomes`` reads the stored row; the attempt's own turn reads its + state). + """ self._call["done"] = True if failed is not None: self._call["failed"] = failed - await _store(self._ctx, self._state) + await _ride(self._ctx, self._state, urgent=True) async def call_of( @@ -230,7 +271,7 @@ async def settle(ctx: SessionContext, stored: Callable[[str, str | None], bool]) if len(kept) == len(state.calls): return state.calls = kept - await _store(ctx, state) + await _ride(ctx, state) async def outcomes( diff --git a/python/restate/agents/_turn.py b/python/restate/agents/_turn.py index cb692913..dd6460c0 100644 --- a/python/restate/agents/_turn.py +++ b/python/restate/agents/_turn.py @@ -35,7 +35,7 @@ from restate.agents import _signals from restate.agents._api import AgentContext, Answering, Published, Steer -from restate.agents._calls import settle +from restate.agents._calls import flush_calls, settle from restate.agents._common import ( BUDGET, WINDOW, @@ -371,6 +371,13 @@ async def answering(ctx: SessionContext, stored: Stored, work: Callable[[], Awai _ANSWERING.set(ctx, outer) else: _ANSWERING.delete(ctx) + # What rides the next commit is written if none is to come. After a turn that answered, the commit that + # stored its answer wrote it, and this does nothing. A failed attempt's own error is not this write's. + if failed: + with contextlib.suppress(BaseException): + await flush_calls(ctx) + else: + await flush_calls(ctx) def _now() -> str: diff --git a/python/restate/sessions/_session.py b/python/restate/sessions/_session.py index b5ae9dd8..51dd5e24 100644 --- a/python/restate/sessions/_session.py +++ b/python/restate/sessions/_session.py @@ -391,6 +391,14 @@ async def query_columns(self, sql: str, params: Sequence[SqlParam] | None = None self._attempt.asked() return await self._attempt.call(lambda db: db.query_columns(sql, params)) + async def execute(self, sql: str, params: Sequence[SqlParam] | None = None) -> None: + # A write while a rider is pending is the transaction that carries it (see ``ride_commit``). + if self._attempt.riding: + async with self._attempt.transaction() as tx: + await tx.execute(sql, params) + else: + await super().execute(sql, params) + def transaction(self) -> typing.AsyncContextManager[Transaction]: return self._attempt.transaction() @@ -450,6 +458,50 @@ def database(db: Database, name: str) -> Database: return attempt.database(name) +Rider = Callable[[Transaction], Awaitable[None]] +"""A write that rides the next commit of a database, in that commit's transaction.""" + +URGENT_HOPS = 64 +"""How many event-loop iterations an urgent rider waits for a transaction to start before it is written alone. + +A framework asks for the commit that stores a tool's result a few iterations after the tool's call answered, with +no I/O between (3 to 23 were measured, the most in the OpenAI Agents SDK); a count of iterations, unlike a time, does +not change with the load of the process. A transaction that does not start within it is not coming soon (another +tool of the round still runs), and an answer must not stay unrecorded for as long.""" + + +def ride_commit(db: Database, slot: str, write: Rider | None, *, urgent: bool = False) -> bool: + """Have ``write`` run in the next transaction of ``db`` that commits, before its commit, rather than commit on its own. + + This is for bookkeeping that must be stored with the next write, not before it. A write by ``db.execute`` + outside a transaction, made while a rider is pending, is that transaction; a read (``get``, ``values``, + ``query``) is not, and writes nothing. A transaction that rolls back leaves the rider pending, and so does + one that ends the handler before it commits: ``flush_riders`` writes what is left. Nothing rides after the + attempt ended, and what is pending is dropped with it. + + A database has one rider per ``slot``: a later one replaces the earlier, and ``None`` clears it. A rider + registered while a commit that runs the earlier one is under way is for the commit after. + + An ``urgent`` rider waits only for a transaction that is under way: if none is asked for within + ``URGENT_HOPS`` event-loop iterations of its registration (or of the end of one that left it pending), it is + written in a transaction of its own. A write of its own that fails is not retried and raises nothing: the rider + stays pending for the next commit or ``flush_riders``. A rider that replaces an urgent one stays urgent. + + Returns: + ``False``, registering nothing, for a database that cannot ride (a view's, or one that is not a handler's + ``ctx.db``): the caller writes at once. + """ + attempt = _ATTEMPT.of(db) + return attempt.ride(slot, write, urgent) if attempt is not None else False + + +async def flush_riders(db: Database) -> None: + """Write what is pending (see ``ride_commit``) in a transaction of its own: nothing, if nothing is.""" + attempt = _ATTEMPT.of(db) + if attempt is not None: + await attempt.flush_riders() + + async def reset(tx: Transaction) -> None: """Empty the key's database inside the transaction ``tx``. @@ -540,6 +592,14 @@ async def close() -> None: task.add_done_callback(lambda t: t.cancelled() or t.exception()) +@dataclass +class _Pending: + """A rider that is pending, and whether it may not wait for a commit that is not under way.""" + + write: Rider + urgent: bool + + class Attempt: """The SQL session of one attempt. @@ -563,6 +623,17 @@ def __init__(self, host: SqlHost, config: ObjectConfig | None = None, name: str # The schemas fully applied to this attempt's database, by name. self._ensured: dict[str, Schema] = {} self._ended: bool = False + # The writes that ride the next commit, by slot (see ``ride_commit``). + self._riders: dict[str, _Pending] = {} + # The transactions asked for and not finished: one that is under way writes the riders. + self._active: int = 0 + # The next hop of the chain that counts the iterations an urgent rider waits, and the hops counted so far. + self._hop: asyncio.Handle | None = None + self._hops: int = 0 + # The transaction that writes an urgent rider alone, while it runs. + self._lone: asyncio.Task[None] | None = None + # Set when the handler has ended: nothing rides from then on. + self._closing: bool = False self.db: AttemptDatabase = AttemptDatabase(self) """``ctx.db``.""" ensuring(self.db, self._ensure) @@ -595,6 +666,77 @@ def asked(self) -> None: if take is not None and take(): raise TerminalError("cancelled", 409) + @property + def riding(self) -> bool: + """Whether a rider is pending.""" + return bool(self._riders) + + def ride(self, slot: str, write: Rider | None, urgent: bool) -> bool: + """Register the rider of ``slot`` (see ``ride_commit``); ``False`` if this database cannot ride.""" + if self._host.shared or self._ended or self._closing: + return False + if write is None: + self._riders.pop(slot, None) + else: + earlier = self._riders.get(slot) + self._riders[slot] = _Pending(write, urgent or (earlier is not None and earlier.urgent)) + self._arm() + return True + + def _arm(self) -> None: + """Start counting the iterations an urgent rider waits, if one is pending and nothing is counting.""" + if self._hop is not None or self._ended or self._closing: + return + if not any(pending.urgent for pending in self._riders.values()): + return + self._hops = 0 + self._hop = asyncio.get_running_loop().call_soon(self._step) + + def _stop_counting(self) -> None: + if self._hop is not None: + self._hop.cancel() + self._hop = None + + def _step(self) -> None: + """One iteration of the loop has passed: write the urgent riders alone once enough have, with nothing under way.""" + self._hop = None + # A transaction under way writes them, or counts again as it ends. + if self._ended or self._closing or self._active > 0: + return + if not any(pending.urgent for pending in self._riders.values()): + return + self._hops += 1 + if self._hops < URGENT_HOPS: + self._hop = asyncio.get_running_loop().call_soon(self._step) + return + self._lone = asyncio.ensure_future(self._alone()) + + async def _alone(self) -> None: + """Write the riders in a transaction of their own, which is not the handler's to ask for (see ``asked``). + + The handler's cancellation is not for it: it stays owed to the handler's next call. A failure leaves the + riders pending for the next commit or ``flush_riders`` and is not tried again by a timer; it raises + nothing, as nothing awaits this. + """ + try: + try: + async with self._transacted(rearm=False): + pass + except asyncio.CancelledError: + raise + except BaseException: # pylint: disable=broad-exception-caught + return + # After a success, a rider that came while it committed is counted now. + self._arm() + finally: + self._lone = None + + async def flush_riders(self) -> None: + """Write what is pending in a transaction of its own (see ``flush_riders``).""" + if self._riders: + async with self.transaction(): + pass + def database(self, name: str) -> Database: """Return the key's separate database ``name`` for this attempt (see ``database``).""" if self._ended: @@ -620,6 +762,12 @@ async def end(self, error: BaseException | None) -> None: Re-raises ``error``, the handler's exception, if there is one; otherwise raises any failure to end a session. """ + # What is pending is dropped, and nothing counts or writes from here on. + self._closing = True + self._riders.clear() + self._stop_counting() + if self._lone is not None: + await asyncio.wait({self._lone}) failures: list[BaseException] = [] for other in self._databases.values(): try: @@ -662,28 +810,55 @@ async def transaction(self) -> AsyncGenerator[AttemptTransaction, None]: """ # Before the session opens or the transaction begins: see ``asked``. self.asked() - outgoing: Outgoing | None = None - session = self._current() + async with self._transacted() as tx: + yield tx + + @asynccontextmanager + async def _transacted(self, rearm: bool = True) -> AsyncGenerator[AttemptTransaction, None]: + """``transaction`` without ``asked``: it counts as under way until it ends, and runs the pending riders. + + They are written after the body, which may have registered one (a transaction held open for more work), + and before the commit; one that is registered since is for the next commit. What it leaves pending (it + rolled back, or the rider came after it ran them) is counted again as it ends, if ``rearm``. + """ + self._active += 1 try: - db = await session.ready - async with db.transaction() as handle: - sends = _Sends() if self._has_outbox else None - # A view's writes stay in its own session, so there is nothing to reset. - tx = AttemptTransaction(handle, sends.record if sends is not None else _refused_send) - if not self._host.shared: - _RESET.on(tx, lambda: self._reset(handle)) - try: - yield tx - finally: - outgoing = sends.close() if sends is not None else None - if self._has_outbox: - await self._commit_outbox(handle, outgoing) - except BaseException: - if session.ended: - session.retired = True - raise - if outgoing is not None: - await self.call(self._flush) + outgoing: Outgoing | None = None + # The riders this transaction wrote: pending until it has committed. + rode: list[tuple[str, _Pending]] = [] + session = self._current() + try: + db = await session.ready + async with db.transaction() as handle: + sends = _Sends() if self._has_outbox else None + # A view's writes stay in its own session, so there is nothing to reset. + tx = AttemptTransaction(handle, sends.record if sends is not None else _refused_send) + if not self._host.shared: + _RESET.on(tx, lambda: self._reset(handle)) + try: + yield tx + finally: + outgoing = sends.close() if sends is not None else None + if self._riders: + rode = list(self._riders.items()) + for _, pending in rode: + await pending.write(tx) + if self._has_outbox: + await self._commit_outbox(handle, outgoing) + except BaseException: + if session.ended: + session.retired = True + raise + for slot, pending in rode: + if self._riders.get(slot) is pending: + del self._riders[slot] + if outgoing is not None: + await self.call(self._flush) + finally: + self._active -= 1 + if rearm: + self._stop_counting() + self._arm() async def _commit_outbox(self, handle: ConnectionTransaction, outgoing: Outgoing | None) -> None: """Write the outbox in ``handle``: the unstored committed sends, plus ``outgoing``, which the commit makes.""" diff --git a/python/restate/sessions/internal.py b/python/restate/sessions/internal.py index fdd4a07c..eaf04f0c 100644 --- a/python/restate/sessions/internal.py +++ b/python/restate/sessions/internal.py @@ -28,6 +28,8 @@ - ``start`` and ``attach_invocation``: send, keeping the invocation id, and wait for that invocation's result; a library runs a workflow this way (a send to it again, after a crash, starts nothing: the same run). +- ``ride_commit`` and ``flush_riders``: a write that rides the next commit of a database instead of committing + on its own, for bookkeeping that is stored with the next write (the agents' record of a call that answered). - ``ScopeKey`` and ``definition_of``: state a library keeps per attempt, and the object an attempt belongs to. - ``invoke``, ``SqlHost`` and ``ObjectConfig``: run one attempt of a handler @@ -47,7 +49,7 @@ ) from restate.sessions._schema import Schema, ensure_schemas from restate.sessions._scope import ScopeKey -from restate.sessions._session import ObjectConfig, SqlHost, database, reset +from restate.sessions._session import ObjectConfig, SqlHost, database, flush_riders, reset, ride_commit __all__ = [ "Annotation", @@ -62,8 +64,10 @@ "database", "definition_of", "ensure_schemas", + "flush_riders", "hide_entries", "invoke", "reset", + "ride_commit", "start", ] diff --git a/tests/agents_calls_ride.py b/tests/agents_calls_ride.py new file mode 100644 index 00000000..4c5c90ef --- /dev/null +++ b/tests/agents_calls_ride.py @@ -0,0 +1,216 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""The call records of Restate tools ride the commits that happen anyway (``_calls.py``): that a call answered, and that +its record is forgotten, are stored with the commit of the call's result, not by commits of their own. What that +must keep: a stopped turn closed by another invocation reports a call that answered as having happened, and a crash +at any point of the turn makes the call once.""" + +# pylint: disable=missing-function-docstring,missing-class-docstring,import-error,import-outside-toplevel + +import asyncio +import typing +from collections.abc import AsyncGenerator +from dataclasses import dataclass +from typing import Any + +import pytest + +from restate import sessions +from restate.agents._common import ENDED, RETURNED_UNRECORDED +from restate.agents._conversation import Conversation +from restate.agents._conversation import settle as settle_turn +from restate.agents._tools import Tool +from restate.sessions.internal import invoke +from agents_commits import ( + SHAPE, + SLOW, + TURN, + Counting, + adk_ask, + held, + restated_lookup, + slow_tool, + until_done, +) +from sessions_database import Backend +from sessions_object import Host, request + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@dataclass +class Watched(Counting): + """A counting host that tells a test when a call is made and when a commit has stored a text, and crashes then.""" + + on_call: typing.Callable[["Watched"], None] | None = None + crash_once_stored: str | None = None + + def generic_call(self, service, handler, arg, key=None, idempotency_key=None, headers=None, name=None): + if handler == "status" and self.on_call is not None: + self.on_call(self) + return super().generic_call(service, handler, arg, key, idempotency_key, headers, name) + + async def sync(self) -> None: + await super().sync() + if self.crash_once_stored is not None: + text, _ = await held(self.committed[-1]) + if self.crash_once_stored in text: + self.crash_once_stored = None + self.crash_after(0) + + +# --- A turn killed while a slow tool runs ---------------------------------------------------------------------- + + +async def read_results(backend: Backend) -> list[tuple[str, str]]: + """The tool results of the key's transcript, in order: (tool call id, output).""" + from restate.agents.adk._agent import _Items # pyright: ignore[reportPrivateUsage] + + reader = sessions.SessionObject("asker") + + @reader.handler + async def read(ctx: sessions.SessionContext) -> list[tuple[str, str]]: + conversation = await Conversation.load(ctx.db, _Items("assistant"), complete=True) + return [(r.id, r.output) for e in conversation.entries for r in e.results] + + return await invoke(reader, "read", Host(backend, service="asker"), request()) + + +async def test_a_turn_killed_while_a_slow_tool_runs_is_closed_by_another_invocation_with_the_call_reported_done(): + from restate.agents.adk._agent import _Items # pyright: ignore[reportPrivateUsage] + + SHAPE[0] = "parallel" + try: + ask = await adk_ask() + asker = sessions.SessionObject("asker") + + @asker.handler + async def run(ctx: sessions.SessionContext, text: str) -> str: + return await ask(ctx, text, [restated_lookup, slow_tool]) + + @asker.handler(name="settle") + async def settling(ctx: sessions.SessionContext, invocation_id: str) -> bool: + return await settle_turn(ctx, _Items("assistant"), invocation_id) + + TURN[0] = "killed" + SLOW[:] = [asyncio.Event()] + gate = asyncio.Event() + backend, req = Backend(), request() + host = Counting(backend, service="asker", answers={"publish": b'{"revision": 1}'}, gate=gate) + turn = asyncio.ensure_future(invoke(asker, "run", host, req, "killed")) + try: + # Call 1 answered while the slow tool runs: its answer is written on its own, at once. + await until_done(host, {0}) + # The process dies here: nothing more is stored, and the slow tool never ends. + host.crash_after(0) + finally: + turn.cancel() + await asyncio.gather(turn, return_exceptions=True) + other = Host(backend, service="asker", answers={"publish": b'{"revision": 1}'}) + assert await invoke(asker, "settle", other, request(), req.id) is True + results = dict(await read_results(backend)) + assert results["call-killed-0"] == RETURNED_UNRECORDED + assert results["call-killed-1"] == ENDED + assert results["call-killed-2"] == ENDED + finally: + SHAPE[0] = "serial" + + +# --- A crash --------------------------------------------------------------------------------------------------- + + +async def crashing_ask(rounds: int) -> Any: + """ADK's agent whose model asks for ``rounds`` calls of the same tool, one after each result, as the transcript + says (so that every attempt asks the same), and then answers.""" + from google.adk.models import BaseLlm + from google.adk.models.llm_request import LlmRequest + from google.adk.models.llm_response import LlmResponse + from google.genai import types + + from restate.agents import adk + + class ByResults(BaseLlm): + model: str = "scripted" + + async def generate_content_async( + self, llm_request: LlmRequest, stream: bool = False + ) -> AsyncGenerator[LlmResponse, None]: + results = sum(1 for c in llm_request.contents for p in c.parts or [] if p.function_response) + if results >= rounds: + part = types.Part(text="done") + else: + call = types.FunctionCall(id=f"call_{results + 1}", name="lookup", args={"key": "eu", "input": "o1"}) + part = types.Part(function_call=call) + yield LlmResponse(content=types.Content(role="model", parts=[part])) + + async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: + return await adk.prompt(ctx, text, model=ByResults(), tools=[*tools]) + + return ask + + +def keys_of(*hosts: Host) -> list[str | None]: + return [c[4] for host in hosts for c in host.calls if c[1] == "status"] + + +async def records_of(backend: Backend) -> list[dict[str, Any]]: + return (await held(dict(backend.stored)))[1] + + +async def test_a_crash_after_a_call_answered_and_before_its_result_is_stored_makes_it_again_under_the_same_key(): + ask = await crashing_ask(1) + asker = sessions.SessionObject("asker") + + @asker.handler + async def run(ctx: sessions.SessionContext, text: str) -> str: + return await ask(ctx, text, [restated_lookup]) + + TURN[0] = "crash" + backend, req = Backend(), request() + published = {"publish": b'{"revision": 1}'} + # The process dies as the call returns: the commit that would store its answer and its result fails. + first = Watched(backend, service="asker", answers=dict(published), on_call=lambda host: host.crash_after(0)) + with pytest.raises(Exception): + await invoke(asker, "run", first, req, "go") + assert not any(r.get("done") for r in await records_of(backend)) + retry = Watched(backend, service="asker", answers=dict(published)) + assert await invoke(asker, "run", retry, req, "go") == "done" + assert keys_of(first, retry) == [f"{req.id}:call_1", f"{req.id}:call_1"] + assert [i for i, _ in await read_results(backend)] == ["call_1"] + + +async def test_a_crash_right_after_a_result_is_stored_forgets_the_record_and_a_later_identical_call_is_a_new_call(): + ask = await crashing_ask(2) + asker = sessions.SessionObject("asker") + + @asker.handler + async def run(ctx: sessions.SessionContext, text: str) -> str: + return await ask(ctx, text, [restated_lookup]) + + TURN[0] = "crash" + backend, req = Backend(), request() + published = {"publish": b'{"revision": 1}'} + # The commit that stores the result is the crash's last: the next write fails. + first = Watched(backend, service="asker", answers=dict(published), crash_once_stored="shipped o1") + with pytest.raises(Exception): + await invoke(asker, "run", first, req, "go") + # Stored with the result: the call answered, and its forgetting has not been written. + assert [i for i, _ in await read_results(backend)] == ["call_1"] + records = await records_of(backend) + assert [(r["ids"], r.get("done")) for r in records] == [(["call_1"], True)] + retry = Watched(backend, service="asker", answers=dict(published)) + assert await invoke(asker, "run", retry, req, "go") == "done" + # The same tool and input again, under a new id: not the call the model has the result of. + assert keys_of(first, retry) == [f"{req.id}:call_1", f"{req.id}:call_2"] + assert [i for i, _ in await read_results(backend)] == ["call_1", "call_2"] diff --git a/tests/agents_commits.py b/tests/agents_commits.py index 0003c52a..53a269da 100644 --- a/tests/agents_commits.py +++ b/tests/agents_commits.py @@ -17,6 +17,7 @@ # pylint: disable=missing-function-docstring,missing-class-docstring +import asyncio import json import typing from collections.abc import Awaitable, Callable @@ -31,7 +32,7 @@ from restate.agents._tools import Tool from restate.sessions.internal import invoke from sessions_database import Backend # pylint: disable=import-error -from sessions_object import Host, request # pylint: disable=import-error +from sessions_object import Answer, Host, request # pylint: disable=import-error @pytest.fixture @@ -39,10 +40,10 @@ def anyio_backend(): return "asyncio" -EXTRA_COMMITS_PER_RESTATE_CALL = 3 -"""What each Restate tool call costs in commits, over the same call of a plain tool. The call's record, in -``restate_agent_calls``, is committed: (1) before the call is made, (2) when it answered, and (3) when the record is -forgotten, after the framework stored the tool's result.""" +EXTRA_COMMITS_PER_RESTATE_CALL = 1 +"""What each Restate tool call costs in commits, over the same call of a plain tool. Only the call's record, in +``restate_agent_calls``, commits of its own, before the call is made. That the call answered rides the commit that +stores the tool's result, and so does that the record is forgotten, after the framework stored it.""" REQUESTS = 4 TOOL_CALLS = 3 @@ -105,6 +106,50 @@ def arguments_of(index: int) -> dict[str, str]: return {"key": "eu", "input": order_of(index)} +SHAPE: list[str] = ["serial"] +"""The model's plan: ``serial`` is a tool call after each of the first ``TOOL_CALLS`` requests, ``parallel`` is one +round of two Restate calls and a slow plain tool, and then the answer.""" + + +def round_of(n: int) -> list[tuple[str, str, dict[str, str]]] | None: + """The tool calls (id, tool, arguments) that the model's ``n``-th request makes, or ``None`` if it answers.""" + if SHAPE[0] == "serial": + return [(call_id(n), "lookup", arguments_of(n))] if n < TOOL_CALLS else None + if n == 0: + return [ + (call_id(0), "lookup", arguments_of(0)), + (call_id(1), "lookup", arguments_of(1)), + (call_id(2), "slow", {}), + ] + return None + + +SLOW: list[asyncio.Event] = [] +"""The slow plain tool of the parallel round waits for it.""" + + +@tool(name="slow") +async def slow_tool() -> str: + """A plain tool that runs until the test says so.""" + await SLOW[0].wait() + return "slow done" + + +class Gated(Answer): + """A call's result, once ``gate`` is set.""" + + def __init__(self, value: bytes, gate: asyncio.Event) -> None: + super().__init__(value) + self.gate = gate + + def __await__(self): + async def value() -> bytes: + await self.gate.wait() + return self.value + + return value().__await__() + + @dataclass class Counting(Host): """A host that counts its syncs (each a commit), keeps what each committed, and answers the faked callee.""" @@ -117,10 +162,16 @@ async def sync(self) -> None: self.syncs += 1 self.committed.append(dict(self.backend.stored)) + gate: asyncio.Event | None = None + """When set, the call about the second order answers once it is.""" + def generic_call(self, service, handler, arg, key=None, idempotency_key=None, headers=None, name=None): if handler == "status": self.answers[handler] = json.dumps(result_of(json.loads(arg))).encode() - return super().generic_call(service, handler, arg, key, idempotency_key, headers, name) + answer = super().generic_call(service, handler, arg, key, idempotency_key, headers, name) + if self.gate is not None and order_of(1) in arg.decode(): + return Gated(self.answers[handler], self.gate) + return answer @dataclass @@ -184,16 +235,16 @@ async def read(ctx: sessions.SessionContext) -> tuple[str, list[dict[str, Any]]] return await invoke(reader, "read", Host(copy, service="asker"), request()) -async def assert_no_result_ahead_of_its_record(measured: Measured) -> None: +async def assert_no_result_ahead_of_its_record(measured: Measured, calls: int = TOOL_CALLS) -> None: """At no commit does the committed state hold a tool's real result while that call's record is not marked done. A call whose record was forgotten (after it was marked done) may hold its result.""" done: set[int] = set() - seen_result = [False] * TOOL_CALLS + seen_result = [False] * calls for committed in measured.committed: text, records = await held(committed) - present = {i for i in range(TOOL_CALLS) for r in records if f'"{order_of(i)}"' in r["input"]} - for i in range(TOOL_CALLS): + present = {i for i in range(calls) for r in records if f'"{order_of(i)}"' in r["input"]} + for i in range(calls): for r in records: if f'"{order_of(i)}"' in r["input"] and r.get("done"): done.add(i) @@ -203,7 +254,7 @@ async def assert_no_result_ahead_of_its_record(measured: Measured) -> None: assert i not in present or i in done # The check is not vacuous: every result was committed, and each record was seen done. assert all(seen_result) - assert done == set(range(TOOL_CALLS)) + assert done == set(range(calls)) async def assert_costs(name: str, ask: Ask) -> None: @@ -223,7 +274,7 @@ async def assert_costs(name: str, ask: Ask) -> None: # --- Each framework's turn ----------------------------------------------------------------------- -async def test_adk_turn(): +async def adk_ask() -> Ask: pytest.importorskip("google.adk") from collections.abc import AsyncGenerator # pylint: disable=import-outside-toplevel @@ -243,19 +294,21 @@ async def generate_content_async( ) -> AsyncGenerator[LlmResponse, None]: n = len(self.asked) self.asked.append(n) - if n < TOOL_CALLS: - part = types.Part(function_call=types.FunctionCall(id=call_id(n), name="lookup", args=arguments_of(n))) - else: - part = types.Part(text="done") - yield LlmResponse(content=types.Content(role="model", parts=[part])) + planned = round_of(n) + parts = ( + [types.Part(function_call=types.FunctionCall(id=i, name=name, args=args)) for i, name, args in planned] + if planned + else [types.Part(text="done")] + ) + yield LlmResponse(content=types.Content(role="model", parts=parts)) async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: return await adk.prompt(ctx, text, model=Scripted(asked=[]), tools=[*tools]) - await assert_costs("adk", ask) + return ask -async def test_langgraph_agent_turn(): +async def langgraph_agent_ask() -> Ask: pytest.importorskip("langgraph") from langchain_core.language_models import BaseChatModel # pylint: disable=import-outside-toplevel from langchain_core.messages import AIMessage, BaseMessage # pylint: disable=import-outside-toplevel @@ -279,8 +332,9 @@ def _generate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> C async def _agenerate(self, messages: list[BaseMessage], *args: Any, **kwargs: Any) -> ChatResult: n = len(self.asked) self.asked.append(n) - if n < TOOL_CALLS: - reply = AIMessage("", tool_calls=[{"id": call_id(n), "name": "lookup", "args": arguments_of(n)}]) + planned = round_of(n) + if planned: + reply = AIMessage("", tool_calls=[{"id": i, "name": name, "args": args} for i, name, args in planned]) else: reply = AIMessage("done") return ChatResult(generations=[ChatGeneration(message=reply)]) @@ -288,10 +342,10 @@ async def _agenerate(self, messages: list[BaseMessage], *args: Any, **kwargs: An async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: return await langgraph.prompt(ctx, text, model=Scripted(asked=[]), tools=[*tools]) - await assert_costs("langgraph agent", ask) + return ask -async def test_langgraph_graph_turn(): +async def langgraph_graph_ask() -> Ask: pytest.importorskip("langgraph") from langchain_core.messages import AIMessage # pylint: disable=import-outside-toplevel from langgraph.graph import END, START, MessagesState, StateGraph # pylint: disable=import-outside-toplevel @@ -305,8 +359,9 @@ async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str async def model(state: MessagesState) -> dict[str, Any]: n = len(asked) asked.append(n) - if n < TOOL_CALLS: - reply = AIMessage("", tool_calls=[{"id": call_id(n), "name": "lookup", "args": arguments_of(n)}]) + planned = round_of(n) + if planned: + reply = AIMessage("", tool_calls=[{"id": i, "name": name, "args": args} for i, name, args in planned]) else: reply = AIMessage("done") return {"messages": [reply]} @@ -323,10 +378,10 @@ def route(state: MessagesState) -> str: builder.add_edge("tools", "model") return await langgraph.prompt(ctx, text, graph=builder) - await assert_costs("langgraph graph", ask) + return ask -async def test_openai_turn(): +async def openai_ask() -> Ask: pytest.importorskip("agents") from agents import Model, ModelResponse, Usage, set_tracing_disabled # pylint: disable=import-outside-toplevel from openai.types.responses import ( # pylint: disable=import-outside-toplevel @@ -346,17 +401,18 @@ def __init__(self) -> None: async def get_response(self, *args: Any, **kwargs: Any) -> ModelResponse: n = self.asked self.asked += 1 - output: Any - if n < TOOL_CALLS: - output = ResponseFunctionToolCall( - type="function_call", call_id=call_id(n), name="lookup", arguments=json.dumps(arguments_of(n)) - ) + output: list[Any] + if planned := round_of(n): + output = [ + ResponseFunctionToolCall(type="function_call", call_id=i, name=name, arguments=json.dumps(args)) + for i, name, args in planned + ] else: text: list[Any] = [ResponseOutputText(type="output_text", text="done", annotations=[])] - output = ResponseOutputMessage( - id="msg", type="message", role="assistant", status="completed", content=text - ) - return ModelResponse(output=[output], usage=Usage(), response_id=None) + output = [ + ResponseOutputMessage(id="msg", type="message", role="assistant", status="completed", content=text) + ] + return ModelResponse(output=output, usage=Usage(), response_id=None) def stream_response(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError @@ -364,10 +420,10 @@ def stream_response(self, *args: Any, **kwargs: Any) -> Any: async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str: return await openai.prompt(ctx, text, model=Scripted(), tools=[*tools]) - await assert_costs("openai", ask) + return ask -async def test_pydantic_ai_turn(): +async def pydantic_ai_ask() -> Ask: pytest.importorskip("pydantic_ai") from pydantic_ai.messages import ( # pylint: disable=import-outside-toplevel ModelMessage, @@ -385,10 +441,78 @@ async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str def scripted(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse: n = len(asked) asked.append(n) - if n < TOOL_CALLS: - return ModelResponse(parts=[ToolCallPart("lookup", arguments_of(n), tool_call_id=call_id(n))]) + if planned := round_of(n): + return ModelResponse(parts=[ToolCallPart(name, args, tool_call_id=i) for i, name, args in planned]) return ModelResponse(parts=[TextPart("done")]) return await pydantic_ai.prompt(ctx, text, model=FunctionModel(scripted), tools=[*tools]) - await assert_costs("pydantic_ai", ask) + return ask + + +FRAMEWORKS: dict[str, Callable[[], Awaitable[Ask]]] = { + "adk": adk_ask, + "langgraph agent": langgraph_agent_ask, + "langgraph graph": langgraph_graph_ask, + "openai": openai_ask, + "pydantic_ai": pydantic_ai_ask, +} + + +@pytest.mark.parametrize("name", FRAMEWORKS) +async def test_a_turns_restate_calls_cost_one_commit_each(name: str): + SHAPE[0] = "serial" + await assert_costs(name, await FRAMEWORKS[name]()) + + +# --- Two Restate calls and a slow plain tool in one round -------------------------------------------- + + +async def records_done(host: Counting) -> set[int]: + """The calls (by the index of their order) that the latest commit has as done.""" + _, records = await held(host.committed[-1]) + return {i for i in range(2) for r in records if f'"{order_of(i)}"' in r["input"] and r.get("done")} + + +async def until_done(host: Counting, wanted: set[int]) -> None: + for _ in range(1000): + if host.committed and await records_done(host) == wanted: + return + await asyncio.sleep(0.005) + raise AssertionError(f"the committed records never had {wanted} done: {await records_done(host)}") + + +@pytest.mark.parametrize("name", FRAMEWORKS) +async def test_each_answer_of_a_round_is_committed_on_its_own_while_a_slow_tool_still_runs(name: str): + """The commit that stores the results waits for the slow tool, and the answers do not wait for it: call 1's + answer is committed (written alone, as no commit is coming), then call 2's, each before the slow tool ends.""" + SHAPE[0] = "parallel" + try: + ask = await FRAMEWORKS[name]() + asker = sessions.SessionObject("asker") + + @asker.handler + async def run(ctx: sessions.SessionContext, text: str) -> str: + return await ask(ctx, text, [restated_lookup, slow_tool]) + + TURN[0] = "round" + SLOW[:] = [asyncio.Event()] + gate = asyncio.Event() + host = Counting(Backend(), service="asker", answers={"publish": b'{"revision": 1}'}, gate=gate) + turn = asyncio.ensure_future(invoke(asker, "run", host, request(), "round")) + try: + await until_done(host, {0}) + assert not turn.done() and not SLOW[0].is_set() + gate.set() + await until_done(host, {0, 1}) + assert not turn.done() and not SLOW[0].is_set() + SLOW[0].set() + assert await turn == "done" + finally: + SLOW[0].set() + gate.set() + await asyncio.gather(turn, return_exceptions=True) + measured = Measured(host.syncs, host.committed, 2, "done", host.backend) + await assert_no_result_ahead_of_its_record(measured, calls=2) + finally: + SHAPE[0] = "serial" diff --git a/tests/sessions_ride.py b/tests/sessions_ride.py new file mode 100644 index 00000000..5df1ee13 --- /dev/null +++ b/tests/sessions_ride.py @@ -0,0 +1,407 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A write that rides the next commit of a database (``ride_commit``): written in that commit's transaction, before +its commit, so that it costs no commit of its own; ``flush_riders`` writes what is still pending.""" + +# pylint: disable=missing-function-docstring,missing-class-docstring,protected-access + +import asyncio +import gc +import typing +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Any + +import pytest + +from restate import sessions +from restate.sessions import _session, internal +from restate.sessions.internal import flush_riders, ride_commit +from sessions_database import Backend # pylint: disable=import-error +from sessions_object import Host, request # pylint: disable=import-error + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +@dataclass +class Counting(Host): + """A host that counts its syncs: each a commit.""" + + syncs: int = 0 + + async def sync(self) -> None: + await super().sync() + self.syncs += 1 + + +Write = Callable[[Any], Awaitable[None]] + + +def insert(x: str) -> Write: + async def write(tx: Any) -> None: + await tx.execute("INSERT INTO t VALUES (?)", [x]) + + return write + + +async def rows(db: Any) -> list[str]: + return [row[0] for row in await db.values("SELECT x FROM t ORDER BY x")] + + +async def hops(n: int) -> None: + """Let ``n`` event-loop iterations pass.""" + for _ in range(n): + await asyncio.sleep(0) + + +async def until(condition: Callable[[], bool]) -> None: + """Wait until ``condition`` holds: a write that takes real time (the store's) is under way.""" + for _ in range(2000): + if condition(): + return + await asyncio.sleep(0.005) + raise AssertionError("the condition did not come") + + +async def quiet(n: int = 5) -> None: + """Let the hop chain and what it started finish: more than a chain's budget, a few times.""" + for _ in range(n): + await hops(_session.URGENT_HOPS + 5) + await asyncio.sleep(0.01) + + +async def attempt(body: Callable[[Any, Counting], Awaitable[Any]], *, view: bool = False) -> Counting: + """Run ``body(ctx, host)`` as a handler of an object with a table ``t``, over a host that counts its syncs.""" + obj = sessions.SessionObject("riding", migrations=["CREATE TABLE t (x TEXT)"]) + host = Counting(Backend(), service="riding") + + if view: + + @obj.view + async def look(ctx: sessions.ViewContext) -> None: + await body(ctx, host) + + await internal.invoke(obj, "look", Host(host.backend, service="riding", shared=True), request()) + return host + + @obj.handler + async def run(ctx: sessions.SessionContext) -> None: + await ctx.db.execute("SELECT 1") + host.syncs = 0 + await body(ctx, host) + + await internal.invoke(obj, "run", host, request()) + return host + + +async def test_a_rider_is_written_by_the_next_transaction_that_commits_in_it(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + assert ride_commit(ctx.db, "a", insert("rode")) is True + assert await rows(ctx.db) == [] + assert host.syncs == 0 + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('own')") + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + # Once: the next transaction does not write it again. + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('again')") + assert await rows(ctx.db) == ["again", "own", "rode"] + + await attempt(body) + + +async def test_a_rider_is_written_by_a_write_outside_a_transaction_in_its_commit(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode")) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_a_rider_is_not_written_by_a_read_which_commits_nothing(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode")) + await ctx.db.get("SELECT 1") + await ctx.db.values("SELECT x FROM t") + await ctx.db.query("SELECT x FROM t") + assert await rows(ctx.db) == [] + assert host.syncs == 0 + + await attempt(body) + + +async def test_a_rider_is_written_by_the_transaction_that_was_open_when_it_was_registered(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('own')") + ride_commit(ctx.db, "a", insert("rode")) + assert await tx.values("SELECT x FROM t") == [["own"]] + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_a_rider_stays_pending_when_its_transaction_rolls_back_and_the_next_commit_writes_it(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode")) + with pytest.raises(RuntimeError, match="rolled back"): + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('lost')") + raise RuntimeError("rolled back") + assert await rows(ctx.db) == [] + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_a_rider_stays_pending_when_its_own_write_fails_and_the_transaction_with_it(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async def nowhere(tx: Any) -> None: + await tx.execute("INSERT INTO nowhere VALUES (1)") + + ride_commit(ctx.db, "a", nowhere) + with pytest.raises(Exception, match="nowhere"): + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == [] + # Replaced, it rides the next. + ride_commit(ctx.db, "a", insert("rode")) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_a_rider_is_one_per_slot_a_later_one_replaces_the_earlier_and_none_clears_it(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("first")) + ride_commit(ctx.db, "a", insert("second")) + ride_commit(ctx.db, "b", insert("other")) + ride_commit(ctx.db, "c", insert("cleared")) + ride_commit(ctx.db, "c", None) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["other", "own", "second"] + + await attempt(body) + + +async def test_a_rider_registered_while_the_commit_that_writes_the_earlier_one_is_under_way_is_for_the_next(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async def first(tx: Any) -> None: + await tx.execute("INSERT INTO t VALUES ('first')") + ride_commit(ctx.db, "a", insert("second")) + + ride_commit(ctx.db, "a", first) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["first", "own"] + await ctx.db.execute("INSERT INTO t VALUES ('next')") + assert await rows(ctx.db) == ["first", "next", "own", "second"] + + await attempt(body) + + +async def test_flush_writes_what_is_pending_in_a_transaction_of_its_own_and_nothing_when_nothing_is(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + await flush_riders(ctx.db) + assert host.syncs == 0 + ride_commit(ctx.db, "a", insert("rode")) + await flush_riders(ctx.db) + assert host.syncs == 1 + assert await rows(ctx.db) == ["rode"] + await flush_riders(ctx.db) + assert host.syncs == 1 + + await attempt(body) + + +async def test_a_view_cannot_ride_and_a_database_that_is_not_an_attempts_either(): + async def body(ctx: Any, host: Counting) -> None: + assert ride_commit(ctx.db, "a", insert("rode")) is False + await flush_riders(ctx.db) + assert ride_commit(typing.cast(Any, object()), "a", insert("rode")) is False + + await attempt(body, view=True) + + +async def test_a_pending_rider_is_dropped_with_the_attempt_and_nothing_rides_after_it_ended(): + registered: list[Any] = [] + + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + registered.append(ctx.db) + + host = await attempt(body) + await quiet() + assert host.syncs == 0 + assert ride_commit(registered[0], "a", insert("late")) is False + + +async def test_a_database_of_another_name_has_riders_of_its_own(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + other = internal.database(ctx.db, "other") + await other.execute("CREATE TABLE t (x TEXT)") + ride_commit(other, "a", insert("rode")) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["own"] + assert await rows(other) == [] + await other.execute("INSERT INTO t VALUES ('own')") + assert await rows(other) == ["own", "rode"] + + await attempt(body) + + +# --- Urgent riders: written alone once nothing has started a commit for URGENT_HOPS event-loop iterations ------ + + +async def test_an_urgent_rider_is_written_alone_after_the_hops_with_nothing_under_way_one_commit(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + await hops(_session.URGENT_HOPS // 2) + assert host.syncs == 0 + await until(lambda: host.syncs > 0) + await quiet() + assert host.syncs == 1 + assert await rows(ctx.db) == ["rode"] + + await attempt(body) + + +async def test_an_urgent_rider_is_written_by_a_transaction_that_starts_within_the_budget_and_not_again(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + await hops(_session.URGENT_HOPS // 2) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert host.syncs == 1 + await quiet() + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_an_urgent_rider_is_written_alone_after_a_rollback_left_it_pending(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + with pytest.raises(RuntimeError): + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('lost')") + raise RuntimeError("rolled back") + assert host.syncs == 0 + await until(lambda: host.syncs > 0) + await quiet() + assert host.syncs == 1 + assert await rows(ctx.db) == ["rode"] + + await attempt(body) + + +async def test_an_urgent_rider_waits_for_a_transaction_that_is_held_open_longer_than_the_budget(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('own')") + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + await hops(_session.URGENT_HOPS * 3) + assert host.syncs == 0 + assert host.syncs == 1 + await quiet() + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_an_urgent_rider_registered_while_the_lone_write_commits_is_written_after_it_in_one_more_commit(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async def first(tx: Any) -> None: + await tx.execute("INSERT INTO t VALUES ('first')") + ride_commit(ctx.db, "b", insert("other"), urgent=True) + ride_commit(ctx.db, "a", insert("second"), urgent=True) + + ride_commit(ctx.db, "a", first, urgent=True) + await until(lambda: host.syncs > 0) + await quiet() + assert host.syncs == 2 + assert await rows(ctx.db) == ["first", "other", "second"] + + await attempt(body) + + +async def test_a_lone_write_that_fails_leaves_the_rider_pending_raises_nothing_and_is_not_retried_by_itself(): + unhandled: list[dict[str, Any]] = [] + loop = asyncio.get_running_loop() + loop.set_exception_handler(lambda _loop, context: unhandled.append(context)) + tried: list[int] = [] + + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + async def broken(tx: Any) -> None: + tried.append(1) + await tx.execute("INSERT INTO nowhere VALUES (1)") + + ride_commit(ctx.db, "a", broken, urgent=True) + await until(lambda: bool(tried)) + await quiet() + gc.collect() + assert tried == [1] + assert host.syncs == 0 + # Still pending: replaced, it rides the next commit. + ride_commit(ctx.db, "a", insert("rode")) + await ctx.db.execute("INSERT INTO t VALUES ('own')") + assert await rows(ctx.db) == ["own", "rode"] + + try: + await attempt(body) + gc.collect() + finally: + loop.set_exception_handler(None) + assert unhandled == [] + + +async def test_a_rider_that_is_not_urgent_is_never_written_by_the_hops(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("rode")) + await quiet() + assert host.syncs == 0 + assert await rows(ctx.db) == [] + + await attempt(body) + + +async def test_a_rider_that_replaces_an_urgent_one_stays_urgent(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + ride_commit(ctx.db, "a", insert("first"), urgent=True) + ride_commit(ctx.db, "a", insert("second")) + await until(lambda: host.syncs > 0) + await quiet() + assert host.syncs == 1 + assert await rows(ctx.db) == ["second"] + + await attempt(body) + + +async def test_the_lone_write_is_not_refused_by_a_cancellation_that_is_owed(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + owed = [True] + # What `asked` takes: the handler's next call is the one that fails with it. + setattr(host, "take_cancellation", lambda: owed.pop() if owed else False) + ride_commit(ctx.db, "a", insert("rode"), urgent=True) + await until(lambda: host.syncs > 0) + await quiet() + assert host.syncs == 1 + assert owed == [True] + + await attempt(body) From eab138cdba68569666bee8dcc60e3fd3ce5f40f6 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 13:55:38 +0100 Subject: [PATCH 09/13] Sessions: an urgent rider stops counting once its attempt ended; the calls' records are tested at their own level --- python/restate/sessions/_session.py | 11 ++-- tests/agents_calls_ride.py | 86 +++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 4 deletions(-) diff --git a/python/restate/sessions/_session.py b/python/restate/sessions/_session.py index 51dd5e24..d8b9dfd6 100644 --- a/python/restate/sessions/_session.py +++ b/python/restate/sessions/_session.py @@ -649,8 +649,11 @@ def asked(self) -> None: What the handler asks for passes through here: ``ctx.db``'s statements, its ``transaction()``, and a schema it ensures. What the session does for itself does not: the open, the object's schema, the sends a crashed - attempt left unmade, emptying the outbox after a commit, and the save at - the handler's end. A cancellation that failed one of those would be + attempt left unmade, emptying the outbox after a commit, the save at + the handler's end, and the write of an urgent rider that no commit came + to carry (``ride_commit``): a call that answered is recorded even while + a cancellation is owed to the handler, which stays owed to its next call. A cancellation that failed one of + those would be delivered to nobody, or would report a transaction as cancelled after it committed. @@ -685,7 +688,7 @@ def ride(self, slot: str, write: Rider | None, urgent: bool) -> bool: def _arm(self) -> None: """Start counting the iterations an urgent rider waits, if one is pending and nothing is counting.""" - if self._hop is not None or self._ended or self._closing: + if self._hop is not None or self._ended or self._closing or self._host.attempt_end() is not None: return if not any(pending.urgent for pending in self._riders.values()): return @@ -701,7 +704,7 @@ def _step(self) -> None: """One iteration of the loop has passed: write the urgent riders alone once enough have, with nothing under way.""" self._hop = None # A transaction under way writes them, or counts again as it ends. - if self._ended or self._closing or self._active > 0: + if self._ended or self._closing or self._active > 0 or self._host.attempt_end() is not None: return if not any(pending.urgent for pending in self._riders.values()): return diff --git a/tests/agents_calls_ride.py b/tests/agents_calls_ride.py index 4c5c90ef..74a16e55 100644 --- a/tests/agents_calls_ride.py +++ b/tests/agents_calls_ride.py @@ -214,3 +214,89 @@ async def run(ctx: sessions.SessionContext, text: str) -> str: # The same tool and input again, under a new id: not the call the model has the result of. assert keys_of(first, retry) == [f"{req.id}:call_1", f"{req.id}:call_2"] assert [i for i, _ in await read_results(backend)] == ["call_1", "call_2"] + + +# --- The records themselves -------------------------------------------------------------------------------- + + +async def calls_attempt(body: typing.Callable[[sessions.SessionContext, Counting, Backend], typing.Awaitable[None]]): + """Run ``body`` as a handler over a host that counts its syncs, from the second one (the first opens the schema).""" + obj = sessions.SessionObject("asker") + backend = Backend() + host = Counting(backend, service="asker") + + @obj.handler + async def run(ctx: sessions.SessionContext) -> None: + await ctx.db.execute("SELECT 1") + await body(ctx, host, backend) + + await invoke(obj, "run", host, request()) + + +async def until_records(backend: Backend, wanted: typing.Callable[[list[dict[str, Any]]], bool]) -> None: + for _ in range(1000): + if wanted(await records_of(backend)): + return + await asyncio.sleep(0.005) + raise AssertionError(f"the committed records never were as wanted: {await records_of(backend)}") + + +async def test_the_records_are_written_by_a_commit_under_way_or_on_their_own_an_answer_at_once_a_settling_with_the_next(): + from restate.agents._calls import call_of, flush_calls, settle + + async def body(ctx: sessions.SessionContext, host: Counting, backend: Backend) -> None: + first = await call_of(ctx, "pay", {"n": 1}, "c1") + # The record of a new call commits before the call. + assert [r["tool"] for r in await records_of(backend)] == ["pay"] + host.syncs = 0 + await first.answered() + assert host.syncs == 0 + # No commit is coming: the answer is written on its own, soon. + await until_records(backend, lambda records: [r.get("done") for r in records] == [True]) + assert host.syncs == 1 + # Settled, it is forgotten with the next commit: nothing writes it by itself. + await settle(ctx, lambda _id, _failed: True) + for _ in range(200): + await asyncio.sleep(0) + await asyncio.sleep(0.02) + assert host.syncs == 1 + assert len(await records_of(backend)) == 1 + await ctx.db.execute("CREATE TABLE IF NOT EXISTS other (x)") + assert host.syncs == 2 + assert await records_of(backend) == [] + await flush_calls(ctx) + assert host.syncs == 2 + + await calls_attempt(body) + + +async def test_the_record_of_a_new_call_writes_the_whole_row_and_leaves_nothing_pending(): + from restate.agents._calls import call_of, flush_calls + + async def body(ctx: sessions.SessionContext, host: Counting, backend: Backend) -> None: + await (await call_of(ctx, "pay", {"n": 1}, "c1")).answered() + host.syncs = 0 + await call_of(ctx, "pay", {"n": 2}, "c2") + # One commit, with the answer of the first in it, and nothing pending after. + assert host.syncs == 1 + records = await records_of(backend) + assert [(r["ids"], r.get("done")) for r in records] == [(["c1"], True), (["c2"], None)] + await flush_calls(ctx) + assert host.syncs == 1 + + await calls_attempt(body) + + +async def test_an_answer_stays_urgent_when_a_settling_is_registered_over_it(): + from restate.agents._calls import call_of, settle + + async def body(ctx: sessions.SessionContext, host: Counting, backend: Backend) -> None: + first = await call_of(ctx, "pay", {"n": 1}, "c1") + second = await call_of(ctx, "pay", {"n": 2}, "c2") + await first.answered() + await second.answered() + # The transcript has the second's result: forgetting it replaces the pending write, which stays urgent. + await settle(ctx, lambda call_id, _failed: call_id == "c2") + await until_records(backend, lambda records: [(r["ids"], r.get("done")) for r in records] == [(["c1"], True)]) + + await calls_attempt(body) From d618d3a4dd29cf3269a25a1333b86ddd3a6528ec Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 14:02:59 +0100 Subject: [PATCH 10/13] Agents: the record of a new call is carried by a transaction that is under way --- python/restate/agents/_calls.py | 29 +++++++++++------ tests/agents_calls_ride.py | 38 ++++++++++++++++++++++ tests/sessions_ride.py | 56 +++++++++++++++++++++++++++++++++ 3 files changed, 114 insertions(+), 9 deletions(-) diff --git a/python/restate/agents/_calls.py b/python/restate/agents/_calls.py index 821d66be..31345b1f 100644 --- a/python/restate/agents/_calls.py +++ b/python/restate/agents/_calls.py @@ -30,7 +30,8 @@ turn's steps that commits, and before each tool call). An error in the transcript does not count as the result, unless the call itself returned that error. -Only the record of a new call commits of its own, before the call is made. That a call answered rides a commit +Only the record of a new call commits of its own, before the call is made (with the commit of a transaction +that is under way, if one is: it carries the pending answers, so none is left behind a result). That a call answered rides a commit that is under way or starts at once (``ride_commit``): the one that stores the call's result, so that the transcript never has a result of a call that is not recorded as answered. If none does (a slow tool of the round is still running, another call waits), it is written on its own once no transaction has started for a while (see @@ -113,15 +114,29 @@ class _Calls: """The slot of the calls' write that rides the next commit (``_ride``).""" +def _writer(state: _Calls) -> Callable[[Transaction], Awaitable[None]]: + """The write of ``state``, as it is when it runs.""" + + async def write(tx: Transaction) -> None: + await tx.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) + + return write + + async def _store(ctx: SessionContext, state: _Calls) -> None: """Store ``state``; it is committed before the call it records is made. The rows the conversation holds back are written first: the call outlives the attempt, and what led to it must - too. It is the whole row: what rides the next commit is written, and no longer pending. + too. It is the whole row, written as a rider that is flushed (``flush_riders``) rather than by a statement of its + own: a transaction that is under way (the write of an earlier call's result) carries it with its commit, so + that it never commits that result without the answer that is pending. Nothing under way, it is one commit of + its own. It returns once the row is committed. """ await flush_held(ctx) - ride_commit(ctx.db, _RIDER, None) - await ctx.db.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) + if ride_commit(ctx.db, _RIDER, _writer(state)): + await flush_riders(ctx.db) + else: + await ctx.db.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) async def _ride(ctx: SessionContext, state: _Calls, urgent: bool = False) -> None: @@ -131,11 +146,7 @@ async def _ride(ctx: SessionContext, state: _Calls, urgent: bool = False) -> Non own unless a commit starts soon to write it; one that is pending and urgent stays so. A database that cannot ride (a view's) commits it at once. """ - - async def write(tx: Transaction) -> None: - await tx.execute(_UPSERT, [state.invocation, json.dumps(state.calls)]) - - if not ride_commit(ctx.db, _RIDER, write, urgent=urgent): + if not ride_commit(ctx.db, _RIDER, _writer(state), urgent=urgent): await _store(ctx, state) diff --git a/tests/agents_calls_ride.py b/tests/agents_calls_ride.py index 74a16e55..e1a35e3e 100644 --- a/tests/agents_calls_ride.py +++ b/tests/agents_calls_ride.py @@ -300,3 +300,41 @@ async def body(ctx: sessions.SessionContext, host: Counting, backend: Backend) - await until_records(backend, lambda records: [(r["ids"], r.get("done")) for r in records] == [(["c1"], True)]) await calls_attempt(body) + + +async def test_the_record_of_a_new_call_does_not_take_the_answer_from_a_transaction_that_is_under_way(): + """A result's transaction is open when a new call is recorded: it carries the answer, and the new record with it.""" + from restate.agents._calls import call_of + + async def body(ctx: sessions.SessionContext, host: Counting, backend: Backend) -> None: + await ctx.db.execute("CREATE TABLE other (x)") + first = await call_of(ctx, "pay", {"n": 1}, "cA") + await first.answered() + start, host.syncs = len(host.committed), 0 + entered, release = asyncio.Event(), asyncio.Event() + + async def result_written() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO other VALUES ('A-result')") + entered.set() + await release.wait() + + under_way = asyncio.ensure_future(result_written()) + await entered.wait() + second = asyncio.ensure_future(call_of(ctx, "pay", {"n": 2}, "cB")) + for _ in range(100): + await asyncio.sleep(0) + # Its record is not committed while the transaction holds the database. + assert not second.done() + release.set() + await under_way + await second + assert [(r["ids"], r.get("done")) for r in await records_of(backend)] == [(["cA"], True), (["cB"], None)] + for committed in host.committed[start:]: + text, records = await held(committed) + if "A-result" in text: + assert [r.get("done") for r in records if r["ids"] == ["cA"]] == [True], records + # The transaction carried both: nothing else committed. + assert host.syncs == 1 + + await calls_attempt(body) diff --git a/tests/sessions_ride.py b/tests/sessions_ride.py index 5df1ee13..e8702219 100644 --- a/tests/sessions_ride.py +++ b/tests/sessions_ride.py @@ -405,3 +405,59 @@ async def body(ctx: sessions.SessionContext, host: Counting) -> None: assert owed == [True] await attempt(body) + + +# --- A flush waits for the transactions that are under way --------------------------------------------------- + + +async def test_a_flush_while_a_transaction_is_under_way_returns_after_the_commit_that_carried_the_rider(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + entered, release = asyncio.Event(), asyncio.Event() + + async def held() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('own')") + entered.set() + await release.wait() + + under_way = asyncio.ensure_future(held()) + await entered.wait() + ride_commit(ctx.db, "a", insert("rode")) + flush = asyncio.ensure_future(flush_riders(ctx.db)) + await hops(30) + assert not flush.done() + release.set() + await under_way + await flush + # Written once, by that transaction's commit; the flush had nothing left to commit. + assert host.syncs == 1 + assert await rows(ctx.db) == ["own", "rode"] + + await attempt(body) + + +async def test_a_flush_while_a_transaction_is_under_way_that_rolls_back_writes_the_rider_itself(): + async def body(ctx: sessions.SessionContext, host: Counting) -> None: + entered, release = asyncio.Event(), asyncio.Event() + + async def held() -> None: + async with ctx.db.transaction() as tx: + await tx.execute("INSERT INTO t VALUES ('lost')") + entered.set() + await release.wait() + raise RuntimeError("rolled back") + + under_way = asyncio.ensure_future(held()) + await entered.wait() + ride_commit(ctx.db, "a", insert("rode")) + flush = asyncio.ensure_future(flush_riders(ctx.db)) + await hops(30) + assert not flush.done() + release.set() + with pytest.raises(RuntimeError, match="rolled back"): + await under_way + await flush + assert host.syncs == 1 + assert await rows(ctx.db) == ["rode"] + + await attempt(body) From 9509407016f7e1e18d64352f5be01aed611865f3 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 14:08:51 +0100 Subject: [PATCH 11/13] Agents: LangGraph's checkpointer stores a task's writes with the checkpoint that follows them --- docs/agents/conversation.md | 2 +- docs/agents/frameworks.md | 11 + docs/agents/porting.md | 2 +- .../restate/agents/langgraph/_checkpointer.py | 279 +++++++-- python/restate/agents/langgraph/_graph.py | 5 +- tests/agents_commits.py | 55 +- tests/agents_langgraph_writes.py | 582 ++++++++++++++++++ tests/transactions_spy.py | 75 +++ 8 files changed, 942 insertions(+), 69 deletions(-) create mode 100644 tests/agents_langgraph_writes.py create mode 100644 tests/transactions_spy.py diff --git a/docs/agents/conversation.md b/docs/agents/conversation.md index 4d959e84..be3022b2 100644 --- a/docs/agents/conversation.md +++ b/docs/agents/conversation.md @@ -190,7 +190,7 @@ CREATE TABLE restate_agent_steers ( -- the messages steered to a turn t | --- | --- | --- | | `restate_agent_calls` (schema `restate-agents.calls`), in the key's database | one row: the invocation's Restate calls made by tools, as JSON ([Tool calls, once](#tool-calls-once-the-call-records)) | the tools built on Restate (`call`, `send`, `workflow`, `subagent`, `wait_for_signal`) and `wait_for` | | the companion's state: the agent's own object `.prebuilt.restate`, keyed as the agent | `turn`: the turn being answered (`Started`: its invocation, since when, whether it takes steered messages and whether `start` publishes it); `waiting`: the tools' waits, each with its awakeable; `kept`: signals that came before their wait; `revision`; `watching`: the `watch` calls waiting for a newer revision | the companion's handlers (`start`, `close`, `wait`, `signal`, `publish`, `watch`) | -| `restate_langgraph_checkpoints`, `restate_langgraph_channel_values`, `restate_langgraph_writes` (schema `restate_agents.langgraph`) | a LangGraph graph's checkpoints, channel values by version, and pending writes, per thread and namespace | `SqlCheckpointSaver`, for `langgraph.agent(graph=...)`; pruned to what the latest checkpoint of each namespace needs after each run | +| `restate_langgraph_checkpoints`, `restate_langgraph_channel_values`, `restate_langgraph_writes` (schema `restate_agents.langgraph`) | a LangGraph graph's checkpoints, channel values by version, and pending writes, per thread and namespace | `SqlCheckpointSaver`, for `langgraph.agent(graph=...)`; a step's writes are in the commit of the checkpoint that follows them, when it follows at once; pruned to what the latest checkpoint of each namespace needs after each run | | `restate_pydantic_ai_plan`, `restate_pydantic_ai_spills`, `restate_pydantic_ai_journal` (schema `restate_agents.pydantic_ai`) | the harness's plan (`plan_store()`), spilled tool results (`overflow_store()`), and each tool call's journal of plan reads and writes, for the current invocation | the Pydantic AI stores | | `restate_pydantic_ai_memory`, `..._receipts`, `..._generation` (schema `restate_agents.pydantic_ai.memory`), in a memory object's key | the harness's memory files, the receipts of the changes, and the version counter: one key per namespace (a user), shared by that user's conversations | `memory()`'s session object | diff --git a/docs/agents/frameworks.md b/docs/agents/frameworks.md index f10b1c2a..cc2c884a 100644 --- a/docs/agents/frameworks.md +++ b/docs/agents/frameworks.md @@ -409,6 +409,17 @@ sequenceDiagram pointing to) the whole state, the message list included. There is no turn: a thread is a chain of checkpoints. Messages have ids, and `RemoveMessage(id)` (or `REMOVE_ALL_MESSAGES`) removes them. +- **A task's writes are saved apart from its step's checkpoint:** the saver + is called with `put_writes` as each task finishes, and with `put` once the + step's last task has (before the next step starts, with + `durability="sync"`). A parallel step's finished tasks are therefore + saved while their siblings still run, so that they do not run again after + a crash. LangGraph waits for every `put_writes` before a run ends, and + before the step's `put` only for a `DeltaChannel`'s writes, an error + handler's and `update_state`'s. The checkpointer keeps a task's writes + pending, and the `put` that follows at once stores them in its own + transaction, before its checkpoint; else they are stored alone after a few + event-loop iterations. - **`DeltaChannel`** (a beta) stores a channel's writes, and its whole value only now and then (a snapshot); its value is rebuilt from the latest snapshot and the writes after it. diff --git a/docs/agents/porting.md b/docs/agents/porting.md index c566e2c6..7923ec98 100644 --- a/docs/agents/porting.md +++ b/docs/agents/porting.md @@ -176,7 +176,7 @@ tests. Test names are this SDK's. | Call records: made once, rejoined under a new id, kept until stored, forgotten after | `tests/agents_tools.py` (`test_a_returned_call_is_kept_until_its_result_is_stored_and_forgotten_once_it_is`) | | The companion: start, close, `awaitTurn`, `settle`, waits and signals; one per agent, keyed as it, ingress-private | `tests/agents_signals.py`, `tests/agents_companion.py`, `tests/agents_object.py` | | Per framework: answer and the full view after it, a crash in a tool, a stored answer not asked again, refused, stopped, `output=`, several prompts | each framework's `tests/agents_*.py` | -| The LangGraph checkpointer: resume, history, prune, `DeltaChannel`, many channels | `tests/agents_langgraph_checkpointer.py` | +| The LangGraph checkpointer: resume, history, prune, `DeltaChannel`, many channels | `tests/agents_langgraph_checkpointer.py`, `tests/agents_langgraph_writes.py` (a task's writes with the checkpoint that follows, or alone; a parallel step cut while a node runs), `tests/agents_commits.py` (the commit sequence) | And the mutants of `scripts/resurrect.py` ([Testing](testing.md)): each brings back one bug that a fix describes, or breaks one rule of the turn. A diff --git a/python/restate/agents/langgraph/_checkpointer.py b/python/restate/agents/langgraph/_checkpointer.py index 390b22ed..1f906a5c 100644 --- a/python/restate/agents/langgraph/_checkpointer.py +++ b/python/restate/agents/langgraph/_checkpointer.py @@ -26,11 +26,27 @@ - ``restate_langgraph_writes`` holds the pending writes of each checkpoint's tasks. -Each ``aput`` and ``aput_writes`` runs in one SQL transaction, so a step is -stored whole, in order with everything else the handler does. Operations run -one at a time, in the order they are called, even when LangGraph writes the -results of parallel tasks at once. The saver is async-only, because ``ctx.db`` -is. +Each ``aput`` is one SQL transaction, so a step is stored whole, in order with +everything else the handler does. Operations run one at a time, in the order +they are called, even when LangGraph writes the results of parallel tasks at +once. The saver is async-only, because ``ctx.db`` is. + +A task's ``aput_writes`` keeps its rows pending, and returns once they are +stored (LangGraph waits for it before a run ends, whatever ends it, and before +a step's ``aput`` if it carries delta writes); it fails with the error of the +transaction that stored them. The ``aput`` of its step, if it is called at once, +which it is when the step's last task has just finished, takes every pending +row into its own transaction and stores them first, then its checkpoint: they +are stored with it, and before any task of the next step starts. Else, the +step has tasks still running, and the pending rows are stored on their own, in +one transaction, when ``_HOPS`` event-loop iterations have passed: a task that +finished has its writes stored while its siblings run, so it does not run +again after a crash, and no ``aput_writes`` waits for an ``aput`` to be +called. Reads (``aget_tuple``, ``alist``), ``aprune`` and ``adelete_thread`` +store what is pending first. Nothing is remembered of a failure: a failed +transaction fails the ``aput_writes`` and the ``aput`` that it carried, which +are not stored again (the run fails and goes on from what is stored), and +later calls go ahead. A thread keeps every checkpoint, which LangGraph needs for ``alist``, time travel and forks, until ``aprune`` (LangGraph's API) deletes them: with @@ -48,6 +64,7 @@ import typing import uuid from collections.abc import AsyncIterator, Collection, Sequence +from dataclasses import dataclass, field from typing import Any from langchain_core.runnables import RunnableConfig @@ -112,6 +129,26 @@ """The type of a channel a step emptied.""" +_HOPS = 3 +"""How many event-loop iterations a task's pending writes wait for the ``aput`` of their step, before they are stored +on their own. Measured, on LangGraph 1.2: from a step's last ``aput_writes`` to its ``aput`` there are 0 or 1 +iterations for a step of one task, of parallel tasks, with stream modes, a subgraph or a step timeout, whether LangGraph +starts tasks at once (Python 3.12 and later) or on the next iteration (3.11). It is a commit's duration, or unbounded, +for the ``__start__`` write, with ``max_concurrency``, and for writes that LangGraph waits for before it calls ``aput`` +(delta channels, error handlers, ``update_state``): those are stored on their own. A larger number only delays the +rows of a step whose ``aput`` does not follow.""" + + +@dataclass(eq=False) +class _Pending: + """The rows of one ``aput_writes``, kept until they are stored, and the awaitable that resolves then.""" + + verb: str + rows: list[list[SqlParam]] + stored: asyncio.Future[None] + hop: asyncio.Handle | None = field(default=None) + + class SqlCheckpointSaver(BaseCheckpointSaver[str]): """A LangGraph checkpoint saver that stores checkpoints in a database session. @@ -120,7 +157,16 @@ class SqlCheckpointSaver(BaseCheckpointSaver[str]): app = graph.compile(checkpointer=SqlCheckpointSaver(ctx.db)) await app.ainvoke(inputs, {"configurable": {"thread_id": ctx.key}}) - See the module docstring for how checkpoints are stored. + See the module docstring for how checkpoints are stored. A task's writes + are stored in the transaction of the checkpoint that follows them, when it + follows at once, and in one of their own otherwise; this is so for your own + use of the saver, as for the agent's. An ``aput_writes`` returns once its + rows are stored, or raises the error of the transaction that was to store + them, as LangGraph expects; await it before a handler returns, as LangGraph + does for a run (it waits for them before ``ainvoke`` returns or raises, + unless the awaiting task is cancelled). The saver is async-only: the + synchronous ``put`` and ``put_writes``, which ``ctx.db`` could not serve, + raise ``NotImplementedError``, as LangGraph's base class has them. Args: db: The database to store checkpoints in, usually ``ctx.db``. @@ -138,6 +184,10 @@ def __init__( self.db = db self._lock = asyncio.Lock() self._ready = False + self._pending: list[_Pending] = [] + """The writes that LangGraph handed over and that are not stored yet, in the order of the calls.""" + self._storing: set[asyncio.Task[None]] = set() + """The transactions of pending writes that have begun, which the operations after them wait for.""" def get_next_version(self, current: str | None, channel: None = None) -> str: """Return the channel version that follows ``current``. @@ -159,6 +209,73 @@ async def _setup(self) -> None: await SCHEMA.ensure(self.db) self._ready = True + def _take(self) -> list[_Pending]: + """Take every pending write, at once: what is taken is stored by the caller's transaction.""" + taken, self._pending = self._pending, [] + for pending in taken: + if pending.hop is not None: + pending.hop.cancel() + return taken + + def _arm(self, pending: _Pending) -> None: + """Store ``pending`` on its own, after ``_HOPS`` iterations, if no ``aput`` took it. + + A chain of ``call_soon``, one handle at a time, so that nothing waits for the saver to be called again. + """ + loop = asyncio.get_running_loop() + + def hop(count: int) -> None: + if count < _HOPS: + pending.hop = loop.call_soon(hop, count + 1) + return + pending.hop = None + if pending in self._pending: + at = self._pending.index(pending) + 1 # with the writes called before it + taken, self._pending = self._pending[:at], self._pending[at:] + for earlier in taken: + if earlier.hop is not None: + earlier.hop.cancel() + self._begin(taken) + + pending.hop = loop.call_soon(hop, 1) + + def _begin(self, taken: list[_Pending]) -> asyncio.Task[None]: + """Start the transaction that stores ``taken``, on its own.""" + task = asyncio.get_running_loop().create_task(self._store(taken)) + self._storing.add(task) + task.add_done_callback(self._storing.discard) + return task + + async def _store(self, taken: list[_Pending]) -> None: + """Store ``taken`` in one transaction, and settle what it carried; a failure is theirs alone.""" + try: + async with self._lock: + await self._setup() + async with self.db.transaction() as tx: + await _insert(tx, taken) + except BaseException as error: + _settle(taken, error) + if not isinstance(error, Exception): + raise + else: + _settle(taken) + + async def _after_stores_begun(self) -> None: + """Wait for every transaction of pending writes that has begun, so that the caller's comes after theirs. + + One that begun in the same iteration as the caller's call may not have the lock yet: without waiting for it, + the caller could take the lock first, and store its rows before the earlier ones. + """ + while self._storing: + await asyncio.wait(set(self._storing)) + + async def _store_pending(self) -> None: + """Store what is pending, before an operation that reads or deletes it.""" + taken = self._take() + if taken: + self._begin(taken) + await self._after_stores_begun() + def _load(self, type_: SqlValue, value: SqlValue) -> Any: return self.serde.loads_typed((str(type_), _bytes(value))) @@ -210,6 +327,7 @@ def config(id_: str) -> RunnableConfig: ) async def aget_tuple(self, config: RunnableConfig) -> CheckpointTuple | None: + await self._store_pending() async with self._lock: await self._setup() thread_id, ns = _thread(config) @@ -236,6 +354,7 @@ async def alist( before: RunnableConfig | None = None, limit: int | None = None, ) -> AsyncIterator[CheckpointTuple]: + await self._store_pending() async with self._lock: await self._setup() configurable: dict[str, Any] = dict((config or {}).get("configurable", {})) @@ -269,37 +388,47 @@ async def aput( metadata: CheckpointMetadata, new_versions: ChannelVersions, ) -> RunnableConfig: - async with self._lock: - await self._setup() - thread_id, ns = _thread(config) - parent_id: str | None = _configurable(config).get("checkpoint_id") - stored: dict[str, Any] = dict(checkpoint) - values: dict[str, Any] = stored.pop("channel_values") - type_, serialized = self.serde.dumps_typed(stored) - metadata_type, metadata_value = self.serde.dumps_typed(get_checkpoint_metadata(config, metadata)) - if type_ != metadata_type: - raise ValueError("Failed to serialize checkpoint and metadata to the same type.") - # The channels this step changed, at their new versions. - changed: list[list[SqlParam]] = [ - [ - channel, - str(version), - *(self.serde.dumps_typed(values[channel]) if channel in values else (_EMPTY, None)), + # Taken before anything is awaited: the writes called until now are this checkpoint's. + taken = self._take() + try: + await self._after_stores_begun() + async with self._lock: + await self._setup() + thread_id, ns = _thread(config) + parent_id: str | None = _configurable(config).get("checkpoint_id") + stored: dict[str, Any] = dict(checkpoint) + values: dict[str, Any] = stored.pop("channel_values") + type_, serialized = self.serde.dumps_typed(stored) + metadata_type, metadata_value = self.serde.dumps_typed(get_checkpoint_metadata(config, metadata)) + if type_ != metadata_type: + raise ValueError("Failed to serialize checkpoint and metadata to the same type.") + # The channels this step changed, at their new versions. + changed: list[list[SqlParam]] = [ + [ + channel, + str(version), + *(self.serde.dumps_typed(values[channel]) if channel in values else (_EMPTY, None)), + ] + for channel, version in new_versions.items() ] - for channel, version in new_versions.items() - ] - async with self.db.transaction() as tx: - for row in changed: + async with self.db.transaction() as tx: + await _insert(tx, taken) + for row in changed: + await tx.execute( + "INSERT OR REPLACE INTO restate_langgraph_channel_values " + "(thread_id, checkpoint_ns, channel, version, type, value) VALUES (?, ?, ?, ?, ?, ?)", + [thread_id, ns, *row], + ) await tx.execute( - "INSERT OR REPLACE INTO restate_langgraph_channel_values " - "(thread_id, checkpoint_ns, channel, version, type, value) VALUES (?, ?, ?, ?, ?, ?)", - [thread_id, ns, *row], + f"INSERT OR REPLACE INTO restate_langgraph_checkpoints ({_COLUMNS}) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + [thread_id, ns, checkpoint["id"], parent_id, type_, serialized, metadata_value], ) - await tx.execute( - f"INSERT OR REPLACE INTO restate_langgraph_checkpoints ({_COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?)", - [thread_id, ns, checkpoint["id"], parent_id, type_, serialized, metadata_value], - ) - return {"configurable": {"thread_id": thread_id, "checkpoint_ns": ns, "checkpoint_id": checkpoint["id"]}} + except BaseException as error: + _settle(taken, error) + raise + _settle(taken) + return {"configurable": {"thread_id": thread_id, "checkpoint_ns": ns, "checkpoint_id": checkpoint["id"]}} async def aput_writes( self, @@ -308,34 +437,32 @@ async def aput_writes( task_id: str, task_path: str = "", ) -> None: - async with self._lock: - await self._setup() - thread_id, ns = _thread(config) - checkpoint_id = str(_configurable(config)["checkpoint_id"]) - # Special writes (errors, interrupts) replace; others keep the first. - verb = ( - "INSERT OR REPLACE" if all(channel in WRITES_IDX_MAP for channel, _ in writes) else "INSERT OR IGNORE" - ) - rows: list[list[SqlParam]] = [ - [ - thread_id, - ns, - checkpoint_id, - task_id, - task_path, - WRITES_IDX_MAP.get(channel, idx), - channel, - *self.serde.dumps_typed(value), - ] - for idx, (channel, value) in enumerate(writes) + """Keep a task's ``writes`` pending, and return once they are stored. + + They are stored by the next ``aput`` if it is called within a few event-loop iterations, else on their own; + the error of the transaction that was to store them is raised. + """ + thread_id, ns = _thread(config) + checkpoint_id = str(_configurable(config)["checkpoint_id"]) + # Special writes (errors, interrupts) replace; others keep the first. + verb = "INSERT OR REPLACE" if all(channel in WRITES_IDX_MAP for channel, _ in writes) else "INSERT OR IGNORE" + rows: list[list[SqlParam]] = [ + [ + thread_id, + ns, + checkpoint_id, + task_id, + task_path, + WRITES_IDX_MAP.get(channel, idx), + channel, + *self.serde.dumps_typed(value), ] - async with self.db.transaction() as tx: - for row in rows: - await tx.execute( - f"{verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, " - "task_path, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - row, - ) + for idx, (channel, value) in enumerate(writes) + ] + pending = _Pending(verb, rows, asyncio.get_running_loop().create_future()) + self._pending.append(pending) + self._arm(pending) + await pending.stored async def adelete_thread(self, thread_id: str) -> None: await self.aprune([thread_id], strategy="delete") @@ -358,6 +485,7 @@ async def aprune(self, thread_ids: Sequence[str], *, strategy: str = "keep_lates """ if strategy not in ("keep_latest", "delete"): raise ValueError(f'unknown strategy {strategy!r}: use "keep_latest" or "delete"') + await self._store_pending() async with self._lock: await self._setup() async with self.db.transaction() as tx: @@ -412,6 +540,35 @@ async def _kept(self, tx: DatabaseWriter, thread_id: str, ns: str, checkpoint_id return kept +async def _insert(tx: DatabaseWriter, pending: Sequence[_Pending]) -> None: + """Write the rows of ``pending``, in the order of the calls, each with its own verb.""" + for writes in pending: + for row in writes.rows: + await tx.execute( + f"{writes.verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, " + "task_path, idx, channel, type, value) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + row, + ) + + +def _settle(pending: Sequence[_Pending], error: BaseException | None = None) -> None: + """Resolve the ``aput_writes`` of ``pending``, or fail them with ``error``. + + A failure is marked as retrieved: a run that was cancelled does not await its writes any more, and nothing may be + logged for that. + """ + for writes in pending: + if writes.stored.done(): + continue + if error is None: + writes.stored.set_result(None) + elif isinstance(error, asyncio.CancelledError): + writes.stored.cancel() + else: + writes.stored.set_exception(error) + writes.stored.exception() + + def _thread(config: RunnableConfig) -> tuple[str, str]: """Return the thread id and checkpoint namespace of ``config``.""" configurable = _configurable(config) diff --git a/python/restate/agents/langgraph/_graph.py b/python/restate/agents/langgraph/_graph.py index 8047b940..0403f701 100644 --- a/python/restate/agents/langgraph/_graph.py +++ b/python/restate/agents/langgraph/_graph.py @@ -18,7 +18,10 @@ - The graph's checkpoints are in the key's database (``SqlCheckpointSaver``), stored before each step runs (``durability="sync"``), and the prebuilt ``nodes`` and the tools of ``tools()`` get the handler's context in it - (``_context.py``). LangGraph's run context is the graph's own + (``_context.py``). A task's writes are stored with the checkpoint of its + step when that follows at once, and alone otherwise, as a parallel step's + finished task's are, so that a crash does not run it again (see the + checkpointer). LangGraph's run context is the graph's own (``context=``), else the handler's. A retried attempt resumes the run it cut off. A run that finishes prunes the thread to the latest checkpoint of each namespace (LangGraph's ``aprune``), and what LangGraph rebuilds diff --git a/tests/agents_commits.py b/tests/agents_commits.py index 0003c52a..f8aa0c7f 100644 --- a/tests/agents_commits.py +++ b/tests/agents_commits.py @@ -27,6 +27,7 @@ import restate from restate import sessions +from restate.sessions import Database from restate.agents import call, tool from restate.agents._tools import Tool from restate.sessions.internal import invoke @@ -51,15 +52,17 @@ def anyio_backend(): PLAIN_COMMITS = { "adk": 8, "langgraph agent": 8, - "langgraph graph": 26, + "langgraph graph": 19, "openai": 8, "pydantic_ai": 8, } """The commits of the second turn of a key, with plain tools, as measured. Each framework's own: the conversation stores the user's message (1), each model request's response that calls a tool (3) and each tool's result (3), and the last commit has the final response and the turn's answer (1). A graph of your own has more: LangGraph's -checkpointer commits a checkpoint and the writes of each node of each step of the graph, besides the conversation's -items.""" +checkpointer commits the checkpoint of each step of the graph, with the writes of the step's nodes, and besides the +conversation's items (the copies of the 3 replies and 3 results, and the final reply with the answer) it has the input's +checkpoint, the write of the ``__start__`` task (which its checkpoint does not follow at once, so it is a commit of its +own), the 7 steps' (3 rounds of a model's reply and a tool's result, and the final reply), and the prune.""" # --- The callee, the tools, and the host that counts ------------------------------------------------ @@ -291,7 +294,8 @@ async def ask(ctx: sessions.SessionContext, text: str, tools: list[Tool]) -> str await assert_costs("langgraph agent", ask) -async def test_langgraph_graph_turn(): +def langgraph_graph_ask() -> Ask: + """The turn of a graph of your own: a model node and a tool node, as LangGraph's examples have them.""" pytest.importorskip("langgraph") from langchain_core.messages import AIMessage # pylint: disable=import-outside-toplevel from langgraph.graph import END, START, MessagesState, StateGraph # pylint: disable=import-outside-toplevel @@ -323,7 +327,48 @@ def route(state: MessagesState) -> str: builder.add_edge("tools", "model") return await langgraph.prompt(ctx, text, graph=builder) - await assert_costs("langgraph graph", ask) + return ask + + +async def test_langgraph_graph_turn(): + pytest.importorskip("langgraph") + await assert_costs("langgraph graph", langgraph_graph_ask()) + + +async def test_langgraph_graph_checkpointer_commits(monkeypatch: pytest.MonkeyPatch): + """The checkpointer's commits, in order, of the second turn: a step's writes are in its checkpoint's commit.""" + pytest.importorskip("langgraph") + from restate.agents.langgraph import SqlCheckpointSaver, _graph # pylint: disable=import-outside-toplevel + from transactions_spy import Spy # pylint: disable=import-outside-toplevel,import-error + + spies: list[Spy] = [] + + class Recording(SqlCheckpointSaver): + def __init__(self, db: Database) -> None: + spies.append(Spy(db)) + super().__init__(spies[-1].database) + + monkeypatch.setattr(_graph, "SqlCheckpointSaver", Recording) + measured = await measure(langgraph_graph_ask(), restated=False) + assert len(spies) == 2 # one saver for each turn + put = ["restate_langgraph_channel_values", "restate_langgraph_checkpoints"] + step = ["restate_langgraph_writes", *put] + prune = ["restate_langgraph_checkpoints", "restate_langgraph_writes", "restate_langgraph_channel_values"] + # The input's checkpoint, the write of LangGraph's ``__start__`` task (which its checkpoint does not follow at + # once), the checkpoint of the first step; then each step of the other 7 (3 rounds of a model's reply and a tool's + # result, and the final reply), a commit with its writes; and the thread pruned to its latest checkpoint. + assert spies[1].tables == [ + put, + ["restate_langgraph_writes"], + put, + *[step] * 7, + prune, + ] + # The commits that are not the checkpointer's are the conversation's: the user's message, the copies of the 3 + # replies with tool calls and the 3 results (each after its checkpoint: they run beside the next step, whose + # commit may come first), and the final reply with the answer, last. + assert measured.commits - len(spies[1].commits) == 8 + assert measured.commits == PLAIN_COMMITS["langgraph graph"] async def test_openai_turn(): diff --git a/tests/agents_langgraph_writes.py b/tests/agents_langgraph_writes.py new file mode 100644 index 00000000..1cbf3768 --- /dev/null +++ b/tests/agents_langgraph_writes.py @@ -0,0 +1,582 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""The checkpointer stores a task's pending writes in the transaction of the checkpoint that follows them, when it +follows at once, and on their own after a few event-loop iterations otherwise; an ``aput_writes`` returns once its rows +are stored. + +Every test runs twice: with LangGraph starting its tasks at once (Python 3.12 and later) and on the next iteration (what +3.11 does), which the second run emulates. +""" + +# pylint: disable=missing-function-docstring,missing-class-docstring,protected-access + +import asyncio +import gc +import operator +import typing +from collections.abc import AsyncIterator, Callable, Coroutine +from typing import Annotated, Any, TypedDict + +import pytest + +pytest.importorskip("langgraph") + +from langchain_core.runnables import RunnableConfig # noqa: E402 +from langgraph._internal import _future # noqa: E402 +from langgraph.checkpoint.base import Checkpoint, empty_checkpoint # noqa: E402 +from langgraph.graph import END, START, StateGraph # noqa: E402 +from langgraph.types import Command, interrupt # noqa: E402 + +from restate import sessions # noqa: E402 +from restate.agents.langgraph import SqlCheckpointSaver # noqa: E402 +from agents_langgraph_checkpointer import THREAD, attempt # noqa: E402 # pylint: disable=import-error +from sessions_database import Backend # noqa: E402 # pylint: disable=import-error +from transactions_spy import Spy # noqa: E402 # pylint: disable=import-error + +WRITES = "restate_langgraph_writes" +CHECKPOINTS = "restate_langgraph_checkpoints" + + +@pytest.fixture(scope="session") +def anyio_backend(): + return "asyncio" + + +@pytest.fixture(autouse=True, params=["tasks at once", "tasks on the next iteration"]) +def lazy_tasks(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> bool: + """LangGraph starts the coroutines it submits at once on Python 3.12 and later, and on the next iteration before.""" + lazy = request.param != "tasks at once" + if lazy: + monkeypatch.setattr(_future, "EAGER_NOT_SUPPORTED", True) + return lazy + + +pytestmark = [pytest.mark.anyio] + + +@pytest.fixture +async def unhandled() -> AsyncIterator[list[dict[str, Any]]]: + """What the event loop's exception handler was given while the test ran: a task or a future whose exception + nobody retrieved, say. A test ends by asserting that it is empty.""" + loop = asyncio.get_running_loop() + found: list[dict[str, Any]] = [] + loop.set_exception_handler(lambda _loop, context: found.append(context)) + yield found + for _ in range(10): + await asyncio.sleep(0) + gc.collect() + loop.set_exception_handler(None) + assert not found + + +async def iterations(count: int) -> None: + for _ in range(count): + await asyncio.sleep(0) + + +# --- The acceptance test: a parallel step cut while one of its nodes runs ----------------------------------------- + + +class State(TypedDict): + par: Annotated[list[str], operator.add] + + +class HoldsWrites(SqlCheckpointSaver): + """The control: holds every write until the next ``aput``, and returns at once.""" + + def __init__(self, db: Any) -> None: + super().__init__(db) + self.held: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] + + async def aput_writes(self, *args: Any, **kwargs: Any) -> None: + self.held.append((args, kwargs)) + + async def aput(self, *args: Any, **kwargs: Any) -> RunnableConfig: + held, self.held = self.held, [] + for held_args, held_kwargs in held: + await super().aput_writes(*held_args, **held_kwargs) + return await super().aput(*args, **kwargs) + + +def parallel(ran: dict[str, int], gate: asyncio.Event | None = None, fail: bool = False) -> Any: + """START, then x and y at once, then join: y waits for ``gate``, and fails if it is told to.""" + + async def x(_: State) -> dict[str, list[str]]: + ran["x"] += 1 + return {"par": ["x"]} + + async def y(_: State) -> dict[str, list[str]]: + ran["y"] += 1 + if gate is not None: + await gate.wait() + if fail: + raise RuntimeError("y failed") + return {"par": ["y"]} + + async def join(_: State) -> dict[str, list[str]]: + ran["join"] += 1 + return {} + + graph = StateGraph(State) + graph.add_node("x", typing.cast(Any, x)) + graph.add_node("y", typing.cast(Any, y)) + graph.add_node("join", typing.cast(Any, join)) + graph.add_edge(START, "x") + graph.add_edge(START, "y") + graph.add_edge("x", "join") + graph.add_edge("y", "join") + graph.add_edge("join", END) + return graph + + +async def crash_while_y_runs(saver: Callable[[Any], SqlCheckpointSaver]) -> tuple[dict[str, int], list[str]]: + """Cut the run while y runs, with x finished, and resume from a copy of what was stored then.""" + backend = Backend() + ran = {"x": 0, "y": 0, "join": 0} + gate = asyncio.Event() + image: dict[str, bytes] = {} + + async def first(ctx: sessions.SessionContext) -> None: + app = parallel(ran, gate, fail=True).compile(checkpointer=saver(ctx.db)) + run = asyncio.create_task(app.ainvoke({"par": []}, THREAD, durability="sync")) + while ran["x"] == 0 or ran["y"] == 0: + await asyncio.sleep(0) + await iterations(300) # x's commit, and the writes' wait, are far inside this many iterations + image.update(backend.stored) # what is durable now: the crash + gate.set() + with pytest.raises(RuntimeError, match="y failed"): + await run + + await attempt(backend, first) + resumed = Backend() + resumed.stored = dict(image) # a new process: the copy only + result: dict[str, Any] = {} + + async def second(ctx: sessions.SessionContext) -> None: + app = parallel(ran).compile(checkpointer=saver(ctx.db)) + result.update(await app.ainvoke(None, THREAD, durability="sync")) + + await attempt(resumed, second) + return ran, sorted(result["par"]) + + +async def test_a_node_that_finished_does_not_run_again_after_a_crash_while_its_sibling_runs(): + ran, par = await crash_while_y_runs(SqlCheckpointSaver) + assert ran == {"x": 1, "y": 2, "join": 1} + assert par == ["x", "y"] + + +async def test_a_saver_that_holds_the_writes_until_the_next_put_runs_it_again_so_the_test_discriminates(): + ran, _ = await crash_while_y_runs(HoldsWrites) + assert ran["x"] == 2 + + +async def test_a_node_that_finished_does_not_run_again_after_the_attempt_fails_on_the_same_database(): + backend = Backend() + ran = {"x": 0, "y": 0, "join": 0} + + async def first(ctx: sessions.SessionContext) -> None: + app = parallel(ran, fail=True).compile(checkpointer=SqlCheckpointSaver(ctx.db)) + with pytest.raises(RuntimeError, match="y failed"): + await app.ainvoke({"par": []}, THREAD, durability="sync") + + async def second(ctx: sessions.SessionContext) -> None: + app = parallel(ran).compile(checkpointer=SqlCheckpointSaver(ctx.db)) + assert sorted((await app.ainvoke(None, THREAD, durability="sync"))["par"]) == ["x", "y"] + + await attempt(backend, first) + await attempt(backend, second) + assert ran == {"x": 1, "y": 2, "join": 1} + + +# --- A handler that returns right after the run: what the run leaves stored ---------------------------------------- + + +class Log(TypedDict): + log: Annotated[list[str], operator.add] + + +def interrupting(kind: str) -> Any: + """a, then b, which interrupts or fails.""" + + async def a(_: Log) -> dict[str, list[str]]: + return {"log": ["a"]} + + async def b(_: Log) -> dict[str, list[str]]: + if kind == "error": + raise RuntimeError("b failed") + return {"log": [str(interrupt("question?"))]} + + graph = StateGraph(Log) + graph.add_node("a", typing.cast(Any, a)) + graph.add_node("b", typing.cast(Any, b)) + graph.add_edge(START, "a") + graph.add_edge("a", "b") + graph.add_edge("b", END) + return graph + + +async def stored_writes(image: dict[str, bytes]) -> list[tuple[str, str]]: + """The writes in a copy of the store, as a new process would read them: (task, channel) of each.""" + copy = Backend() + copy.stored = dict(image) + found: list[tuple[str, str]] = [] + + async def read(ctx: sessions.SessionContext) -> None: + found.extend( + (str(task), str(channel)) + for task, channel in await ctx.db.values("SELECT task_id, channel FROM restate_langgraph_writes") + ) + + await attempt(copy, read) + return found + + +@pytest.mark.parametrize("durability", ["sync", "async", "exit"]) +@pytest.mark.parametrize("kind", ["interrupt", "error"]) +async def test_a_handler_that_returns_right_after_the_run_has_its_interrupt_or_error_stored( + kind: str, durability: typing.Literal["sync", "async", "exit"], unhandled: list[dict[str, Any]] +): + backend = Backend() + image: dict[str, bytes] = {} + + async def handler(ctx: sessions.SessionContext) -> None: + app = interrupting(kind).compile(checkpointer=SqlCheckpointSaver(ctx.db)) + try: + await app.ainvoke({"log": []}, THREAD, durability=durability) + except RuntimeError: + assert kind == "error" + image.update(backend.stored) # the handler returns at once: this is what it leaves + + await attempt(backend, handler) + channels = {channel for _, channel in await stored_writes(image)} + assert ("__interrupt__" if kind == "interrupt" else "__error__") in channels + assert not unhandled + + if kind == "interrupt": # a new saver over the same database shows the interrupt, and the run resumes from it + copy = Backend() + copy.stored = dict(image) + shown: list[Any] = [] + + async def resume(ctx: sessions.SessionContext) -> None: + app = interrupting(kind).compile(checkpointer=SqlCheckpointSaver(ctx.db)) + state = await app.aget_state(THREAD) + shown.extend(i.value for task in state.tasks for i in task.interrupts) + result = await app.ainvoke(Command(resume="yes"), THREAD, durability=durability) + assert result["log"] == ["a", "yes"] + + await attempt(copy, resume) + assert shown == ["question?"] + + +# --- The saver's own operations ------------------------------------------------------------------------------------ + + +def checkpoint_config(checkpoint: Checkpoint) -> RunnableConfig: + return {"configurable": {"thread_id": "t", "checkpoint_ns": "", "checkpoint_id": checkpoint["id"]}} + + +class Pair: + """A saver over a recording database, with a first checkpoint stored, whose writes the test makes.""" + + def __init__(self, ctx: sessions.SessionContext, backend: Backend) -> None: + self.spy = Spy(ctx.db) + self.saver = SqlCheckpointSaver(self.spy.database) + self.backend = backend + self.first = empty_checkpoint() + self.at = checkpoint_config(self.first) + + async def start(self) -> None: + """Store the first checkpoint, whose writes the test makes next.""" + await self.saver.aput({"configurable": {"thread_id": "t", "checkpoint_ns": ""}}, self.first, {}, {}) + self.spy.commits.clear() + + def write(self, task: str, *channels: str) -> asyncio.Task[None]: + """Call ``aput_writes`` for ``task`` as a task of its own: it returns once its rows are stored.""" + values = [(channel, f"{task}:{channel}") for channel in channels] + return asyncio.ensure_future(self.saver.aput_writes(self.at, values, task, f"~{task}")) + + def put(self) -> asyncio.Task[RunnableConfig]: + """Call ``aput`` of the checkpoint that follows the first, as a task of its own.""" + following = empty_checkpoint() + return asyncio.ensure_future(self.saver.aput(self.at, following, {"step": 1}, {})) + + def rows(self) -> list[Any]: + """The writes' rows of the commits, in order: a list of (task, channel).""" + return [ + (row[3], row[6]) + for commit in self.spy.commits + for table, row in commit + if table == WRITES and len(row) == 9 + ] + + def image(self) -> dict[str, bytes]: + return dict(self.backend.stored) + + +async def with_pair(body: Callable[[Pair], Coroutine[Any, Any, None]]) -> None: + backend = Backend() + + async def handler(ctx: sessions.SessionContext) -> None: + pair = Pair(ctx, backend) + await pair.start() + await body(pair) + + await attempt(backend, handler) + + +async def test_writes_and_the_put_that_follows_at_once_are_one_commit_with_the_writes_first_in_call_order( + unhandled: list[dict[str, Any]], +): + async def body(pair: Pair) -> None: + first, second = pair.write("a", "x", "y"), pair.write("b", "z") + put = pair.put() + await asyncio.gather(first, second, put) + assert pair.spy.tables == [[WRITES, CHECKPOINTS]] + assert pair.rows() == [("a", "x"), ("a", "y"), ("b", "z")] + assert [table for table, _ in pair.spy.commits[0]] == [WRITES, WRITES, WRITES, CHECKPOINTS] + # The first checkpoint shows them as LangGraph expects: (task, channel, value) in its order. + found = await pair.saver.aget_tuple(pair.at) + assert found is not None + assert found.pending_writes == [("a", "x", "a:x"), ("a", "y", "a:y"), ("b", "z", "b:z")] + + await with_pair(body) + assert not unhandled + + +async def test_a_write_that_no_put_follows_is_stored_alone_after_a_few_iterations_and_returns_then( + unhandled: list[dict[str, Any]], +): + async def body(pair: Pair) -> None: + write = pair.write("a", "x") + await asyncio.sleep(0) + assert not write.done() and pair.spy.commits == [] # it waits: a put may follow + await write + assert pair.spy.tables == [[WRITES]] + # A second connection over the same store has the rows when the write returned. + assert await stored_writes(pair.image()) == [("a", "x")] + + await with_pair(body) + assert not unhandled + + +async def test_a_write_awaited_before_the_put_is_called_does_not_wait_for_it_and_is_a_commit_of_its_own( + unhandled: list[dict[str, Any]], +): + async def body(pair: Pair) -> None: # the order of a delta channel's write, an error handler's, update_state's + await pair.write("a", "x") + await pair.put() + assert pair.spy.tables == [[WRITES], [CHECKPOINTS]] + + await with_pair(body) + assert not unhandled + + +async def test_writes_of_one_task_called_twice_in_a_commit_keep_their_verbs(): + async def body(pair: Pair) -> None: + # A special write replaces the one before; the others keep the first. + first = asyncio.ensure_future(pair.saver.aput_writes(pair.at, [("__error__", "one")], "a", "")) + second = asyncio.ensure_future(pair.saver.aput_writes(pair.at, [("__error__", "two")], "a", "")) + third = asyncio.ensure_future(pair.saver.aput_writes(pair.at, [("c", "one")], "b", "")) + fourth = asyncio.ensure_future(pair.saver.aput_writes(pair.at, [("c", "two")], "b", "")) + await asyncio.gather(first, second, third, fourth, pair.put()) + found = await pair.saver.aget_tuple(pair.at) + assert found is not None + assert found.pending_writes == [("a", "__error__", "two"), ("b", "c", "one")] + + await with_pair(body) + + +async def test_reads_prune_and_delete_store_what_is_pending_first(unhandled: list[dict[str, Any]]): + async def body(pair: Pair) -> None: + write = pair.write("a", "x") + await asyncio.sleep(0) # the write has been called + found = await pair.saver.aget_tuple(pair.at) # in the same iteration as the write + assert found is not None and found.pending_writes == [("a", "x", "a:x")] + assert write.done() or pair.spy.tables == [[WRITES]] + + other = pair.write("b", "y") + await asyncio.sleep(0) + listed = [c async for c in pair.saver.alist(pair.at)] + assert listed[0].pending_writes == [("a", "x", "a:x"), ("b", "y", "b:y")] + assert pair.spy.tables == [[WRITES], [WRITES]] + + third = pair.write("c", "z") + await asyncio.sleep(0) + await pair.saver.aprune(["t"]) # the first checkpoint is the latest: it keeps its writes + assert pair.spy.tables == [ + [WRITES], + [WRITES], + [WRITES], + [CHECKPOINTS, WRITES, "restate_langgraph_channel_values"], + ] + assert len(await stored_writes(pair.image())) == 3 + + last = pair.write("d", "w") + await asyncio.sleep(0) + await pair.saver.adelete_thread("t") + await asyncio.gather(write, other, third, last) + assert await stored_writes(pair.image()) == [] # the last write was stored before the delete, not after + assert pair.rows() == [("a", "x"), ("b", "y"), ("c", "z"), ("d", "w")] + + await with_pair(body) + assert not unhandled + + +async def test_a_lone_store_that_fails_fails_the_writes_it_carried_and_the_next_call_goes_ahead( + unhandled: list[dict[str, Any]], +): + async def body(pair: Pair) -> None: + pair.spy.fail = lambda tables: tables == [WRITES] + first, second = pair.write("a", "x"), pair.write("b", "y") + for write in (first, second): + with pytest.raises(RuntimeError, match="the commit failed"): + await write + pair.spy.fail = None + assert pair.spy.commits == [] # nothing was stored, and it is not tried again + await pair.write("c", "z") + assert await stored_writes(pair.image()) == [("c", "z")] + await iterations(20) + assert pair.rows() == [("c", "z")] + + await with_pair(body) + assert not unhandled + + +async def test_a_put_that_fails_fails_itself_and_the_writes_it_carried_and_the_next_calls_go_ahead( + unhandled: list[dict[str, Any]], +): + async def body(pair: Pair) -> None: + pair.spy.fail = lambda tables: CHECKPOINTS in tables + write = pair.write("a", "x") + put = pair.put() + for call in (write, put): + with pytest.raises(RuntimeError, match="the commit failed"): + await call + pair.spy.fail = None + await iterations(20) + assert pair.spy.commits == [] + await pair.write("b", "y") + await pair.put() + assert pair.rows() == [("b", "y")] + assert await stored_writes(pair.image()) == [("b", "y")] + + await with_pair(body) + assert not unhandled + + +async def test_a_flush_that_has_begun_is_stored_before_a_put_called_in_the_same_iteration( + lazy_tasks: bool, unhandled: list[dict[str, Any]] +): + """The write's rows wait, and are stored on their own just as a put is called, in the iteration where the wait + ended; the put is started at once (as LangGraph's are, on Python 3.12 and later), so it could take the database + first. The rows of the writes called before the put come first.""" + + async def body(pair: Pair) -> None: + loop = asyncio.get_running_loop() + first = pair.write("a", "x") + await asyncio.sleep(0) # the write has been called + results: list[asyncio.Task[Any]] = [] + + def start(coro: Coroutine[Any, Any, Any]) -> asyncio.Task[Any]: + if lazy_tasks: + return loop.create_task(coro) + return asyncio.eager_task_factory(loop, coro) # type: ignore[attr-defined,no-any-return] + + def late(count: int) -> None: + if count: # our own chain of iterations, one handle at a time, behind the write's + loop.call_soon(late, count - 1) + return + results.append(start(pair.saver.aput_writes(pair.at, [("y", "late")], "b", "~b"))) + results.append(start(pair.saver.aput(pair.at, empty_checkpoint(), {"step": 1}, {}))) + + loop.call_soon(late, 2) + await asyncio.gather(first, *results[:0]) + while len(results) < 2: + await asyncio.sleep(0) + await asyncio.gather(*results) + assert pair.rows() == [("a", "x"), ("b", "y")] + assert pair.spy.tables == [[WRITES], [WRITES, CHECKPOINTS]] + + await with_pair(body) + assert not unhandled + + +async def test_a_store_that_runs_after_the_handler_ended_fails_its_write_quietly(unhandled: list[dict[str, Any]]): + backend = Backend() + saver: list[SqlCheckpointSaver] = [] + writes: list[asyncio.Task[None]] = [] + + async def handler(ctx: sessions.SessionContext) -> None: + pair = Pair(ctx, backend) + await pair.start() + saver.append(pair.saver) + await pair.saver._lock.acquire() # the saver is busy: the write's rows wait for it, and the handler is over + writes.append(pair.write("a", "x")) + await iterations(5) + + await attempt(backend, handler) + saver[0]._lock.release() + with pytest.raises(RuntimeError, match="session is closed"): + await writes[0] + assert await stored_writes(dict(backend.stored)) == [] + assert not unhandled + + +# --- A run cancelled with a write pending --------------------------------------------------------------------------- + + +async def test_a_run_cancelled_with_a_write_pending_leaves_nothing_unhandled_and_the_next_attempt_resumes( + unhandled: list[dict[str, Any]], +): + backend = Backend() + ran = {"x": 0, "y": 0, "join": 0} + gate = asyncio.Event() + running: list[asyncio.Task[Any]] = [] + failing: list[Spy] = [] + + class Cancelling(SqlCheckpointSaver): + """Cancels the run in the iteration after x's writes are handed over.""" + + async def aput_writes( + self, config: RunnableConfig, writes: typing.Sequence[tuple[str, Any]], task_id: str, task_path: str = "" + ) -> None: + if any(channel == "par" for channel, _ in writes) and not failing[0].commits: + failing[0].commits.append([]) # once + asyncio.get_running_loop().call_soon(running[0].cancel) + await super().aput_writes(config, writes, task_id, task_path) + + async def first(ctx: sessions.SessionContext) -> None: + spy = Spy(ctx.db) + failing.append(spy) + # The write that is pending when the cancellation arrives cannot be stored: nobody awaits it any more. + spy.fail = lambda tables: tables == [WRITES] + app = parallel(ran, gate).compile(checkpointer=Cancelling(spy.database)) + running.append(asyncio.create_task(app.ainvoke({"par": []}, THREAD, durability="sync"))) + with pytest.raises(asyncio.CancelledError): + await running[0] + + await attempt(backend, first) + await iterations(100) # the handler is over: a late hop would run now + gc.collect() + assert not unhandled + gate.set() + + result: dict[str, Any] = {} + + async def second(ctx: sessions.SessionContext) -> None: + app = parallel(ran).compile(checkpointer=SqlCheckpointSaver(ctx.db)) + result.update(await app.ainvoke(None, THREAD, durability="sync")) + + await attempt(backend, second) + assert sorted(result["par"]) == ["x", "y"] + assert ran["join"] == 1 + assert 1 <= ran["x"] <= 2 diff --git a/tests/transactions_spy.py b/tests/transactions_spy.py new file mode 100644 index 00000000..5df8e82c --- /dev/null +++ b/tests/transactions_spy.py @@ -0,0 +1,75 @@ +# +# Copyright (c) 2023-2026 - Restate Software, Inc., Restate GmbH +# +# This file is part of the Restate SDK for Python, +# which is released under the MIT license. +# +# You can find a copy of the license in file LICENSE in the root +# directory of this repository or package, or at +# https://github.com/restatedev/sdk-typescript/blob/main/LICENSE +# +"""A database session that records the transactions of what runs over it: the tables each wrote, in order.""" + +# pylint: disable=missing-function-docstring,missing-class-docstring + +import contextlib +import re +import typing +from collections.abc import AsyncIterator, Callable +from typing import Any + +from restate.sessions import Database, DatabaseWriter + +WRITE = re.compile(r'(?:INSERT OR REPLACE INTO|INSERT OR IGNORE INTO|INSERT INTO|UPDATE|DELETE FROM)\s+"?(\w+)', re.I) + + +class _Recorder: + """A transaction that records the statements it runs, as the table and the parameters of each.""" + + def __init__(self, tx: DatabaseWriter, statements: list[tuple[str, list[Any]]]) -> None: + self._tx = tx + self._statements = statements + + async def execute(self, sql: str, params: Any = None) -> Any: + found = WRITE.match(sql) + if found: + self._statements.append((found.group(1), list(params or []))) + return await self._tx.execute(sql, params) + + def __getattr__(self, name: str) -> Any: + return getattr(self._tx, name) + + +class Spy: + """Passes everything to ``db``, and records each committed transaction as its statements. + + ``fail``, if set, is asked for the tables of each transaction when its body ends: if it says so, the transaction + fails, as a commit that the database refused, and rolls back. + """ + + def __init__(self, db: Database) -> None: + self.db = db + self.commits: list[list[tuple[str, list[Any]]]] = [] + self.fail: Callable[[list[str]], bool] | None = None + + @property + def tables(self) -> list[list[str]]: + """The tables each committed transaction wrote, in the order they were first written.""" + return [list(dict.fromkeys(table for table, _ in commit)) for commit in self.commits] + + @contextlib.asynccontextmanager + async def transaction(self) -> AsyncIterator[Any]: + statements: list[tuple[str, list[Any]]] = [] + async with self.db.transaction() as tx: + yield _Recorder(tx, statements) + if self.fail is not None and self.fail(list(dict.fromkeys(table for table, _ in statements))): + raise RuntimeError("the commit failed") + self.commits.append(statements) + + def __getattr__(self, name: str) -> Any: + return getattr(self.db, name) + + @property + def database(self) -> Database: + """This spy, as the database that a saver takes.""" + return typing.cast(Database, self) From e9f2f473c23f865a4c6a758245e99fedf1358754 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 16:24:10 +0100 Subject: [PATCH 12/13] Sessions: a run of working scopes beats once the silence reaches the interval, and once for scopes opened together --- python/restate/sessions/_driver.py | 14 ++++++--- tests/sessions_driver.py | 50 ++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 4 deletions(-) diff --git a/python/restate/sessions/_driver.py b/python/restate/sessions/_driver.py index 734d7673..2e673393 100644 --- a/python/restate/sessions/_driver.py +++ b/python/restate/sessions/_driver.py @@ -530,7 +530,8 @@ async def working(self) -> AsyncIterator[None]: self._scopes -= 1 def _start_heartbeats(self, every: float) -> None: - """A run of scopes opens: its beats are ``every`` after it opened, and every ``every`` while a scope stays open. + """A run of scopes opens: its first beat is due once the attempt has been silent for ``every`` (at once, if it + has), and the next ``every`` after each beat, while a scope stays open. The timer is armed for the first. On firing it beats if the run it finds is that old, waits out the rest if a run that opened later is younger, and is let go if no scope is open. @@ -539,11 +540,13 @@ def _start_heartbeats(self, every: float) -> None: return now = self._loop.time() # The first once the silence reaches an interval: at once, if it already has. - if now - self._wrote_at >= every: + first = self._wrote_at + every + if first <= now: self._heartbeat() + first = now + every self._run_every = every - self._next_beat = now + every - self._arm(self._next_beat) + self._next_beat = first + self._arm(first) def _arm(self, due: float) -> None: """Arm the timer for ``due``, unless it is armed for that or earlier.""" @@ -570,6 +573,9 @@ def _heartbeat(self) -> None: # If the attempt ended, the tick notices. with contextlib.suppress(SdkInternalBaseException): self.act(lambda vm: vm.heartbeat()) + # The write restarts Restate's inactivity timer, as the tick will note: scopes opened before it do not beat + # again. + self._wrote_at = self._loop.time() def _cancelled_error() -> TerminalError: diff --git a/tests/sessions_driver.py b/tests/sessions_driver.py index 83106324..381ba575 100644 --- a/tests/sessions_driver.py +++ b/tests/sessions_driver.py @@ -159,6 +159,24 @@ async def works_alone(ctx: sessions.SessionContext, kept: bool) -> str: return "done" +@notes.handler() +async def works_after_silence(ctx: sessions.SessionContext, args: list[float]) -> str: + """Is silent for ``args[0]`` seconds, then works in ``ctx.working`` (in ``args[1]`` scopes that follow one another + at once, if more than one) until the test lets it go on. Tells the gate when it started.""" + silence, scopes = args[0], int(args[1]) + gate_of().seen.append(str(asyncio.get_running_loop().time())) + await asyncio.sleep(silence) + if scopes > 1: + for _ in range(scopes): + async with ctx.working(): + pass + await gate_of().wait() + else: + async with ctx.working(): + await gate_of().wait() + return "done" + + @notes.handler() async def scopes_then_waits(ctx: sessions.SessionContext, scopes: int) -> str: """Opens and closes ``scopes`` scopes of ``ctx.working`` back to back (the database opens one a statement), then @@ -749,6 +767,38 @@ async def test_after_the_last_scope_closed_nothing_beats_and_nothing_is_left_run assert (beats, tasks, timers) == (0, 0, 1), describe(side) +async def test_a_scope_opened_part_way_into_an_interval_of_silence_beats_when_the_silence_reaches_the_interval( + gate: Gate, monkeypatch +): + # Silent for 0.3 s of a 0.4 s interval, then working: the first beat is due at 0.4 s of silence, not 0.4 s after + # the scope opened (0.7 s), or Restate may hear nothing for nearly two intervals. + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.4)) + side = RestateSide() + side.start("kt5", [0.3, 1]) + running = asyncio.ensure_future(run(notes, "works_after_silence", side)) + await gate.reached.wait() + started = float(gate.seen[0]) + await asyncio.sleep(max(0.0, started + 0.55 - asyncio.get_running_loop().time())) + beats = heartbeats(side) + gate.opened.set() + await running + assert beats == 1, describe(side) + + +async def test_scopes_opened_together_after_a_long_silence_send_one_heartbeat(gate: Gate, monkeypatch): + monkeypatch.setattr(_driver, "HEARTBEAT_INTERVAL", timedelta(seconds=0.2)) + side = RestateSide() + side.start("kt6", [0.3, 3]) + running = asyncio.ensure_future(run(notes, "works_after_silence", side)) + await gate.reached.wait() + # The scopes closed at once; the timer of the run fires after an interval, finds none open, and sends nothing. + await asyncio.sleep(0.1) + beats = heartbeats(side) + gate.opened.set() + await running + assert beats == 1, describe(side) + + @pytest.mark.parametrize("value", ["", "abc", "0", "-5", "nan", "inf", "1_0", "1e999"]) def test_an_invalid_heartbeat_setting_is_the_default(monkeypatch, value: str): monkeypatch.setenv("RESTATE_SESSIONS_HEARTBEAT", value) From 503261d5a3470aaf9694c23395f92699596e4e19 Mon Sep 17 00:00:00 2001 From: igalshilman Date: Tue, 24 Nov 2026 17:37:11 +0100 Subject: [PATCH 13/13] Tests: the eager-start run of the flush-before-put test needs asyncio.eager_task_factory, which 3.11 lacks; it hung there --- tests/agents_langgraph_writes.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/agents_langgraph_writes.py b/tests/agents_langgraph_writes.py index 1cbf3768..ba90b941 100644 --- a/tests/agents_langgraph_writes.py +++ b/tests/agents_langgraph_writes.py @@ -479,6 +479,8 @@ async def test_a_flush_that_has_begun_is_stored_before_a_put_called_in_the_same_ """The write's rows wait, and are stored on their own just as a put is called, in the iteration where the wait ended; the put is started at once (as LangGraph's are, on Python 3.12 and later), so it could take the database first. The rows of the writes called before the put come first.""" + if not lazy_tasks and not hasattr(asyncio, "eager_task_factory"): + pytest.skip("Python 3.11 has no eager tasks: LangGraph never starts a task at once there") async def body(pair: Pair) -> None: loop = asyncio.get_running_loop() @@ -500,8 +502,11 @@ def late(count: int) -> None: loop.call_soon(late, 2) await asyncio.gather(first, *results[:0]) - while len(results) < 2: + for _ in range(100): # bounded: a callback that failed must fail the test, not hang it + if len(results) == 2: + break await asyncio.sleep(0) + assert len(results) == 2 await asyncio.gather(*results) assert pair.rows() == [("a", "x"), ("b", "y")] assert pair.spy.tables == [[WRITES], [WRITES, CHECKPOINTS]]