-
Notifications
You must be signed in to change notification settings - Fork 425
Expand file tree
/
Copy pathtest_scenarios.py
More file actions
2233 lines (1889 loc) · 72.1 KB
/
test_scenarios.py
File metadata and controls
2233 lines (1889 loc) · 72.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import collections
import logging
from typing import Any
import grpc
import pytest
import pytest_asyncio
from a2a.auth.user import User
from a2a.client.client import ClientConfig
from a2a.client.client_factory import ClientFactory
from a2a.client.errors import A2AClientError
from a2a.helpers.proto_helpers import new_task_from_user_message
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.context import ServerCallContext
from a2a.server.events import EventQueue
from a2a.server.events.in_memory_queue_manager import InMemoryQueueManager
from a2a.server.request_handlers import (
DefaultRequestHandlerV2,
GrpcHandler,
GrpcServerCallContextBuilder,
)
from a2a.server.request_handlers.default_request_handler import (
LegacyRequestHandler,
)
from a2a.server.tasks.inmemory_task_store import InMemoryTaskStore
from a2a.types import a2a_pb2_grpc
from a2a.types.a2a_pb2 import (
AgentCapabilities,
AgentCard,
AgentInterface,
Artifact,
CancelTaskRequest,
GetTaskRequest,
ListTasksRequest,
Message,
Part,
Role,
SendMessageConfiguration,
SendMessageRequest,
SubscribeToTaskRequest,
Task,
TaskArtifactUpdateEvent,
TaskState,
TaskStatus,
TaskStatusUpdateEvent,
)
from a2a.utils import TransportProtocol
from a2a.utils.errors import (
InvalidAgentResponseError,
InvalidParamsError,
TaskNotCancelableError,
TaskNotFoundError,
)
logger = logging.getLogger(__name__)
async def wait_for_state(
client: Any,
task_id: str,
expected_states: set[TaskState.ValueType],
timeout: float = 1.0,
) -> None:
"""Wait for the task to reach one of the expected states."""
start_time = asyncio.get_event_loop().time()
while True:
task = await client.get_task(GetTaskRequest(id=task_id))
if task.status.state in expected_states:
return
if asyncio.get_event_loop().time() - start_time > timeout:
raise TimeoutError(
f'Task {task_id} did not reach expected states {expected_states} within {timeout}s. '
f'Current state: {task.status.state}'
)
await asyncio.sleep(0.01)
async def get_all_events(stream):
return [event async for event in stream]
class MockUser(User):
@property
def is_authenticated(self) -> bool:
return True
@property
def user_name(self) -> str:
return 'test-user'
class MockCallContextBuilder(GrpcServerCallContextBuilder):
def build(self, request: Any) -> ServerCallContext:
return ServerCallContext(
user=MockUser(), state={'headers': {'a2a-version': '1.0'}}
)
def agent_card():
return AgentCard(
name='Test Agent',
version='1.0.0',
capabilities=AgentCapabilities(streaming=True),
supported_interfaces=[
AgentInterface(
protocol_binding=TransportProtocol.GRPC,
url='http://testserver',
)
],
)
def get_task_id(event):
if event.HasField('task'):
return event.task.id
if event.HasField('status_update'):
return event.status_update.task_id
assert False, f'Event {event} has no task_id'
def get_task_context_id(event):
if event.HasField('task'):
return event.task.context_id
if event.HasField('status_update'):
return event.status_update.context_id
assert False, f'Event {event} has no context_id'
def get_state(event):
if event.HasField('task'):
return event.task.status.state
return event.status_update.status.state
def validate_state(event, expected_state):
assert get_state(event) == expected_state
_test_servers = []
@pytest_asyncio.fixture(autouse=True)
async def cleanup_test_servers():
yield
for server in _test_servers:
await server.stop(None)
_test_servers.clear()
# TODO: Test different transport (e.g. HTTP_JSON hangs for some tests).
async def create_client(handler, agent_card, streaming=False):
server = grpc.aio.server()
port = server.add_insecure_port('[::]:0')
server_address = f'localhost:{port}'
agent_card.supported_interfaces[0].url = server_address
agent_card.supported_interfaces[0].protocol_binding = TransportProtocol.GRPC
servicer = GrpcHandler(
request_handler=handler, context_builder=MockCallContextBuilder()
)
a2a_pb2_grpc.add_A2AServiceServicer_to_server(servicer, server)
await server.start()
_test_servers.append(server)
factory = ClientFactory(
config=ClientConfig(
grpc_channel_factory=grpc.aio.insecure_channel,
supported_protocol_bindings=[TransportProtocol.GRPC],
streaming=streaming,
)
)
client = factory.create(agent_card)
client._server = server # Keep reference to prevent garbage collection
return client
def create_handler(
agent_executor, use_legacy, task_store=None, queue_manager=None
):
task_store = task_store or InMemoryTaskStore()
queue_manager = queue_manager or InMemoryQueueManager()
return (
LegacyRequestHandler(
agent_executor,
task_store,
agent_card(),
queue_manager,
)
if use_legacy
else DefaultRequestHandlerV2(
agent_executor,
task_store,
agent_card(),
queue_manager,
)
)
# Scenario 1: Cancellation of already terminal task
# This also covers test_scenario_7_cancel_terminal_task from test_handler_comparison
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_1_cancel_terminal_task(use_legacy, streaming):
class DummyAgentExecutor(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
pass
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
task_store = InMemoryTaskStore()
handler = create_handler(
DummyAgentExecutor(), use_legacy, task_store=task_store
)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
task_id = 'terminal-task'
await task_store.save(
Task(
id=task_id, status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED)
),
ServerCallContext(user=MockUser()),
)
with pytest.raises(TaskNotCancelableError):
await client.cancel_task(CancelTaskRequest(id=task_id))
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
async def test_scenario_4_simple_streaming(use_legacy):
class DummyAgentExecutor(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
await event_queue.enqueue_event(
TaskStatusUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED),
)
)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(DummyAgentExecutor(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=True
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
events = [
event
async for event in client.send_message(SendMessageRequest(message=msg))
]
task, status_update = events
assert task.HasField('task')
assert status_update.HasField('status_update')
assert [get_state(event) for event in events] == [
TaskState.TASK_STATE_WORKING,
TaskState.TASK_STATE_COMPLETED,
]
# Scenario 5: Re-subscribing to a finished task
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
async def test_scenario_5_resubscribe_to_finished(use_legacy):
class DummyAgentExecutor(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
await event_queue.enqueue_event(
TaskStatusUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED),
)
)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(DummyAgentExecutor(), use_legacy)
client = await create_client(handler, agent_card=agent_card())
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=False),
)
)
(event,) = [event async for event in it]
task_id = event.task.id
await wait_for_state(
client, task_id, expected_states={TaskState.TASK_STATE_COMPLETED}
)
# TODO: Use different transport.
with pytest.raises(
NotImplementedError,
match='client and/or server do not support resubscription',
):
async for _ in client.subscribe(SubscribeToTaskRequest(id=task_id)):
pass
# Scenario 6-8: Parity for Error cases
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenarios_simple_errors(use_legacy, streaming):
class DummyAgentExecutor(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_COMPLETED
await event_queue.enqueue_event(task)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(DummyAgentExecutor(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
with pytest.raises(TaskNotFoundError):
await client.get_task(GetTaskRequest(id='missing'))
msg1 = Message(
task_id='missing',
message_id='missing-task',
role=Role.ROLE_USER,
parts=[Part(text='h')],
)
with pytest.raises(TaskNotFoundError):
async for _ in client.send_message(SendMessageRequest(message=msg1)):
pass
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=False),
)
)
(event,) = [event async for event in it]
if streaming:
assert event.HasField('task')
task_id = event.task.id
validate_state(event, TaskState.TASK_STATE_COMPLETED)
else:
assert event.HasField('task')
task_id = event.task.id
assert event.task.status.state == TaskState.TASK_STATE_COMPLETED
logger.info('Sending message to completed task %s', task_id)
msg2 = Message(
message_id='test-msg-2',
task_id=task_id,
role=Role.ROLE_USER,
parts=[Part(text='message to completed task')],
)
# TODO: Is it correct error code ?
with pytest.raises(InvalidParamsError):
async for _ in client.send_message(SendMessageRequest(message=msg2)):
pass
(task,) = (await client.list_tasks(ListTasksRequest())).tasks
assert task.status.state == TaskState.TASK_STATE_COMPLETED
(message,) = task.history
assert message.role == Role.ROLE_USER
(message_part,) = message.parts
assert message_part.text == 'hello'
# Scenario 9: Exception before any event.
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_9_error_before_blocking(use_legacy, streaming):
class ErrorBeforeAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
raise ValueError('TEST_ERROR_IN_EXECUTE')
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(ErrorBeforeAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
# TODO: Is it correct error code ?
with pytest.raises(A2AClientError, match='TEST_ERROR_IN_EXECUTE'):
async for _ in client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(
return_immediately=False
),
)
):
pass
if use_legacy:
# Legacy is not creating tasks for agent failures.
assert len((await client.list_tasks(ListTasksRequest())).tasks) == 0
else:
(task,) = (await client.list_tasks(ListTasksRequest())).tasks
assert task.status.state == TaskState.TASK_STATE_FAILED
# Scenario 12/13: Exception after initial event
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_12_13_error_after_initial_event(use_legacy, streaming):
started_event = asyncio.Event()
continue_event = asyncio.Event()
class ErrorAfterAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await continue_event.wait()
raise ValueError('TEST_ERROR_IN_EXECUTE')
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(ErrorAfterAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it = client.send_message(SendMessageRequest(message=msg))
tasks = []
if streaming:
res = await it.__anext__()
validate_state(res, TaskState.TASK_STATE_WORKING)
continue_event.set()
else:
async def release_agent():
await started_event.wait()
continue_event.set()
tasks.append(asyncio.create_task(release_agent()))
with pytest.raises(A2AClientError, match='TEST_ERROR_IN_EXECUTE'):
async for _ in it:
pass
await asyncio.gather(*tasks)
(task,) = (await client.list_tasks(ListTasksRequest())).tasks
if use_legacy:
# Legacy does not update task state on exception.
assert task.status.state == TaskState.TASK_STATE_WORKING
else:
assert task.status.state == TaskState.TASK_STATE_FAILED
# Scenario 14: Exception in Cancel
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_14_error_in_cancel(use_legacy, streaming):
started_event = asyncio.Event()
hang_event = asyncio.Event()
class ErrorCancelAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await hang_event.wait()
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
raise ValueError('TEST_ERROR_IN_CANCEL')
handler = create_handler(ErrorCancelAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg = Message(
message_id='test-msg',
role=Role.ROLE_USER,
parts=[Part(text='hello')],
)
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=True),
)
)
res = await it.__anext__()
task_id = res.task.id if res.HasField('task') else res.status_update.task_id
await asyncio.wait_for(started_event.wait(), timeout=1.0)
with pytest.raises(A2AClientError, match='TEST_ERROR_IN_CANCEL'):
await client.cancel_task(CancelTaskRequest(id=task_id))
(task,) = (await client.list_tasks(ListTasksRequest())).tasks
if use_legacy:
# Legacy does not update task state on exception.
assert task.status.state == TaskState.TASK_STATE_WORKING
else:
assert task.status.state == TaskState.TASK_STATE_FAILED
# Scenario 15: Subscribe to task that errors out
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
async def test_scenario_15_subscribe_error(use_legacy):
started_event = asyncio.Event()
continue_event = asyncio.Event()
class ErrorAfterAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await continue_event.wait()
raise ValueError('TEST_ERROR_IN_EXECUTE')
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(ErrorAfterAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=True
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it_start = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=True),
)
)
res = await it_start.__anext__()
task_id = res.task.id if res.HasField('task') else res.status_update.task_id
async def consume_events():
async for _ in client.subscribe(SubscribeToTaskRequest(id=task_id)):
pass
consume_task = asyncio.create_task(consume_events())
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(asyncio.shield(consume_task), timeout=0.1)
await asyncio.wait_for(started_event.wait(), timeout=1.0)
continue_event.set()
if use_legacy:
# Legacy client hangs forever.
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(consume_task, timeout=0.1)
else:
with pytest.raises(A2AClientError, match='TEST_ERROR_IN_EXECUTE'):
await consume_task
(task,) = (await client.list_tasks(ListTasksRequest())).tasks
if use_legacy:
# Legacy does not update task state on exception.
assert task.status.state == TaskState.TASK_STATE_WORKING
else:
assert task.status.state == TaskState.TASK_STATE_FAILED
# Scenario 16: Slow execution and return_immediately=True
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_16_slow_execution(use_legacy, streaming):
started_event = asyncio.Event()
hang_event = asyncio.Event()
class SlowAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
started_event.set()
await hang_event.wait()
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
queue_manager = InMemoryQueueManager()
handler = create_handler(
SlowAgent(), use_legacy, queue_manager=queue_manager
)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg = Message(
message_id='test-msg',
role=Role.ROLE_USER,
parts=[Part(text='hello')],
)
async def send_message_and_get_first_response():
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=True),
)
)
return await asyncio.wait_for(it.__anext__(), timeout=0.1)
# First response should not be there yet.
with pytest.raises(asyncio.TimeoutError):
await send_message_and_get_first_response()
tasks = (await client.list_tasks(ListTasksRequest())).tasks
assert len(tasks) == 0
# Scenario 17: Cancellation of a working task.
# @pytest.mark.skip
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_cancel_working_task_empty_cancel(use_legacy, streaming):
started_event = asyncio.Event()
hang_event = asyncio.Event()
class DummyCancelAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await hang_event.wait()
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
# TODO: this should be done automatically by the framework ?
await event_queue.enqueue_event(
TaskStatusUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
status=TaskStatus(state=TaskState.TASK_STATE_CANCELED),
)
)
handler = create_handler(DummyCancelAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=True),
)
)
res = await it.__anext__()
task_id = res.task.id if res.HasField('task') else res.status_update.task_id
await asyncio.wait_for(started_event.wait(), timeout=1.0)
task_before = await client.get_task(GetTaskRequest(id=task_id))
assert task_before.status.state == TaskState.TASK_STATE_WORKING
cancel_res = await client.cancel_task(CancelTaskRequest(id=task_id))
assert cancel_res.status.state == TaskState.TASK_STATE_CANCELED
task_after = await client.get_task(GetTaskRequest(id=task_id))
assert task_after.status.state == TaskState.TASK_STATE_CANCELED
(task_from_list,) = (await client.list_tasks(ListTasksRequest())).tasks
assert task_from_list.status.state == TaskState.TASK_STATE_CANCELED
# Scenario 18: Complex streaming with multiple subscribers
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
async def test_scenario_18_streaming_subscribers(use_legacy):
started_event = asyncio.Event()
working_event = asyncio.Event()
completed_event = asyncio.Event()
class ComplexAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await working_event.wait()
await event_queue.enqueue_event(
TaskArtifactUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
artifact=Artifact(artifact_id='test-art'),
)
)
await completed_event.wait()
await event_queue.enqueue_event(
TaskStatusUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED),
)
)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(ComplexAgent(), use_legacy)
client = await create_client(
handler, agent_card=agent_card(), streaming=True
)
msg = Message(
message_id='test-msg', role=Role.ROLE_USER, parts=[Part(text='hello')]
)
it = client.send_message(
SendMessageRequest(
message=msg,
configuration=SendMessageConfiguration(return_immediately=True),
)
)
res = await it.__anext__()
task_id = res.task.id if res.HasField('task') else res.status_update.task_id
await asyncio.wait_for(started_event.wait(), timeout=1.0)
# create first subscriber
sub1 = client.subscribe(SubscribeToTaskRequest(id=task_id))
# first subscriber receives current task state (WORKING)
validate_state(await sub1.__anext__(), TaskState.TASK_STATE_WORKING)
# create second subscriber
sub2 = client.subscribe(SubscribeToTaskRequest(id=task_id))
# second subscriber receives current task state (WORKING)
validate_state(await sub2.__anext__(), TaskState.TASK_STATE_WORKING)
working_event.set()
# validate what both subscribers observed (artifact)
res1_art = await sub1.__anext__()
assert res1_art.artifact_update.artifact.artifact_id == 'test-art'
res2_art = await sub2.__anext__()
assert res2_art.artifact_update.artifact.artifact_id == 'test-art'
completed_event.set()
# validate what both subscribers observed (completed)
validate_state(await sub1.__anext__(), TaskState.TASK_STATE_COMPLETED)
validate_state(await sub2.__anext__(), TaskState.TASK_STATE_COMPLETED)
# validate final task state with getTask
final_task = await client.get_task(GetTaskRequest(id=task_id))
assert final_task.status.state == TaskState.TASK_STATE_COMPLETED
(artifact,) = final_task.artifacts
assert artifact.artifact_id == 'test-art'
(message,) = final_task.history
assert message.parts[0].text == 'hello'
# Scenario 19: Parallel executions for the same task should not happen simultaneously.
@pytest.mark.timeout(2.0)
@pytest.mark.asyncio
@pytest.mark.parametrize('use_legacy', [False, True], ids=['v2', 'legacy'])
@pytest.mark.parametrize(
'streaming', [False, True], ids=['blocking', 'streaming']
)
async def test_scenario_19_no_parallel_executions(use_legacy, streaming):
started_event = asyncio.Event()
continue_event = asyncio.Event()
executions_count = 0
class CountingAgent(AgentExecutor):
async def execute(
self, context: RequestContext, event_queue: EventQueue
):
nonlocal executions_count
executions_count += 1
if executions_count > 1:
await event_queue.enqueue_event(
TaskArtifactUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
artifact=Artifact(artifact_id='SECOND_EXECUTION'),
)
)
return
task = new_task_from_user_message(context.message)
task.status.state = TaskState.TASK_STATE_WORKING
await event_queue.enqueue_event(task)
started_event.set()
await continue_event.wait()
await event_queue.enqueue_event(
TaskStatusUpdateEvent(
task_id=context.task_id,
context_id=context.context_id,
status=TaskStatus(state=TaskState.TASK_STATE_COMPLETED),
)
)
async def cancel(
self, context: RequestContext, event_queue: EventQueue
):
pass
handler = create_handler(CountingAgent(), use_legacy)
client1 = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
client2 = await create_client(
handler, agent_card=agent_card(), streaming=streaming
)
msg1 = Message(
message_id='test-msg-1',
role=Role.ROLE_USER,
parts=[Part(text='hello 1')],
)
# First client sends initial message
it1 = client1.send_message(
SendMessageRequest(
message=msg1,
configuration=SendMessageConfiguration(return_immediately=False),
)
)
task1 = asyncio.create_task(it1.__anext__())
# Wait for the first execution to reach the WORKING state
await asyncio.wait_for(started_event.wait(), timeout=1.0)
assert executions_count == 1
# Extract task_id from the first call using list_tasks
(task,) = (await client1.list_tasks(ListTasksRequest())).tasks
task_id = task.id
msg2 = Message(
message_id='test-msg-2',
task_id=task_id,
role=Role.ROLE_USER,
parts=[Part(text='hello 2')],
)
# Second client sends a message to the same task
it2 = client2.send_message(
SendMessageRequest(
message=msg2,
configuration=SendMessageConfiguration(return_immediately=False),
)
)
task2 = asyncio.create_task(it2.__anext__())
if use_legacy:
# Legacy handler executes the second request in parallel.
await task2
assert executions_count == 2
else:
# V2 handler queues the second request.
with pytest.raises(asyncio.TimeoutError):
await asyncio.wait_for(asyncio.shield(task2), timeout=0.1)
assert executions_count == 1
# Unblock AgentExecutor
continue_event.set()
# Verify that both calls for clients finished.
if use_legacy and not streaming:
# Legacy handler fails on first execution.
with pytest.raises(A2AClientError, match='NoTaskQueue'):
await task1
else:
await task1
try:
await task2
except StopAsyncIteration:
# TODO: Test is flaky. Debug it.
return
# Consume remaining events if any
async def consume(it):