-
Notifications
You must be signed in to change notification settings - Fork 179
Expand file tree
/
Copy pathtest_activity.py
More file actions
1418 lines (1208 loc) · 48 KB
/
test_activity.py
File metadata and controls
1418 lines (1208 loc) · 48 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 concurrent.futures
import logging
import logging.handlers
import multiprocessing
import os
import queue
import signal
import threading
import time
import uuid
from concurrent.futures.process import BrokenProcessPool
from contextvars import ContextVar
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from typing import Any, Callable, List, NoReturn, Optional, Sequence, Type
from temporalio import activity, workflow
from temporalio.client import (
AsyncActivityHandle,
Client,
WorkflowFailureError,
WorkflowHandle,
)
from temporalio.common import RawValue, RetryPolicy
from temporalio.exceptions import (
ActivityError,
ApplicationError,
CancelledError,
TimeoutError,
TimeoutType,
)
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import (
ActivityInboundInterceptor,
ExecuteActivityInput,
Interceptor,
SharedStateManager,
Worker,
WorkerConfig,
)
from tests.helpers.worker import (
ExternalWorker,
KSAction,
KSExecuteActivityAction,
KSWorkflowParams,
)
# Passing through because Python 3.9 has an import bug at
# https://github.com/python/cpython/issues/91351
with workflow.unsafe.imports_passed_through():
import pytest
_default_shared_state_manager = SharedStateManager.create_from_multiprocessing(
multiprocessing.Manager()
)
default_max_concurrent_activities = 50
async def test_activity_hello(client: Client, worker: ExternalWorker):
@activity.defn
async def say_hello(name: str) -> str:
return f"Hello, {name}!"
result = await _execute_workflow_with_activity(
client, worker, say_hello, "Temporal"
)
assert result.result == "Hello, Temporal!"
async def test_activity_without_decorator(client: Client, worker: ExternalWorker):
async def say_hello(name: str) -> str:
return f"Hello, {name}!"
with pytest.raises(TypeError) as err:
await _execute_workflow_with_activity(client, worker, say_hello, "Temporal")
assert "Activity say_hello missing attributes" in str(err.value)
async def test_activity_custom_name(client: Client, worker: ExternalWorker):
@activity.defn(name="my custom activity name!")
async def get_name(name: str) -> str:
return f"Name: {activity.info().activity_type}"
result = await _execute_workflow_with_activity(
client,
worker,
get_name,
"Temporal",
activity_name_override="my custom activity name!",
)
assert result.result == "Name: my custom activity name!"
async def test_activity_info(
client: Client, worker: ExternalWorker, env: WorkflowEnvironment
):
# TODO(cretz): Fix
if env.supports_time_skipping:
pytest.skip(
"Java test server: https://github.com/temporalio/sdk-java/issues/1426"
)
# Make sure info call outside of activity context fails
assert not activity.in_activity()
with pytest.raises(RuntimeError) as err:
activity.info()
assert str(err.value) == "Not in activity context"
# Capture the info from the activity
info: Optional[activity.Info] = None
@activity.defn
async def capture_info() -> None:
nonlocal info
info = activity.info()
result = await _execute_workflow_with_activity(
client, worker, capture_info, start_to_close_timeout_ms=4000
)
assert info
assert info.activity_id
assert info.activity_type == "capture_info"
assert info.attempt == 1
assert abs(
info.current_attempt_scheduled_time - datetime.now(timezone.utc)
) < timedelta(seconds=5)
assert info.heartbeat_details == []
assert info.heartbeat_timeout is None
assert not info.is_local
assert info.schedule_to_close_timeout is None
assert abs(info.scheduled_time - datetime.now(timezone.utc)) < timedelta(seconds=5)
assert info.start_to_close_timeout == timedelta(seconds=4)
assert abs(info.started_time - datetime.now(timezone.utc)) < timedelta(seconds=5)
assert info.task_queue == result.act_task_queue
assert info.task_token
assert info.workflow_id == result.handle.id
assert info.workflow_namespace == client.namespace
assert info.workflow_run_id == result.handle.first_execution_run_id
assert info.workflow_type == "kitchen_sink"
async def test_sync_activity_thread(client: Client, worker: ExternalWorker):
@activity.defn
def some_activity() -> str:
return f"activity name: {activity.info().activity_type}"
# We intentionally leave max_workers by default in the thread pool executor
# to confirm that the warning is triggered
with concurrent.futures.ThreadPoolExecutor() as executor:
with pytest.warns(
UserWarning,
match=f"Worker max_concurrent_activities is {default_max_concurrent_activities} but activity_executor's max_workers is only",
):
result = await _execute_workflow_with_activity(
client,
worker,
some_activity,
worker_config={"activity_executor": executor},
)
assert result.result == "activity name: some_activity"
@activity.defn
def picklable_activity() -> str:
return f"activity name: {activity.info().activity_type}"
async def test_sync_activity_process(client: Client, worker: ExternalWorker):
# We intentionally leave max_workers by default in the process pool executor
# to confirm that the warning is triggered
with concurrent.futures.ProcessPoolExecutor() as executor:
with pytest.warns(
UserWarning,
match=f"Worker max_concurrent_activities is {default_max_concurrent_activities} but activity_executor's max_workers is only",
):
result = await _execute_workflow_with_activity(
client,
worker,
picklable_activity,
worker_config={"activity_executor": executor},
)
assert result.result == "activity name: picklable_activity"
async def test_sync_activity_process_non_picklable(
client: Client, worker: ExternalWorker
):
@activity.defn
def some_activity() -> str:
return f"activity name: {activity.info().activity_type}"
with pytest.raises(TypeError) as err:
with concurrent.futures.ProcessPoolExecutor() as executor:
await _execute_workflow_with_activity(
client,
worker,
some_activity,
worker_config={"activity_executor": executor},
)
assert "must be picklable when using a process executor" in str(err.value)
async def test_activity_failure(client: Client, worker: ExternalWorker):
@activity.defn
async def raise_error():
raise RuntimeError("oh no!")
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(client, worker, raise_error)
assert str(assert_activity_application_error(err.value)) == "RuntimeError: oh no!"
@activity.defn
def picklable_activity_failure():
raise RuntimeError("oh no!")
async def test_sync_activity_process_failure(client: Client, worker: ExternalWorker):
with pytest.raises(WorkflowFailureError) as err:
with concurrent.futures.ProcessPoolExecutor() as executor:
await _execute_workflow_with_activity(
client,
worker,
picklable_activity_failure,
worker_config={"activity_executor": executor},
)
assert str(assert_activity_application_error(err.value)) == "RuntimeError: oh no!"
async def test_activity_bad_params(client: Client, worker: ExternalWorker):
@activity.defn
async def say_hello(name: str) -> str:
return f"Hello, {name}!"
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(client, worker, say_hello)
assert str(assert_activity_application_error(err.value)).endswith(
"missing 1 required positional argument: 'name'"
)
async def test_activity_kwonly_params():
with pytest.raises(TypeError) as err:
@activity.defn
async def say_hello(*, name: str) -> str:
return f"Hello, {name}!"
assert str(err.value).endswith("cannot have keyword-only arguments")
async def test_activity_cancel_catch(client: Client, worker: ExternalWorker):
@activity.defn
async def wait_cancel() -> str:
try:
while True:
await asyncio.sleep(0.3)
activity.heartbeat()
except asyncio.CancelledError:
return "Got cancelled error, cancelled? " + str(activity.is_cancelled())
result = await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=2000,
)
assert result.result == "Got cancelled error, cancelled? True"
async def test_activity_cancel_throw(client: Client, worker: ExternalWorker):
@activity.defn
async def wait_cancel() -> str:
while True:
await asyncio.sleep(0.3)
activity.heartbeat()
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=1000,
)
assert isinstance(err.value.cause, ActivityError)
assert isinstance(err.value.cause.cause, CancelledError)
async def test_sync_activity_thread_cancel_caught(
client: Client, worker: ExternalWorker
):
@activity.defn
def wait_cancel() -> str:
try:
while True:
time.sleep(1)
activity.heartbeat()
except CancelledError:
assert activity.is_cancelled()
return "Cancelled"
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
result = await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=3000,
worker_config={"activity_executor": executor},
)
assert result.result == "Cancelled"
async def test_sync_activity_thread_cancel_uncaught(
client: Client, worker: ExternalWorker
):
@activity.defn
def wait_cancel() -> NoReturn:
while True:
time.sleep(1)
activity.heartbeat()
with pytest.raises(WorkflowFailureError) as err:
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=3000,
worker_config={"activity_executor": executor},
)
assert isinstance(err.value.cause, ActivityError)
assert isinstance(err.value.cause.cause, CancelledError)
async def test_sync_activity_thread_cancel_exception_disabled(
client: Client, worker: ExternalWorker
):
@activity.defn(no_thread_cancel_exception=True)
def wait_cancel() -> str:
while True:
time.sleep(1)
activity.heartbeat()
if activity.is_cancelled():
# Heartbeat again just to confirm nothing happens
time.sleep(1)
activity.heartbeat()
return "Cancelled"
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
result = await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=3000,
worker_config={"activity_executor": executor},
)
assert result.result == "Cancelled"
async def test_sync_activity_thread_cancel_exception_shielded(
client: Client, worker: ExternalWorker
):
events: List[str] = []
@activity.defn
def wait_cancel() -> None:
events.append("pre1")
with activity.shield_thread_cancel_exception():
events.append("pre2")
with activity.shield_thread_cancel_exception():
events.append("pre3")
while not activity.is_cancelled():
time.sleep(1)
activity.heartbeat()
events.append("post3")
events.append("post2")
events.append("post1")
with pytest.raises(WorkflowFailureError) as err:
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
await _execute_workflow_with_activity(
client,
worker,
wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=3000,
worker_config={"activity_executor": executor},
)
assert isinstance(err.value.cause, ActivityError)
assert isinstance(err.value.cause.cause, CancelledError)
# This will have every event except post1 because that's where it throws
assert events == ["pre1", "pre2", "pre3", "post3", "post2"]
sync_activity_waiting_cancel = threading.Event()
@activity.defn
def sync_activity_wait_cancel():
sync_activity_waiting_cancel.set()
while True:
time.sleep(1)
activity.heartbeat()
# We don't sandbox because Python logging uses multiprocessing if it's present
# which we don't want to get warnings about
@workflow.defn(sandboxed=False)
class CancelOnWorkerShutdownWorkflow:
@workflow.run
async def run(self) -> None:
await workflow.execute_activity(
sync_activity_wait_cancel,
start_to_close_timeout=timedelta(hours=1),
retry_policy=RetryPolicy(maximum_attempts=1),
)
# This test used to fail because we were sending a cancelled error and the
# server doesn't allow that
async def test_sync_activity_thread_cancel_on_worker_shutdown(client: Client):
task_queue = f"tq-{uuid.uuid4()}"
def new_worker() -> Worker:
return Worker(
client,
task_queue=task_queue,
activities=[sync_activity_wait_cancel],
workflows=[CancelOnWorkerShutdownWorkflow],
activity_executor=executor,
max_concurrent_activities=default_max_concurrent_activities,
max_cached_workflows=0,
)
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
async with new_worker():
# Start the workflow
handle = await client.start_workflow(
CancelOnWorkerShutdownWorkflow.run,
id=f"workflow-{uuid.uuid4()}",
task_queue=task_queue,
)
# Wait for activity to start
assert await asyncio.get_running_loop().run_in_executor(
executor, lambda: sync_activity_waiting_cancel.wait(20)
)
# Shut down the worker
# Start the worker again and wait for result
with pytest.raises(WorkflowFailureError) as err:
async with new_worker():
await handle.result()
assert isinstance(err.value.cause, ActivityError)
assert isinstance(err.value.cause.cause, ApplicationError)
assert "activity did not complete in time" in err.value.cause.cause.message
@activity.defn
def picklable_activity_wait_cancel() -> str:
while not activity.is_cancelled():
time.sleep(1)
activity.heartbeat()
return "Cancelled"
async def test_sync_activity_process_cancel(client: Client, worker: ExternalWorker):
with concurrent.futures.ProcessPoolExecutor() as executor:
result = await _execute_workflow_with_activity(
client,
worker,
picklable_activity_wait_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=3000,
worker_config={"activity_executor": executor},
)
assert result.result == "Cancelled"
@activity.defn
def picklable_activity_raise_cancel() -> str:
while not activity.is_cancelled():
time.sleep(1)
activity.heartbeat()
raise CancelledError("Cancelled")
async def test_sync_activity_process_cancel_uncaught(
client: Client, worker: ExternalWorker
):
with pytest.raises(WorkflowFailureError) as err:
with concurrent.futures.ProcessPoolExecutor() as executor:
await _execute_workflow_with_activity(
client,
worker,
picklable_activity_raise_cancel,
cancel_after_ms=100,
wait_for_cancellation=True,
heartbeat_timeout_ms=5000,
worker_config={"activity_executor": executor},
)
assert isinstance(err.value.cause, ActivityError)
assert isinstance(err.value.cause.cause, CancelledError)
async def test_activity_does_not_exist(client: Client, worker: ExternalWorker):
@activity.defn
async def say_hello(name: str) -> str:
return f"Hello, {name}!"
with pytest.raises(WorkflowFailureError) as err:
act_task_queue = str(uuid.uuid4())
async with Worker(client, task_queue=act_task_queue, activities=[say_hello]):
await client.execute_workflow(
"kitchen_sink",
KSWorkflowParams(
actions=[
KSAction(
execute_activity=KSExecuteActivityAction(
name="wrong_activity", task_queue=act_task_queue
)
)
]
),
id=str(uuid.uuid4()),
task_queue=worker.task_queue,
)
assert "is not registered" in str(assert_activity_application_error(err.value))
async def test_max_concurrent_activities(client: Client, worker: ExternalWorker):
seen_indexes: List[int] = []
complete_activities_event = asyncio.Event()
@activity.defn
async def some_activity(index: int) -> str:
seen_indexes.append(index)
# Wait here to hold up the activity
await complete_activities_event.wait()
return ""
# Only allow 42 activities, but try to execute 43. Make a short schedule to
# start timeout but a long schedule to close timeout.
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(
client,
worker,
some_activity,
count=43,
index_as_arg=True,
schedule_to_close_timeout_ms=5000,
schedule_to_start_timeout_ms=1000,
worker_config={"max_concurrent_activities": 42},
on_complete=complete_activities_event.set,
)
timeout = assert_activity_error(err.value)
assert isinstance(timeout, TimeoutError)
assert timeout.type == TimeoutType.SCHEDULE_TO_START
@dataclass
class SomeClass1:
foo: int
@dataclass
class SomeClass2:
foo: str
bar: Optional[SomeClass1] = None
async def test_activity_type_hints(client: Client, worker: ExternalWorker):
activity_param1: SomeClass2
@activity.defn
async def some_activity(param1: SomeClass2, param2: str) -> str:
nonlocal activity_param1
activity_param1 = param1
return f"param1: {type(param1)}, param2: {type(param2)}"
result = await _execute_workflow_with_activity(
client,
worker,
some_activity,
SomeClass2(foo="str1", bar=SomeClass1(foo=123)),
"123",
)
assert (
result.result
== "param1: <class 'tests.worker.test_activity.SomeClass2'>, param2: <class 'str'>"
)
assert activity_param1 == SomeClass2(foo="str1", bar=SomeClass1(foo=123))
async def test_activity_heartbeat_details(
client: Client, worker: ExternalWorker, env: WorkflowEnvironment
):
if env.supports_time_skipping:
pytest.skip("https://github.com/temporalio/sdk-java/issues/2459")
@activity.defn
async def some_activity() -> str:
info = activity.info()
count = int(next(iter(info.heartbeat_details))) if info.heartbeat_details else 0
activity.logger.debug("Changing count from %s to %s", count, count + 9)
count += 9
activity.heartbeat(count)
if count < 30:
raise RuntimeError("Try again!")
return f"final count: {count}"
result = await _execute_workflow_with_activity(
client,
worker,
some_activity,
retry_max_attempts=4,
)
assert result.result == "final count: 36"
class NotSerializableValue:
pass
async def test_activity_heartbeat_details_converter_fail(
client: Client, worker: ExternalWorker
):
@activity.defn
async def some_activity() -> str:
activity.heartbeat(NotSerializableValue())
# Since the above fails, it will cause this task to be cancelled on the
# next event loop iteration, so we sleep for a short time to allow that
# iteration to occur
await asyncio.sleep(0.05)
return "Should not get here"
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(client, worker, some_activity)
assert str(assert_activity_application_error(err.value)).endswith(
"is not JSON serializable"
)
async def test_activity_heartbeat_details_timeout(
client: Client, worker: ExternalWorker, env: WorkflowEnvironment
):
# TODO(cretz): Fix
if env.supports_time_skipping:
pytest.skip(
"Java test server: https://github.com/temporalio/sdk-java/issues/1427"
)
@activity.defn
async def some_activity() -> str:
activity.heartbeat("some details!")
await asyncio.sleep(3)
return "Should not get here"
# Have a 1s heartbeat timeout that we won't meet with a second heartbeat
# then check the timeout's details
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(
client, worker, some_activity, heartbeat_timeout_ms=1000
)
timeout = assert_activity_error(err.value)
assert isinstance(timeout, TimeoutError)
assert str(timeout) == "activity Heartbeat timeout"
assert timeout.type == TimeoutType.HEARTBEAT
assert list(timeout.last_heartbeat_details) == ["some details!"]
@activity.defn
def picklable_heartbeat_details_activity() -> str:
info = activity.info()
some_list: List[str] = (
next(iter(info.heartbeat_details)) if info.heartbeat_details else []
)
some_list.append(f"attempt: {info.attempt}")
activity.logger.debug("Heartbeating with value: %s", some_list)
activity.heartbeat(some_list)
if len(some_list) < 2:
raise RuntimeError(f"Try again, list contains: {some_list}")
return ", ".join(some_list)
async def test_sync_activity_thread_heartbeat_details(
client: Client, worker: ExternalWorker, env: WorkflowEnvironment
):
if env.supports_time_skipping:
pytest.skip("https://github.com/temporalio/sdk-java/issues/2459")
with concurrent.futures.ThreadPoolExecutor(
max_workers=default_max_concurrent_activities
) as executor:
result = await _execute_workflow_with_activity(
client,
worker,
picklable_heartbeat_details_activity,
retry_max_attempts=2,
worker_config={"activity_executor": executor},
)
assert result.result == "attempt: 1, attempt: 2"
async def test_sync_activity_process_heartbeat_details(
client: Client, worker: ExternalWorker, env: WorkflowEnvironment
):
if env.supports_time_skipping:
pytest.skip("https://github.com/temporalio/sdk-java/issues/2459")
with concurrent.futures.ProcessPoolExecutor() as executor:
result = await _execute_workflow_with_activity(
client,
worker,
picklable_heartbeat_details_activity,
retry_max_attempts=2,
worker_config={"activity_executor": executor},
)
assert result.result == "attempt: 1, attempt: 2"
@activity.defn
def picklable_activity_non_pickable_heartbeat_details() -> str:
activity.heartbeat(lambda: "cannot pickle lambda by default")
return "Should not get here"
async def test_sync_activity_process_non_picklable_heartbeat_details(
client: Client, worker: ExternalWorker
):
with pytest.raises(WorkflowFailureError) as err:
with concurrent.futures.ProcessPoolExecutor() as executor:
await _execute_workflow_with_activity(
client,
worker,
picklable_activity_non_pickable_heartbeat_details,
worker_config={"activity_executor": executor},
)
msg = str(assert_activity_application_error(err.value))
# TODO: different messages can apparently be produced across runs/platforms
# See e.g. https://github.com/temporalio/sdk-python/actions/runs/10455232879/job/28949714969?pr=571
assert (
"Can't pickle" in msg
or "Can't get local object 'picklable_activity_non_pickable_heartbeat_details.<locals>.<lambda>'"
in msg
)
async def test_activity_error_non_retryable(client: Client, worker: ExternalWorker):
@activity.defn
async def some_activity():
if activity.info().attempt < 2:
raise ApplicationError("Retry me", non_retryable=False)
# We'll test error details while we're here
raise ApplicationError("Do not retry me", "detail1", 123, non_retryable=True)
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(
client,
worker,
some_activity,
retry_max_attempts=100,
)
app_err = assert_activity_application_error(err.value)
assert str(app_err) == "Do not retry me"
assert list(app_err.details) == ["detail1", 123]
async def test_activity_error_non_retryable_type(
client: Client, worker: ExternalWorker
):
@activity.defn
async def some_activity():
if activity.info().attempt < 2:
raise ApplicationError("Retry me", type="Can retry me")
raise ApplicationError("Do not retry me", type="Cannot retry me")
with pytest.raises(WorkflowFailureError) as err:
await _execute_workflow_with_activity(
client,
worker,
some_activity,
retry_max_attempts=100,
non_retryable_error_types=["Cannot retry me"],
)
assert (
str(assert_activity_application_error(err.value))
== "Cannot retry me: Do not retry me"
)
async def test_activity_logging(client: Client, worker: ExternalWorker):
@activity.defn
async def say_hello(name: str) -> str:
activity.logger.info(f"Called with arg: {name}")
return f"Hello, {name}!"
# Create a queue, add handler to logger, call normal activity, then check
handler = logging.handlers.QueueHandler(queue.Queue())
activity.logger.base_logger.addHandler(handler)
prev_level = activity.logger.base_logger.level
activity.logger.base_logger.setLevel(logging.INFO)
try:
result = await _execute_workflow_with_activity(
client, worker, say_hello, "Temporal"
)
finally:
activity.logger.base_logger.removeHandler(handler)
activity.logger.base_logger.setLevel(prev_level)
assert result.result == "Hello, Temporal!"
records: List[logging.LogRecord] = list(handler.queue.queue) # type: ignore
assert len(records) > 0
assert records[-1].message.startswith(
"Called with arg: Temporal ({'activity_id': '"
)
assert records[-1].__dict__["temporal_activity"]["activity_type"] == "say_hello"
async def test_activity_worker_shutdown(client: Client, worker: ExternalWorker):
activity_started = asyncio.Event()
@activity.defn
async def wait_on_event() -> str:
nonlocal activity_started
activity_started.set()
try:
while True:
await asyncio.sleep(0.3)
activity.heartbeat()
except asyncio.CancelledError:
return "Properly cancelled"
act_task_queue = str(uuid.uuid4())
act_worker = Worker(client, task_queue=act_task_queue, activities=[wait_on_event])
asyncio.create_task(act_worker.run())
# Start workflow
handle = await client.start_workflow(
"kitchen_sink",
KSWorkflowParams(
actions=[
KSAction(
execute_activity=KSExecuteActivityAction(
name="wait_on_event",
task_queue=act_task_queue,
heartbeat_timeout_ms=1000,
)
)
]
),
id=str(uuid.uuid4()),
task_queue=worker.task_queue,
)
# Wait until activity started before shutting down the worker
await activity_started.wait()
await act_worker.shutdown()
assert "Properly cancelled" == await handle.result()
async def test_activity_worker_shutdown_graceful(
client: Client, worker: ExternalWorker
):
activity_started = asyncio.Event()
@activity.defn
async def wait_on_event() -> str:
nonlocal activity_started
activity_started.set()
await activity.wait_for_worker_shutdown()
return "Worker graceful shutdown"
act_task_queue = str(uuid.uuid4())
act_worker = Worker(
client,
task_queue=act_task_queue,
activities=[wait_on_event],
graceful_shutdown_timeout=timedelta(seconds=2),
)
asyncio.create_task(act_worker.run())
# Start workflow
handle = await client.start_workflow(
"kitchen_sink",
KSWorkflowParams(
actions=[
KSAction(
execute_activity=KSExecuteActivityAction(
name="wait_on_event", task_queue=act_task_queue
)
)
]
),
id=str(uuid.uuid4()),
task_queue=worker.task_queue,
)
# Wait until activity started before shutting down the worker
await activity_started.wait()
await act_worker.shutdown()
assert "Worker graceful shutdown" == await handle.result()
@activity.defn
def picklable_wait_on_event() -> str:
activity.wait_for_worker_shutdown_sync(20)
return "Worker graceful shutdown"
async def test_sync_activity_process_worker_shutdown_graceful(
client: Client, worker: ExternalWorker
):
act_task_queue = str(uuid.uuid4())
with concurrent.futures.ProcessPoolExecutor() as executor:
act_worker = Worker(
client,
task_queue=act_task_queue,
activities=[picklable_wait_on_event],
activity_executor=executor,
max_concurrent_activities=default_max_concurrent_activities,
graceful_shutdown_timeout=timedelta(seconds=2),
shared_state_manager=_default_shared_state_manager,
)
asyncio.create_task(act_worker.run())
# Start workflow
handle = await client.start_workflow(
"kitchen_sink",
KSWorkflowParams(
actions=[
KSAction(
execute_activity=KSExecuteActivityAction(
name="picklable_wait_on_event",
task_queue=act_task_queue,
heartbeat_timeout_ms=30000,
)
)
]
),
id=str(uuid.uuid4()),
task_queue=worker.task_queue,
)
# Wait until activity started before shutting down the worker. Since it's
# cross process, we'll just cheat a bit using a private var to check.
found = False
activity_worker = act_worker._activity_worker
assert activity_worker
for _ in range(10):
await asyncio.sleep(0.2)
found = len(activity_worker._running_activities) > 0
if found:
break
assert found
# Do shutdown
await act_worker.shutdown()
assert "Worker graceful shutdown" == await handle.result()
@activity.defn
def kill_my_process() -> str:
os.kill(os.getpid(), getattr(signal, "SIGKILL", -9))
return "does not get here"
async def test_sync_activity_process_executor_crash(
client: Client, worker: ExternalWorker
):
act_task_queue = str(uuid.uuid4())
with concurrent.futures.ProcessPoolExecutor() as executor:
act_worker = Worker(
client,
task_queue=act_task_queue,
activities=[kill_my_process],
activity_executor=executor,
max_concurrent_activities=default_max_concurrent_activities,
graceful_shutdown_timeout=timedelta(seconds=2),
shared_state_manager=_default_shared_state_manager,
)
act_worker_task = asyncio.create_task(act_worker.run())