Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/langchain-submilli/NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,8 @@ expiry tests. The HTTP client now lives in its own package, `submilli`
- `client=` takes a ready `submilli.AsyncSubmilli`, which can wrap your own `httpx.AsyncClient`.
The managed client keeps one `httpx.AsyncClient` per event loop, because applications and tests
often run several loops.
- The default request timeout is 330 s. The server may wait up to 300 s for a running request
with the same idempotency key.
- The default request timeout is 330 s, leaving room for long-running programs and in-flight
idempotent retries waiting for an active run to finish.
- **Async only.** The tools' sync entry points raise `NotImplementedError` with a pointer to
`ainvoke`. deepagents does not require a sync API.
- One `SubmilliMiddleware` per agent: two instances would share the `submilli_session` key.
Expand Down
5 changes: 3 additions & 2 deletions packages/langchain-submilli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ instructions for using them from the Submilli server.
- Harness secrets are sent when a session opens and are never stored in agent state. End the
session before using rotated secrets.
- Each execute call sends an `Idempotency-Key` derived from the LangChain tool call id. A
repeated call replays the recorded result. The middleware reports conflicts and incomplete,
in-progress, or unavailable replays without silently rerunning the program.
repeated call waits for an in-flight run or replays the recorded result. The middleware
reports conflicts and incomplete or unavailable replays without silently rerunning the
program.
- When a session has ended, the middleware opens a replacement. If a restarted server asks for
the session's secrets, it rebinds them once and retries.
- On a server with durable execution, the middleware waits for a queued run. A run that stops
Expand Down
27 changes: 25 additions & 2 deletions packages/langchain-submilli/tests/unit_tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,15 @@ async def test_lost_secrets_are_sent_again_with_rebind(server: FakeServer) -> No
(503, "idempotency_unavailable", "could not read or write"),
],
)
async def test_idempotency_refusals_are_explained(server: FakeServer, status: int, code: str, phrase: str) -> None:
server.refuse_next.append((status, {"error": code, "detail": "server detail", "execution_id": "e-1"}))
async def test_idempotency_refusals_are_explained(
server: FakeServer, monkeypatch: pytest.MonkeyPatch, status: int, code: str, phrase: str
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
refusal = (status, {"error": code, "detail": "server detail", "execution_id": "e-1"})
server.refuse_next.extend([refusal] * (3 if code == "idempotency_in_progress" else 1))
message = tool_message(await run(agent(calls_then_done(execute("a")), middleware())))
body = content(message)
assert body["error"]["kind"] == code
Expand All @@ -244,6 +251,22 @@ async def test_idempotency_refusals_are_explained(server: FakeServer, status: in
assert message.artifact["execution_id"] == "e-1"


async def test_idempotency_in_progress_retries_with_the_same_key_and_returns_the_result(
server: FakeServer, monkeypatch: pytest.MonkeyPatch
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
server.refuse_next.append((503, {"error": "idempotency_in_progress", "detail": "still running"}))
result = await run(agent(calls_then_done(execute("code", id="toolu_retry")), middleware()))
message = tool_message(result)
assert message.status == "success"
assert content(message) == {"result": "ok", "console": [], "error": None, "denied": False}
executes = server.calls("POST", r"/v1/sessions/.*/execute")
assert [req.headers["idempotency-key"] for req in executes] == ["toolu_retry", "toolu_retry"]


async def test_incomplete_tells_the_model_to_check_before_retrying(server: FakeServer) -> None:
server.refuse_next.append((409, {"error": "idempotency_incomplete", "detail": "never recorded"}))
body = content(tool_message(await run(agent(calls_then_done(execute("a")), middleware()))))
Expand Down
4 changes: 2 additions & 2 deletions packages/openai-agents-submilli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ instructions for using them from the Submilli server.
- Harness secrets are sent when a session opens and are never stored. End the session before
using rotated secrets.
- Each execute call sends an `Idempotency-Key` derived from the SDK's tool call id. A repeated
call replays the recorded result. The toolkit reports conflicts and incomplete, in-progress,
or unavailable replays without silently rerunning the program.
call waits for an in-flight run or replays the recorded result. The toolkit reports conflicts
and incomplete or unavailable replays without silently rerunning the program.
- When a session has ended, the toolkit opens a replacement and tells the model. If a restarted
server asks for the session's secrets, it rebinds them once and retries.
- On a server with durable execution, the toolkit waits for a queued run. A run that stops
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,9 +151,10 @@ async def on_call(call: PendingCall) -> ToolResult:
result, _ = answer(call.call_id, outputs[call.call_id])
return result

state: RunState | None = None
try:
# With the same key, this answers the run's current state.
state: RunState = await self.client.sessions.execute(
state = await self.client.sessions.execute(
session_id, program.code, idempotency_key=program.idempotency_key
)
result = await self.client.runs.complete(state, on_tool_call=on_call)
Expand All @@ -171,9 +172,8 @@ async def on_call(call: PendingCall) -> ToolResult:
outcome = t.lost_run_outcome(execution_id="", session_id=session_id, tool_calls=records)
return _response(_message(final_text(outcome)))
except UnknownRunError as error:
outcome = t.lost_run_outcome(
execution_id=error.execution_id or "", session_id=session_id, tool_calls=records
)
execution_id = error.execution_id or (state.execution_id if state is not None else "")
outcome = t.lost_run_outcome(execution_id=execution_id, session_id=session_id, tool_calls=records)
return _response(_message(final_text(outcome)))
if not isinstance(result, ExecuteResult): # pragma: no cover - `complete` returns only finished runs
raise TypeError(f"unexpected run state {result!r}")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
from openai_agents_submilli._sessions import InMemorySessionStore, SessionStore, SubmilliSession
from submilli import (
AsyncSubmilli,
ExecuteResult,
IdempotencyError,
PackageDocsEntry,
RunStateError,
SessionRequiresSecretsError,
SubmilliError,
UnknownRunError,
UnknownSessionError,
idempotency_key,
)
Expand Down Expand Up @@ -285,17 +285,18 @@ async def _run(
run's context.
"""
if self._program_agent is None:
state = None
try:
state = await self.client.sessions.execute(session_id, code, idempotency_key=key)
result = await self.client.runs.complete(state)
except IdempotencyError as error:
return t.idempotency_outcome(error, session_id=session_id)
except RunStateError as error:
return t.run_state_outcome(error, session_id=session_id, tool_calls=[])
if not isinstance(state, ExecuteResult):
raise SubmilliError(
f"run {state.execution_id} did not finish, in a session opened without application tools"
)
return t.execute_outcome(state, notice=notice)
except UnknownRunError as error:
execution_id = error.execution_id or (state.execution_id if state is not None else "")
return t.lost_run_outcome(execution_id=execution_id, session_id=session_id, tool_calls=[])
return t.execute_outcome(result, notice=notice)
# With application tools the nested agent runs the program, from its
# first execute on. A program resumed after an approval continues from
# the nested run the SDK saved, whose input names the session it began
Expand Down
36 changes: 36 additions & 0 deletions packages/openai-agents-submilli/tests/unit_tests/test_app_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -269,3 +269,39 @@ async def test_approvals_work_in_a_streamed_run(server: FakeServer) -> None:
assert streamed.final_output == "done"
[output] = [item for item in streamed.new_items if isinstance(item, ToolCallOutputItem)]
assert json.loads(json.loads(output.output)["result"]) == ["refunded 18.0 on o_7"]


async def test_durable_queued_and_running_states_are_polled_around_tool_calls(
server: FakeServer, monkeypatch: pytest.MonkeyPatch
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
server.durable_next = [{"status": "queued", "execution_id": "run-1", "durable": True}]
call_item = {"call_id": "run-1:1", "tool": "greet", "args": {"name": "Ada"}}
server.views["run-1"] = [
{"status": "running", "execution_id": "run-1", "durable": True},
{"status": "suspended", "execution_id": "run-1", "session_id": "s", "calls": [call_item]},
]
submilli = toolkit(greet)
# Seed the suspended run so `POST /v1/runs/run-1/resume` can answer it, then
# return `running` on the second execute (after the nested tool call) before finishing.
from tests.unit_tests.fake_server import Run

assistant = agent(submilli, calls_then_done(execute("main()", id="call_ptc_dur")))
session_created = server.open

def open_and_seed(body: dict[str, Any]) -> Any:
resp = session_created(body)
session_id = json.loads(resp.content)["session_id"]
server.suspended["run-1"] = Run("run-1", session_id, [("greet", {"name": "Ada"})])
server.durable_next.append({"status": "running", "execution_id": "run-1", "durable": True})
return resp

monkeypatch.setattr(server, "open", open_and_seed)
result = await Runner.run(assistant, "go", context=ADA)
output = execute_output(result)
reported = json.loads(output.output)
assert json.loads(reported["result"]) == ["hello Ada"]
assert len(server.calls("GET", "/v1/runs/run-1")) >= 3
49 changes: 49 additions & 0 deletions packages/openai-agents-submilli/tests/unit_tests/test_toolkit.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,55 @@ async def test_a_durable_run_without_a_result_is_reported_not_raised(server: Fak
assert output.custom_data is not None and output.custom_data["run_status"] == "stuck"


async def test_a_queued_or_running_durable_run_is_waited_for(
server: FakeServer, monkeypatch: pytest.MonkeyPatch
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
server.durable_next = [{"status": "queued", "execution_id": "run-1", "durable": True}]
retained = {"status": "finished", "execution_id": "run-1", "session_id": "s", "result": "42", "console": []}
server.views["run-1"] = [
{"status": "running", "execution_id": "run-1", "durable": True},
{"status": "completed", "execution_id": "run-1", "durable": True, "response": {**retained, "error": None}},
]
result = await run(toolkit(), calls_then_done(execute("a", id="call_dur")))
[output] = outputs(result)
assert content(output) == {"result": "42", "console": [], "error": None, "denied": False}
assert output.custom_data is not None and output.custom_data["execution_id"] == "run-1"
assert len(server.calls("GET", "/v1/runs/run-1")) == 2


async def test_a_lost_durable_run_keeps_its_execution_id_in_custom_data(
server: FakeServer, monkeypatch: pytest.MonkeyPatch
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
server.durable_next = [{"status": "queued", "execution_id": "run-lost-1", "durable": True}]
result = await run(toolkit(), calls_then_done(execute("a", id="call_lost")))
[output] = outputs(result)
assert content(output)["error"]["kind"] == "run_lost"
assert output.custom_data is not None and output.custom_data["execution_id"] == "run-lost-1"


async def test_idempotency_in_progress_retries_with_the_same_key_and_returns_the_result(
server: FakeServer, monkeypatch: pytest.MonkeyPatch
) -> None:
async def no_sleep(_: float) -> None:
return None

monkeypatch.setattr("submilli._async_client.asyncio.sleep", no_sleep)
server.refuse_next = [(503, {"error": "idempotency_in_progress", "detail": "still running"})]
result = await run(toolkit(), calls_then_done(execute("a", id="call_retry")))
[output] = outputs(result)
assert content(output) == {"result": "ok", "console": [], "error": None, "denied": False}
executes = server.calls("POST", r"/v1/sessions/[^/]+/execute")
assert [req.headers["idempotency-key"] for req in executes] == ["call_retry", "call_retry"]


async def test_the_same_tool_call_replays(server: FakeServer) -> None:
submilli = toolkit()
await run(submilli, calls_then_done(execute("a", id="call_same")))
Expand Down
4 changes: 2 additions & 2 deletions packages/submilli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,8 +230,8 @@ across restarts. A server whose key changed refuses such a session with a `Confl
A connection failure, or a 502, 503, or 504, is retried up to `max_retries` times (default 2),
with backoff, but only for requests that are safe to repeat: reads, deletes, rebinds, resumes,
and executes that carry an idempotency key. An execute without a key and `sessions.create` are
never retried. The default timeout is 330 seconds, because an execute may wait up to 300 seconds
for an earlier attempt with the same key.
never retried. The default timeout is 330 seconds, leaving room for long-running programs and
in-flight idempotent retries waiting for an active run to finish.

```python
client = AsyncSubmilli(timeout=60.0, max_retries=0, http_client=httpx.AsyncClient(...))
Expand Down
1 change: 1 addition & 0 deletions packages/submilli/src/submilli/_async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,7 @@ async def complete(
except (RunNotSuspendedError, UnknownCallError):
# A call timed out, or another attempt answered it: look again.
state = await self.retrieve(state.execution_id)
delay = poll_interval
return state


Expand Down
10 changes: 6 additions & 4 deletions packages/submilli/src/submilli/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@
from submilli._version import __version__

DEFAULT_BASE_URL = "http://127.0.0.1:8128"
# An execute may wait up to 300 seconds on the server for an earlier attempt
# with the same idempotency key; leave room for that.
# Programs and in-flight idempotent retries wait on the server until the run
# settles; leave room for long-running executions.
DEFAULT_TIMEOUT = 330.0
DEFAULT_MAX_RETRIES = 2
# The longest `Idempotency-Key` the server accepts, in bytes.
Expand Down Expand Up @@ -99,8 +99,10 @@ def should_retry(response: httpx.Response) -> bool:
code = response.json().get("error")
except (ValueError, AttributeError):
return True
# An idempotency refusal is the server's answer, not a transient failure.
return code not in IDEMPOTENCY_CODES
# Older servers answer 503 `idempotency_in_progress` when an earlier attempt
# with this key is still running; retrying with the same key picks up its
# result. Other idempotency codes are terminal refusals.
return not isinstance(code, str) or code == "idempotency_in_progress" or code not in IDEMPOTENCY_CODES


def retry_delay(attempt: int, response: httpx.Response | None) -> float:
Expand Down
1 change: 1 addition & 0 deletions packages/submilli/src/submilli/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ def complete(
except (RunNotSuspendedError, UnknownCallError):
# A call timed out, or another attempt answered it: look again.
state = self.retrieve(state.execution_id)
delay = poll_interval
return state


Expand Down
9 changes: 5 additions & 4 deletions packages/submilli/src/submilli/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,11 @@ class IdempotencyError(APIStatusError):

`code` says why: `idempotency_conflict` (the key was used with other code),
`idempotency_incomplete` (an earlier attempt never recorded an outcome, so
its effects are unknown), `idempotency_in_progress` (an earlier attempt is
still running), `idempotency_unavailable` (the record could not be read or
written), `idempotency_response_expired` (the earlier result is no longer
retained), or `idempotency_key_invalid`.
its effects are unknown), `idempotency_in_progress` (an older server still
had an earlier attempt running after retries were exhausted),
`idempotency_unavailable` (the record could not be read or written),
`idempotency_response_expired` (the earlier result is no longer retained),
or `idempotency_key_invalid`.
"""

@property
Expand Down
Loading