-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtest_orchestration_executor.py
More file actions
1261 lines (1023 loc) · 56.6 KB
/
test_orchestration_executor.py
File metadata and controls
1261 lines (1023 loc) · 56.6 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
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
import logging
from datetime import datetime, timedelta
import pytest
import durabletask.internal.helpers as helpers
import durabletask.internal.orchestrator_service_pb2 as pb
from durabletask import task, worker, entities
logging.basicConfig(
format='%(asctime)s.%(msecs)03d %(name)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.DEBUG)
TEST_LOGGER = logging.getLogger("tests")
TEST_INSTANCE_ID = "abc123"
def test_orchestrator_inputs():
"""Validates orchestrator function input population"""
def orchestrator(ctx: task.OrchestrationContext, my_input: int):
return my_input, ctx.instance_id, str(ctx.current_utc_datetime), ctx.is_replaying
test_input = 42
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
start_time = datetime.now()
new_events = [
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=json.dumps(test_input)),
]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, [], new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result is not None
expected_output = [test_input, TEST_INSTANCE_ID, str(start_time), False]
assert complete_action.result.value == json.dumps(expected_output)
def test_complete_orchestration_actions():
"""Tests the actions output for a completed orchestration"""
def empty_orchestrator(ctx: task.OrchestrationContext, _):
return "done"
registry = worker._Registry()
name = registry.add_orchestrator(empty_orchestrator)
new_events = [helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, [], new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == '"done"' # results are JSON-encoded
def test_orchestrator_not_registered():
"""Tests the effect of scheduling an unregistered orchestrator"""
registry = worker._Registry()
name = "Bogus"
new_events = [helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, [], new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == "OrchestratorNotRegisteredError"
assert complete_action.failureDetails.errorMessage
def test_create_timer_actions():
"""Tests the actions output for the create_timer orchestrator method"""
def delay_orchestrator(ctx: task.OrchestrationContext, _):
due_time = ctx.current_utc_datetime + timedelta(seconds=1)
yield ctx.create_timer(due_time)
return "done"
registry = worker._Registry()
name = registry.add_orchestrator(delay_orchestrator)
start_time = datetime(2020, 1, 1, 12, 0, 0)
expected_fire_at = start_time + timedelta(seconds=1)
new_events = [
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, [], new_events)
actions = result.actions
assert actions is not None
assert len(actions) == 1
assert type(actions[0]) is pb.OrchestratorAction
assert actions[0].id == 1
assert actions[0].HasField("createTimer")
assert actions[0].createTimer.fireAt.ToDatetime() == expected_fire_at
def test_timer_fired_completion():
"""Tests the resumption of task using a timer_fired event"""
def delay_orchestrator(ctx: task.OrchestrationContext, _):
due_time = ctx.current_utc_datetime + timedelta(seconds=1)
yield ctx.create_timer(due_time)
return "done"
registry = worker._Registry()
name = registry.add_orchestrator(delay_orchestrator)
start_time = datetime(2020, 1, 1, 12, 0, 0)
expected_fire_at = start_time + timedelta(seconds=1)
old_events = [
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_timer_created_event(1, expected_fire_at)]
new_events = [
helpers.new_timer_fired_event(1, expected_fire_at)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result is not None
assert complete_action.result.value == '"done"' # results are JSON-encoded
def test_schedule_activity_actions():
"""Test the actions output for the call_activity orchestrator method"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, orchestrator_input):
yield ctx.call_activity(dummy_activity, input=orchestrator_input)
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
# TODO: Test several different input types (int, bool, str, dict, etc.)
encoded_input = json.dumps(42)
new_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, [], new_events)
actions = result.actions
assert len(actions) == 1
assert type(actions[0]) is pb.OrchestratorAction
assert actions[0].id == 1
assert actions[0].HasField("scheduleTask")
assert actions[0].scheduleTask.name == task.get_name(dummy_activity)
assert actions[0].scheduleTask.input.value == encoded_input
def test_activity_task_completion():
"""Tests the successful completion of an activity task"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, orchestrator_input):
result = yield ctx.call_activity(dummy_activity, input=orchestrator_input)
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, task.get_name(dummy_activity))]
encoded_output = json.dumps("done!")
new_events = [helpers.new_task_completed_event(1, encoded_output)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == encoded_output
def test_activity_task_failed():
"""Tests the failure of an activity task"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, orchestrator_input):
result = yield ctx.call_activity(dummy_activity, input=orchestrator_input)
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, task.get_name(dummy_activity))]
ex = Exception("Kah-BOOOOM!!!")
new_events = [helpers.new_task_failed_event(1, ex)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'TaskFailedError' # TODO: Should this be the specific error?
assert str(ex) in complete_action.failureDetails.errorMessage
# Make sure the line of code where the exception was raised is included in the stack trace
user_code_statement = "ctx.call_activity(dummy_activity, input=orchestrator_input)"
assert user_code_statement in complete_action.failureDetails.stackTrace.value
def test_activity_retry_policies():
"""Tests the retry policy logic for activity tasks"""
def dummy_activity(ctx, _):
raise ValueError("Kah-BOOOOM!!!")
def orchestrator(ctx: task.OrchestrationContext, orchestrator_input):
result = yield ctx.call_activity(
dummy_activity,
retry_policy=task.RetryPolicy(
first_retry_interval=timedelta(seconds=1),
max_number_of_attempts=6,
backoff_coefficient=2,
max_retry_interval=timedelta(seconds=10),
retry_timeout=timedelta(seconds=50)),
input=orchestrator_input)
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
current_timestamp = datetime.utcnow()
# Simulate the task failing for the first time and confirm that a timer is scheduled for 1 second in the future
old_events = [
helpers.new_orchestrator_started_event(timestamp=current_timestamp),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, task.get_name(dummy_activity))]
expected_fire_at = current_timestamp + timedelta(seconds=1)
new_events = [
helpers.new_orchestrator_started_event(timestamp=current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 1
assert actions[0].HasField("createTimer")
assert actions[0].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[0].id == 2
# Simulate the timer firing at the expected time and confirm that another activity task is scheduled
current_timestamp = expected_fire_at
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_timer_fired_event(2, current_timestamp)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 2
assert actions[1].HasField("scheduleTask")
assert actions[1].id == 1
# Simulate the task failing for the second time and confirm that a timer is scheduled for 2 seconds in the future
old_events = old_events + new_events
expected_fire_at = current_timestamp + timedelta(seconds=2)
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 3
assert actions[2].HasField("createTimer")
assert actions[2].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[2].id == 3
# Simulate the timer firing at the expected time and confirm that another activity task is scheduled
current_timestamp = expected_fire_at
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_timer_fired_event(3, current_timestamp)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 3
assert actions[1].HasField("scheduleTask")
assert actions[1].id == 1
# Simulate the task failing for a third time and confirm that a timer is scheduled for 4 seconds in the future
expected_fire_at = current_timestamp + timedelta(seconds=4)
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 4
assert actions[3].HasField("createTimer")
assert actions[3].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[3].id == 4
# Simulate the timer firing at the expected time and confirm that another activity task is scheduled
current_timestamp = expected_fire_at
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_timer_fired_event(4, current_timestamp)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 4
assert actions[1].HasField("scheduleTask")
assert actions[1].id == 1
# Simulate the task failing for a fourth time and confirm that a timer is scheduled for 8 seconds in the future
expected_fire_at = current_timestamp + timedelta(seconds=8)
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 5
assert actions[4].HasField("createTimer")
assert actions[4].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[4].id == 5
# Simulate the timer firing at the expected time and confirm that another activity task is scheduled
current_timestamp = expected_fire_at
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_timer_fired_event(5, current_timestamp)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 5
assert actions[1].HasField("scheduleTask")
assert actions[1].id == 1
# Simulate the task failing for a fifth time and confirm that a timer is scheduled for 10 seconds in the future.
# This time, the timer will fire after 10 seconds, instead of 16, as max_retry_interval is set to 10 seconds.
expected_fire_at = current_timestamp + timedelta(seconds=10)
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 6
assert actions[5].HasField("createTimer")
assert actions[5].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[5].id == 6
# Simulate the timer firing at the expected time and confirm that another activity task is scheduled
current_timestamp = expected_fire_at
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_timer_fired_event(6, current_timestamp)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 6
assert actions[1].HasField("scheduleTask")
assert actions[1].id == 1
# Simulate the task failing for a sixth time and confirm that orchestration is marked as failed finally.
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!"))]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 7
assert actions[-1].completeOrchestration.failureDetails.errorMessage.__contains__("Activity task #1 failed: Kah-BOOOOM!!!")
assert actions[-1].id == 7
def test_nondeterminism_expected_timer():
"""Tests the non-determinism detection logic when call_timer is expected but some other method (call_activity) is called instead"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.call_activity(dummy_activity)
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
fire_at = datetime.now()
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_timer_created_event(1, fire_at)]
new_events = [helpers.new_timer_fired_event(timer_id=1, fire_at=fire_at)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "create_timer" in complete_action.failureDetails.errorMessage # expected method name
assert "call_activity" in complete_action.failureDetails.errorMessage # actual method name
def test_nondeterminism_expected_activity_call_no_task_id():
"""Tests the non-determinism detection logic when invoking activity functions"""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield task.CompletableTask() # dummy task
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, "bogus_activity")]
new_events = [helpers.new_task_completed_event(1)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "call_activity" in complete_action.failureDetails.errorMessage # expected method name
def test_nondeterminism_expected_activity_call_wrong_task_type():
"""Tests the non-determinism detection when an activity exists in the history but a non-activity is in the code"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, _):
# create a timer when the history expects an activity call
yield ctx.create_timer(datetime.now())
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, task.get_name(dummy_activity))]
new_events = [helpers.new_task_completed_event(1)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "call_activity" in complete_action.failureDetails.errorMessage # expected method name
assert "create_timer" in complete_action.failureDetails.errorMessage # unexpected method name
def test_nondeterminism_wrong_activity_name():
"""Tests the non-determinism detection when calling an activity with a name that differs from the name in the history"""
def dummy_activity(ctx, _):
pass
def orchestrator(ctx: task.OrchestrationContext, _):
# create a timer when the history expects an activity call
yield ctx.call_activity(dummy_activity)
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, "original_activity")]
new_events = [helpers.new_task_completed_event(1)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "call_activity" in complete_action.failureDetails.errorMessage # expected method name
assert "original_activity" in complete_action.failureDetails.errorMessage # expected activity name
assert "dummy_activity" in complete_action.failureDetails.errorMessage # unexpected activity name
def test_sub_orchestration_task_completion():
"""Tests that a sub-orchestration task is completed when the sub-orchestration completes"""
def suborchestrator(ctx: task.OrchestrationContext, _):
pass
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.call_sub_orchestrator(suborchestrator)
return result
registry = worker._Registry()
suborchestrator_name = registry.add_orchestrator(suborchestrator)
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_sub_orchestration_created_event(1, suborchestrator_name, "sub-orch-123", encoded_input=None)]
new_events = [
helpers.new_sub_orchestration_completed_event(1, encoded_output="42")]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == "42"
def test_sub_orchestration_task_failed():
"""Tests that a sub-orchestration task is completed when the sub-orchestration fails"""
def suborchestrator(ctx: task.OrchestrationContext, _):
pass
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.call_sub_orchestrator(suborchestrator)
return result
registry = worker._Registry()
suborchestrator_name = registry.add_orchestrator(suborchestrator)
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_sub_orchestration_created_event(1, suborchestrator_name, "sub-orch-123", encoded_input=None)]
ex = Exception("Kah-BOOOOM!!!")
new_events = [helpers.new_sub_orchestration_failed_event(1, ex)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'TaskFailedError' # TODO: Should this be the specific error?
assert str(ex) in complete_action.failureDetails.errorMessage
# Make sure the line of code where the exception was raised is included in the stack trace
user_code_statement = "ctx.call_sub_orchestrator(suborchestrator)"
assert user_code_statement in complete_action.failureDetails.stackTrace.value
def test_nondeterminism_expected_sub_orchestration_task_completion_no_task():
"""Tests the non-determinism detection when a sub-orchestration action is encounteed when it shouldn't be"""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield task.CompletableTask() # dummy task
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_sub_orchestration_created_event(1, "some_sub_orchestration", "sub-orch-123", encoded_input=None)]
new_events = [
helpers.new_sub_orchestration_completed_event(1, encoded_output="42")]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "call_sub_orchestrator" in complete_action.failureDetails.errorMessage # expected method name
def test_nondeterminism_expected_sub_orchestration_task_completion_wrong_task_type():
"""Tests the non-determinism detection when a sub-orchestration action is encounteed when it shouldn't be.
This variation tests the case where the expected task type is wrong (e.g. the code schedules a timer task
but the history contains a sub-orchestration completed task)."""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.create_timer(datetime.utcnow()) # created timer but history expects sub-orchestration
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_sub_orchestration_created_event(1, "some_sub_orchestration", "sub-orch-123", encoded_input=None)]
new_events = [
helpers.new_sub_orchestration_completed_event(1, encoded_output="42")]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'NonDeterminismError'
assert "1" in complete_action.failureDetails.errorMessage # task ID
assert "call_sub_orchestrator" in complete_action.failureDetails.errorMessage # expected method name
def test_raise_event():
"""Tests that an orchestration can wait for and process an external event sent by a client"""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.wait_for_external_event("my_event")
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = []
new_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID)]
# Execute the orchestration until it is waiting for an external event. The result
# should be an empty list of actions because the orchestration didn't schedule any work.
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 0
# Now send an external event to the orchestration and execute it again. This time
# the orchestration should complete.
old_events = new_events
new_events = [helpers.new_event_raised_event("my_event", encoded_input="42")]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == "42"
def test_raise_event_buffered():
"""Tests that an orchestration can receive an event that arrives earlier than expected"""
def orchestrator(ctx: task.OrchestrationContext, _):
yield ctx.create_timer(ctx.current_utc_datetime + timedelta(days=1))
result = yield ctx.wait_for_external_event("my_event")
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = []
new_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID),
helpers.new_event_raised_event("my_event", encoded_input="42")]
# Execute the orchestration. It should be in a running state waiting for the timer to fire
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 1
assert actions[0].HasField("createTimer")
# Complete the timer task. The orchestration should move to the wait_for_external_event step, which
# should then complete immediately because the event was buffered in the old event history.
timer_due_time = datetime.utcnow() + timedelta(days=1)
old_events = new_events + [helpers.new_timer_created_event(1, timer_due_time)]
new_events = [helpers.new_timer_fired_event(1, timer_due_time)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == "42"
def test_suspend_resume():
"""Tests that an orchestration can be suspended and resumed"""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.wait_for_external_event("my_event")
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID)]
new_events = [
helpers.new_suspend_event(),
helpers.new_event_raised_event("my_event", encoded_input="42")]
# Execute the orchestration. It should remain in a running state because it was suspended prior
# to processing the event raised event.
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 0
# Resume the orchestration. It should complete successfully.
old_events = old_events + new_events
new_events = [helpers.new_resume_event()]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == "42"
def test_terminate():
"""Tests that an orchestration can be terminated before it completes"""
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.wait_for_external_event("my_event")
return result
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID)]
new_events = [
helpers.new_terminated_event(encoded_output=json.dumps("terminated!")),
helpers.new_event_raised_event("my_event", encoded_input="42")]
# Execute the orchestration. It should be in a running state waiting for an external event
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_TERMINATED
assert complete_action.result.value == json.dumps("terminated!")
@pytest.mark.parametrize("save_events", [True, False])
def test_continue_as_new(save_events: bool):
"""Tests the behavior of the continue-as-new API"""
def orchestrator(ctx: task.OrchestrationContext, input: int):
yield ctx.create_timer(ctx.current_utc_datetime + timedelta(days=1))
ctx.continue_as_new(input + 1, save_events=save_events)
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input="1"),
helpers.new_event_raised_event("my_event", encoded_input="42"),
helpers.new_event_raised_event("my_event", encoded_input="43"),
helpers.new_event_raised_event("my_event", encoded_input="44"),
helpers.new_timer_created_event(1, datetime.utcnow() + timedelta(days=1))]
new_events = [
helpers.new_timer_fired_event(1, datetime.utcnow() + timedelta(days=1))]
# Execute the orchestration. It should be in a running state waiting for the timer to fire
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_CONTINUED_AS_NEW
assert complete_action.result.value == json.dumps(2)
assert len(complete_action.carryoverEvents) == (3 if save_events else 0)
for i in range(len(complete_action.carryoverEvents)):
event = complete_action.carryoverEvents[i]
assert type(event) is pb.HistoryEvent
assert event.HasField("eventRaised")
assert event.eventRaised.name.casefold() == "my_event".casefold() # event names are case-insensitive
assert event.eventRaised.input.value == json.dumps(42 + i)
def test_fan_out():
"""Tests that a fan-out pattern correctly schedules N tasks"""
def hello(_, name: str):
return f"Hello {name}!"
def orchestrator(ctx: task.OrchestrationContext, count: int):
tasks = []
for i in range(count):
tasks.append(ctx.call_activity(hello, input=str(i)))
results = yield task.when_all(tasks)
return results
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
activity_name = registry.add_activity(hello)
old_events = []
new_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input="10")]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
# The result should be 10 "taskScheduled" actions with inputs from 0 to 9
assert len(actions) == 10
for i in range(10):
assert actions[i].HasField("scheduleTask")
assert actions[i].scheduleTask.name == activity_name
assert actions[i].scheduleTask.input.value == f'"{i}"'
def test_fan_in():
"""Tests that a fan-in pattern works correctly"""
def print_int(_, val: int):
return str(val)
def orchestrator(ctx: task.OrchestrationContext, _):
tasks = []
for i in range(10):
tasks.append(ctx.call_activity(print_int, input=i))
results = yield task.when_all(tasks)
return results
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
activity_name = registry.add_activity(print_int)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None)]
for i in range(10):
old_events.append(helpers.new_task_scheduled_event(
i + 1, activity_name, encoded_input=str(i)))
new_events = []
for i in range(10):
new_events.append(helpers.new_task_completed_event(
i + 1, encoded_output=print_int(None, i)))
# First, test with only the first 5 events. We expect the orchestration to be running
# but return zero actions since its still waiting for the other 5 tasks to complete.
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events[:5])
actions = result.actions
assert len(actions) == 0
# Now test with the full set of new events. We expect the orchestration to complete.
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
def test_fan_in_with_single_failure():
"""Tests that a fan-in pattern works correctly when one of the tasks fails"""
def print_int(_, val: int):
return str(val)
def orchestrator(ctx: task.OrchestrationContext, _):
tasks = []
for i in range(10):
tasks.append(ctx.call_activity(print_int, input=i))
results = yield task.when_all(tasks)
return results
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
activity_name = registry.add_activity(print_int)
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None)]
for i in range(10):
old_events.append(helpers.new_task_scheduled_event(
i + 1, activity_name, encoded_input=str(i)))
# 5 of the tasks complete successfully, 1 fails, and 4 are still running.
# The expectation is that the orchestration will fail immediately.
new_events = []
for i in range(5):
new_events.append(helpers.new_task_completed_event(
i + 1, encoded_output=print_int(None, i)))
ex = Exception("Kah-BOOOOM!!!")
new_events.append(helpers.new_task_failed_event(6, ex))
# Now test with the full set of new events. We expect the orchestration to complete.
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_FAILED
assert complete_action.failureDetails.errorType == 'TaskFailedError' # TODO: Is this the right error type?
assert str(ex) in complete_action.failureDetails.errorMessage
def test_when_any():
"""Tests that a when_any pattern works correctly"""
def hello(_, name: str):
return f"Hello {name}!"
def orchestrator(ctx: task.OrchestrationContext, _):
t1 = ctx.call_activity(hello, input="Tokyo")
t2 = ctx.call_activity(hello, input="Seattle")
winner = yield task.when_any([t1, t2])
if winner == t1:
return t1.get_result()
else:
return t2.get_result()
registry = worker._Registry()
orchestrator_name = registry.add_orchestrator(orchestrator)
activity_name = registry.add_activity(hello)
# Test 1: Start the orchestration and let it yield on the when_any. We expect the orchestration
# to return two actions: one to schedule the "Tokyo" task and one to schedule the "Seattle" task.
old_events = []
new_events = [helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert len(actions) == 2
assert actions[0].HasField('scheduleTask')
assert actions[1].HasField('scheduleTask')
# The next tests assume that the orchestration has already awaited at the task.when_any()
old_events = [
helpers.new_orchestrator_started_event(),
helpers.new_execution_started_event(orchestrator_name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, activity_name, encoded_input=json.dumps("Tokyo")),
helpers.new_task_scheduled_event(2, activity_name, encoded_input=json.dumps("Seattle"))]
# Test 2: Complete the "Tokyo" task. We expect the orchestration to complete with output "Hello, Tokyo!"
encoded_output = json.dumps(hello(None, "Tokyo"))
new_events = [helpers.new_task_completed_event(1, encoded_output)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == encoded_output
# Test 3: Complete the "Seattle" task. We expect the orchestration to complete with output "Hello, Seattle!"
encoded_output = json.dumps(hello(None, "Seattle"))
new_events = [helpers.new_task_completed_event(2, encoded_output)]
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
complete_action = get_and_validate_complete_orchestration_action_list(1, actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == encoded_output