Skip to content

Commit f320afa

Browse files
aringuyen3claude
andcommitted
fix(examples): skip events Temporal signal handlers can't process
Every Temporal tutorial (000-150), the base temporal template used by `agentex init` and the procurement demo now check an event before acting on it, and log and return for content they cannot process instead of raising on it or dereferencing it: anything but TextContent in most handlers (010 and 050 also skip events the user did not write, and 030 also takes its DataContent queue controls), and only missing content in the handlers that echo every event. A signal that arrives before on_task_create waits for the state instead of raising, the procurement demo drops malformed send_event payloads, and span.output is only set when tracing returned a span. Each tutorial gets offline signal-handler tests. Their setup is a module-scoped fixture in the tutorial's conftest.py that applies only to that tutorial's tests, so one pytest session can run several tutorials; 150_codex's conftest moves to the same pattern, and 090's project/ gets the empty __init__.py every other tutorial has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6636503 commit f320afa

49 files changed

Lines changed: 3181 additions & 113 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎examples/demos/procurement_agent/project/workflow.py‎

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -129,21 +129,27 @@ async def on_task_event_send(self, params: SendEventParams) -> None:
129129
First event: Triggers the initial agent workflow execution.
130130
Subsequent events: Feed the wait_for_human tool's human_queue.
131131
"""
132-
if self._state is None:
133-
raise ValueError("State is not initialized")
134-
135-
if params.event.content is None:
132+
# Skip events this agent can't handle instead of raising: an exception here fails
133+
# the workflow task, and Temporal replays the signal forever, wedging the task.
134+
# Any content type can be displayed, but an event can arrive with no content.
135+
content = params.event.content
136+
if content is None:
136137
workflow.logger.warning("Received event with no content")
137138
return
138139

140+
# A signal can arrive before on_task_create has initialised state (e.g. with
141+
# signal-with-start): wait for it rather than drop the user's message.
142+
while self._state is None:
143+
await workflow.wait_condition(lambda: self._state is not None)
144+
139145
# Display the user's message in the UI
140-
await adk.messages.create(task_id=params.task.id, content=params.event.content)
146+
await adk.messages.create(task_id=params.task.id, content=content)
141147

142148
# After the first event, all subsequent events are human responses to wait_for_human
143149
if self._workflow_started:
144150
# Extract text content and put it in the human_queue for wait_for_human tool
145-
if isinstance(params.event.content, TextContent):
146-
await self.human_queue.put(params.event.content.content)
151+
if isinstance(content, TextContent):
152+
await self.human_queue.put(content.content)
147153

148154
@workflow.run
149155
@override
@@ -386,49 +392,52 @@ async def send_event(self, event: str) -> None:
386392
Receives event strings from external systems with validation.
387393
Events should be JSON strings with event_type and required fields.
388394
Example: {"event_type":"Submittal_Approved","item":"Steel Beams"}
395+
396+
Invalid events are logged and dropped, never raised: an exception in a signal
397+
handler fails the workflow task, and Temporal replays the signal forever. The
398+
sender never sees the error either way, since signals do not return results.
389399
"""
390400
# Validate event is not None or empty
391401
if not event:
392402
logger.error("Received empty or None event")
393-
raise ValueError("Event cannot be empty or None")
403+
return
394404

395405
# Validate event is a string
396406
if not isinstance(event, str):
397407
logger.error(f"Event must be string, got {type(event)}")
398-
raise ValueError(f"Event must be a string, received {type(event).__name__}")
408+
return
399409

400410
# Validate event length (prevent DoS)
401411
if len(event) > 50000: # 50KB limit
402412
logger.error(f"Event too large: {len(event)} characters")
403-
raise ValueError(f"Event exceeds maximum size (50KB)")
413+
return
404414

405-
# Validate event is valid JSON
415+
# Validate event is valid JSON. Catch ValueError, not just its subclass JSONDecodeError: an integer
416+
# literal longer than Python's int digit limit raises a plain ValueError, and deeply nested input
417+
# raises RecursionError.
406418
try:
407419
event_data = json.loads(event)
408-
except json.JSONDecodeError as e:
420+
except (ValueError, RecursionError) as e:
409421
logger.error(f"Event is not valid JSON: {e}")
410-
raise ValueError(f"Event must be valid JSON: {e}") from e
422+
return
411423

412424
# Validate event has required structure
413425
if not isinstance(event_data, dict):
414426
logger.error(f"Event JSON must be an object, got {type(event_data)}")
415-
raise ValueError("Event must be a JSON object")
427+
return
416428

417429
# Validate event_type field exists
418430
if "event_type" not in event_data:
419431
logger.error("Event missing 'event_type' field")
420-
raise ValueError("Event must contain 'event_type' field")
432+
return
421433

422434
# Validate event_type is one of the allowed types
423435
event_type_str = event_data["event_type"]
424436
valid_event_types = [e.value for e in EventType]
425437

426438
if event_type_str not in valid_event_types:
427439
logger.error(f"Invalid event_type: {event_type_str}. Valid types: {valid_event_types}")
428-
raise ValueError(
429-
f"Invalid event_type '{event_type_str}'. "
430-
f"Must be one of: {', '.join(valid_event_types)}"
431-
)
440+
return
432441

433442
# Validate event structure based on type using Pydantic models
434443
try:
@@ -448,7 +457,7 @@ async def send_event(self, event: str) -> None:
448457

449458
except Exception as e:
450459
logger.error(f"Event validation failed for {event_type_str}: {e}")
451-
raise ValueError(f"Invalid event structure for {event_type_str}: {e}") from e
460+
return
452461

453462
logger.info(f"Validated event type: {event_type_str}")
454463
await self.event_queue.put(event)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Pytest setup for this tutorial's tests.
2+
3+
``project.workflow`` reads environment variables when it is imported, so the offline tests need them set and
4+
this tutorial's ``project`` package importable. Both are arranged here for this tutorial's tests only, and any
5+
``project`` package already imported (another tutorial's, in a session that collects several) is cleared before
6+
and after them.
7+
"""
8+
9+
from __future__ import annotations
10+
11+
import os
12+
import sys
13+
from collections.abc import Iterator
14+
15+
import pytest
16+
17+
TUTORIAL_DIR = os.path.dirname(os.path.abspath(__file__))
18+
19+
# Values already set in the environment win.
20+
ENV_DEFAULTS = {
21+
"AGENT_NAME": "at000-hello-acp",
22+
"ACP_URL": "http://localhost:8000",
23+
"WORKFLOW_NAME": "at000-hello-acp",
24+
}
25+
26+
27+
def _forget_project_modules() -> None:
28+
for name in [name for name in sys.modules if name == "project" or name.startswith("project.")]:
29+
del sys.modules[name]
30+
31+
32+
@pytest.fixture(autouse=True, scope="module")
33+
def _tutorial_environment() -> Iterator[None]:
34+
with pytest.MonkeyPatch.context() as patch:
35+
for name, value in ENV_DEFAULTS.items():
36+
if not os.environ.get(name):
37+
patch.setenv(name, value)
38+
patch.syspath_prepend(TUTORIAL_DIR)
39+
_forget_project_modules()
40+
try:
41+
yield
42+
finally:
43+
_forget_project_modules()

‎examples/tutorials/10_async/10_temporal/000_hello_acp/project/workflow.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,18 @@ def __init__(self):
3333
@workflow.signal(name=SignalName.RECEIVE_EVENT)
3434
@override
3535
async def on_task_event_send(self, params: SendEventParams) -> None:
36+
# Skip events this agent can't handle instead of raising: an exception here fails
37+
# the workflow task, and Temporal replays the signal forever, wedging the task.
38+
# Any content type can be echoed back, but an event can arrive with no content.
39+
content = params.event.content
40+
if content is None:
41+
logger.warning("Ignoring event with no content for task %s", params.task.id)
42+
return
43+
3644
logger.info(f"Received task message instruction: {params}")
3745

3846
# 2. Echo back the client's message to show it in the UI. This is not done by default so the agent developer has full control over what is shown to the user.
39-
await adk.messages.create(task_id=params.task.id, content=params.event.content)
47+
await adk.messages.create(task_id=params.task.id, content=content)
4048

4149
# 3. Send a simple response message.
4250
# In future tutorials, this is where we'll add more sophisticated response logic.

‎examples/tutorials/10_async/10_temporal/000_hello_acp/tests/test_agent.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
- Non-streaming event sending and polling
66
- Streaming event sending
77
8+
It also unit-tests the workflow's signal handler offline (TestOfflineSignalHandler),
9+
which needs no running agent, Temporal or network.
10+
811
To run these tests:
912
1. Make sure the agent is running (via docker-compose or `agentex agents run`)
1013
2. Set the AGENTEX_API_BASE_URL environment variable if not using default
@@ -19,6 +22,8 @@
1922
import uuid
2023
import asyncio
2124
from typing import Any
25+
from datetime import datetime, timezone
26+
from unittest.mock import AsyncMock, patch
2227

2328
import pytest
2429
import pytest_asyncio
@@ -30,8 +35,17 @@
3035

3136
from agentex import AsyncAgentex
3237
from agentex.types import TaskMessage
38+
from agentex.types.task import Task
39+
from agentex.types.agent import Agent
40+
from agentex.types.event import Event
41+
from agentex.lib.types.acp import SendEventParams
42+
from agentex.types.data_content import DataContent
43+
from agentex.types.text_content import TextContent
3344
from agentex.types.agent_rpc_params import ParamsCreateTaskRequest
45+
from agentex.types.reasoning_content import ReasoningContent
3446
from agentex.types.text_content_param import TextContentParam
47+
from agentex.types.tool_request_content import ToolRequestContent
48+
from agentex.types.tool_response_content import ToolResponseContent
3549

3650
# Configuration from environment variables
3751
AGENTEX_API_BASE_URL = os.environ.get("AGENTEX_API_BASE_URL", "http://localhost:5003")
@@ -185,5 +199,87 @@ async def stream_messages() -> None:
185199
assert user_echo_found, "User message echo not found in stream"
186200
assert agent_response_found, "Agent response not found in stream"
187201

202+
203+
# ---------------------------------------------------------------------------
204+
# Offline signal-handler tests (no running agent, Temporal or network needed)
205+
# ---------------------------------------------------------------------------
206+
207+
TASK_ID = "task-offline-1"
208+
209+
210+
def _send_event_params(content: Any) -> SendEventParams:
211+
"""Real ``SendEventParams``, as the ACP delivers an ``event/send`` to the workflow signal."""
212+
now = datetime.now(timezone.utc)
213+
return SendEventParams(
214+
agent=Agent(id="agent-1", acp_type="async", name=AGENT_NAME, description="", created_at=now, updated_at=now),
215+
task=Task(id=TASK_ID),
216+
event=Event(id="event-1", agent_id="agent-1", task_id=TASK_ID, sequence_id=1, content=content),
217+
)
218+
219+
220+
# Every content type a caller can send. This handler only echoes the content back, so
221+
# all of them are valid input: the one thing it cannot echo is an event with no content.
222+
ECHOED_CONTENTS = [
223+
pytest.param(TextContent(author="user", content="Hello!"), id="text"),
224+
pytest.param(DataContent(author="user", data={}), id="data"),
225+
pytest.param(ReasoningContent(author="user", summary=["thinking"], type="reasoning"), id="reasoning"),
226+
pytest.param(
227+
ToolRequestContent(author="user", name="get_weather", tool_call_id="call-1", arguments={"city": "Paris"}),
228+
id="tool-request",
229+
),
230+
pytest.param(
231+
ToolResponseContent(author="user", name="get_weather", tool_call_id="call-1", content={"k": "v"}),
232+
id="tool-response-dict",
233+
),
234+
pytest.param(
235+
ToolResponseContent(author="user", name="get_weather", tool_call_id="call-1", content=[1, 2]),
236+
id="tool-response-list",
237+
),
238+
]
239+
240+
241+
class TestOfflineSignalHandler:
242+
"""Unit tests for ``on_task_event_send`` that need no running agent, Temporal or network.
243+
244+
The handler is called directly with real ``SendEventParams``; ``adk.messages.create``
245+
is mocked, so nothing leaves the process.
246+
"""
247+
248+
@staticmethod
249+
def _workflow():
250+
from project.workflow import At000HelloAcpWorkflow
251+
252+
# Build the instance without Temporal: skip __init__ and set what it would set.
253+
wf = At000HelloAcpWorkflow.__new__(At000HelloAcpWorkflow)
254+
wf.display_name = AGENT_NAME
255+
wf._complete_task = False
256+
return wf
257+
258+
@pytest.mark.asyncio
259+
async def test_event_without_content_is_ignored(self):
260+
"""No content: return without raising (that would wedge the task) and send nothing."""
261+
with patch("project.workflow.adk.messages.create", new=AsyncMock()) as create:
262+
wf = self._workflow()
263+
await wf.on_task_event_send(_send_event_params(None))
264+
265+
create.assert_not_awaited()
266+
assert wf._complete_task is False
267+
268+
@pytest.mark.asyncio
269+
@pytest.mark.parametrize("content", ECHOED_CONTENTS)
270+
async def test_event_is_echoed_then_answered(self, content):
271+
"""Any content type is echoed back unchanged, then the agent replies."""
272+
with patch("project.workflow.adk.messages.create", new=AsyncMock()) as create:
273+
wf = self._workflow()
274+
await wf.on_task_event_send(_send_event_params(content))
275+
276+
assert create.await_count == 2
277+
echo, reply = create.await_args_list
278+
assert echo.kwargs == {"task_id": TASK_ID, "content": content}
279+
assert reply.kwargs["task_id"] == TASK_ID
280+
assert isinstance(reply.kwargs["content"], TextContent)
281+
assert reply.kwargs["content"].author == "agent"
282+
283+
188284
if __name__ == "__main__":
189285
pytest.main([__file__, "-v"])
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Pytest setup for this tutorial's tests.
2+
3+
``project.workflow`` reads environment variables when it is imported, so the offline tests need them set and
4+
this tutorial's ``project`` package importable. Both are arranged here for this tutorial's tests only, and any
5+
``project`` package already imported (another tutorial's, in a session that collects several) is cleared before
6+
and after them.
7+
"""
8+
9+
from __future__ import annotations
10+
11+
import os
12+
import sys
13+
from collections.abc import Iterator
14+
15+
import pytest
16+
17+
TUTORIAL_DIR = os.path.dirname(os.path.abspath(__file__))
18+
19+
# Values already set in the environment win.
20+
ENV_DEFAULTS = {
21+
"AGENT_NAME": "at010-agent-chat",
22+
"ACP_URL": "http://localhost:8000",
23+
"WORKFLOW_NAME": "at010-agent-chat",
24+
}
25+
26+
27+
def _forget_project_modules() -> None:
28+
for name in [name for name in sys.modules if name == "project" or name.startswith("project.")]:
29+
del sys.modules[name]
30+
31+
32+
@pytest.fixture(autouse=True, scope="module")
33+
def _tutorial_environment() -> Iterator[None]:
34+
with pytest.MonkeyPatch.context() as patch:
35+
for name, value in ENV_DEFAULTS.items():
36+
if not os.environ.get(name):
37+
patch.setenv(name, value)
38+
patch.syspath_prepend(TUTORIAL_DIR)
39+
_forget_project_modules()
40+
try:
41+
yield
42+
finally:
43+
_forget_project_modules()

0 commit comments

Comments
 (0)