-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathtest_orchestration_executor.py
More file actions
1956 lines (1596 loc) · 84 KB
/
test_orchestration_executor.py
File metadata and controls
1956 lines (1596 loc) · 84 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_long_timer_is_chunked_by_maximum_timer_interval():
"""Tests that long timers are scheduled in chunks when exceeding max timer interval."""
def orchestrator(ctx: task.OrchestrationContext, _):
due_time = ctx.current_utc_datetime + timedelta(days=10)
yield ctx.create_timer(due_time)
return "done"
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
start_time = datetime(2020, 1, 1, 12, 0, 0)
first_chunk_fire_at = start_time + timedelta(days=3)
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 len(actions) == 1
assert actions[0].HasField("createTimer")
assert actions[0].id == 1
assert actions[0].createTimer.fireAt.ToDatetime() == first_chunk_fire_at
def test_long_timer_progresses_and_completes_on_final_chunk():
"""Tests that long timers schedule intermediate chunks and complete on the final timerFired."""
def orchestrator(ctx: task.OrchestrationContext, _):
due_time = ctx.current_utc_datetime + timedelta(days=10)
yield ctx.create_timer(due_time)
return "done"
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
start_time = datetime(2020, 1, 1, 12, 0, 0)
t1 = start_time + timedelta(days=3)
t2 = start_time + timedelta(days=6)
t3 = start_time + timedelta(days=9)
t4 = start_time + timedelta(days=10)
# 1) Initial execution schedules first chunk.
first = executor.execute(
TEST_INSTANCE_ID,
[],
[
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
],
)
assert len(first.actions) == 1
assert first.actions[0].HasField("createTimer")
assert first.actions[0].id == 1
assert first.actions[0].createTimer.fireAt.ToDatetime() == t1
# 2) First chunk fires -> schedule second chunk.
second_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, t1),
]
second = executor.execute(
TEST_INSTANCE_ID,
second_old_events,
[helpers.new_timer_fired_event(1, t1)],
)
assert len(second.actions) == 1
assert second.actions[0].HasField("createTimer")
assert second.actions[0].id == 2
assert second.actions[0].createTimer.fireAt.ToDatetime() == t2
# 3) Second chunk fires -> schedule third chunk.
third_old_events = second_old_events + [
helpers.new_timer_fired_event(1, t1),
helpers.new_timer_created_event(2, t2),
]
third = executor.execute(
TEST_INSTANCE_ID,
third_old_events,
[helpers.new_timer_fired_event(2, t2)],
)
assert len(third.actions) == 1
assert third.actions[0].HasField("createTimer")
assert third.actions[0].id == 3
assert third.actions[0].createTimer.fireAt.ToDatetime() == t3
# 4) Third chunk fires -> schedule final short chunk.
fourth_old_events = third_old_events + [
helpers.new_timer_fired_event(2, t2),
helpers.new_timer_created_event(3, t3),
]
fourth = executor.execute(
TEST_INSTANCE_ID,
fourth_old_events,
[helpers.new_timer_fired_event(3, t3)],
)
assert len(fourth.actions) == 1
assert fourth.actions[0].HasField("createTimer")
assert fourth.actions[0].id == 4
assert fourth.actions[0].createTimer.fireAt.ToDatetime() == t4
# 5) Final chunk fires -> orchestration completes.
fifth_old_events = fourth_old_events + [
helpers.new_timer_fired_event(3, t3),
helpers.new_timer_created_event(4, t4),
]
fifth = executor.execute(
TEST_INSTANCE_ID,
fifth_old_events,
[helpers.new_timer_fired_event(4, t4)],
)
complete_action = get_and_validate_complete_orchestration_action_list(1, fifth.actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == '"done"'
def test_long_timer_can_be_cancelled_after_when_any_winner():
"""Tests cancellation of a long timer after an external event wins when_any."""
def orchestrator(ctx: task.OrchestrationContext, _):
approval = ctx.wait_for_external_event("approval")
timeout = ctx.create_timer(timedelta(days=10))
winner = yield task.when_any([approval, timeout])
if winner == approval:
timeout.cancel()
return "approved"
return "timed out"
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
start_time = datetime(2020, 1, 1, 12, 0, 0)
first_chunk_fire_at = start_time + timedelta(days=3)
# Initial execution schedules first long-timer chunk.
first = executor.execute(
TEST_INSTANCE_ID,
[],
[
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
],
)
assert len(first.actions) == 1
assert first.actions[0].HasField("createTimer")
assert first.actions[0].createTimer.fireAt.ToDatetime() == first_chunk_fire_at
# External event arrives before timeout -> long timer is cancelled and orchestration completes.
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, first_chunk_fire_at),
]
second = executor.execute(
TEST_INSTANCE_ID,
old_events,
[helpers.new_event_raised_event("approval", json.dumps(True))],
)
complete_action = get_and_validate_complete_orchestration_action_list(1, second.actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == '"approved"'
def test_timer_can_be_cancelled_after_when_any_winner():
"""Tests cancellation of an outstanding timer task after another task wins when_any."""
def orchestrator(ctx: task.OrchestrationContext, _):
approval = ctx.wait_for_external_event("approval")
timeout = ctx.create_timer(timedelta(hours=1))
winner = yield task.when_any([approval, timeout])
if winner == approval:
timeout.cancel()
return "approved"
return "timed out"
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
start_time = datetime(2020, 1, 1, 12, 0, 0)
timeout_fire_at = start_time + timedelta(hours=1)
result = executor.execute(
TEST_INSTANCE_ID,
[],
[
helpers.new_orchestrator_started_event(start_time),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
],
)
assert len(result.actions) == 1
assert result.actions[0].HasField("createTimer")
assert result.actions[0].createTimer.fireAt.ToDatetime() == timeout_fire_at
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, timeout_fire_at),
]
result = executor.execute(
TEST_INSTANCE_ID,
old_events,
[helpers.new_event_raised_event("approval", json.dumps(True))],
)
complete_action = get_and_validate_complete_orchestration_action_list(1, result.actions)
assert complete_action.orchestrationStatus == pb.ORCHESTRATION_STATUS_COMPLETED
assert complete_action.result.value == '"approved"'
def test_only_cancellable_tasks_expose_cancel():
"""Tests that only timer and external-event tasks expose cancellation state and operations."""
def dummy_activity(ctx, _):
pass
ctx = worker._RuntimeOrchestrationContext(TEST_INSTANCE_ID, worker._Registry())
timer_task = ctx.create_timer(timedelta(minutes=5))
external_event_task = ctx.wait_for_external_event("approval")
activity_task = ctx.call_activity(dummy_activity)
assert isinstance(timer_task, task.CancellableTask)
assert isinstance(external_event_task, task.CancellableTask)
assert not isinstance(activity_task, task.CancellableTask)
assert hasattr(timer_task, "cancel")
assert hasattr(external_event_task, "cancel")
assert not hasattr(activity_task, "cancel")
assert hasattr(timer_task, "is_cancelled")
assert hasattr(external_event_task, "is_cancelled")
assert not hasattr(activity_task, "is_cancelled")
def test_cancelled_task_get_result_raises_task_cancelled_error():
"""Tests that cancelled cancellable tasks raise TaskCancelledError from get_result."""
cancellable_task = task.CancellableTask()
assert cancellable_task.cancel() is True
assert cancellable_task.is_cancelled is True
with pytest.raises(task.TaskCancelledError):
cancellable_task.get_result()
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_activity_retry_without_max_retry_interval():
"""Tests that retry logic works correctly when max_retry_interval is not set.
This is a regression test for a bug where compute_next_delay() returned None
instead of the computed delay when max_retry_interval was not specified,
causing retries to silently fail.
"""
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=3,
backoff_coefficient=2),
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 — retry timer should be created at 1 second
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 and a second failure — retry timer should be at 2 seconds (backoff)
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
expected_fire_at = current_timestamp + timedelta(seconds=2)
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) == 3
assert actions[2].HasField("createTimer")
assert actions[2].createTimer.fireAt.ToDatetime() == expected_fire_at
assert actions[2].id == 3
# Simulate the timer firing and a third failure — should now fail (max_number_of_attempts=3)
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")
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[-1].completeOrchestration.failureDetails.errorMessage.__contains__("Activity task #1 failed: Kah-BOOOOM!!!")
def test_activity_retry_with_default_backoff():
"""Tests retry with default backoff_coefficient (1.0) and no max_retry_interval.
Verifies that retry delays remain constant when backoff_coefficient defaults to 1.0.
"""
def dummy_activity(ctx, _):
raise ValueError("Fail!")
def orchestrator(ctx: task.OrchestrationContext, _):
result = yield ctx.call_activity(
dummy_activity,
retry_policy=task.RetryPolicy(
first_retry_interval=timedelta(seconds=5),
max_number_of_attempts=3))
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
current_timestamp = datetime.utcnow()
# First failure — retry timer at 5 seconds (default backoff=1.0, so 5 * 1^0 = 5)
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=5)
new_events = [
helpers.new_orchestrator_started_event(timestamp=current_timestamp),
helpers.new_task_failed_event(1, ValueError("Fail!"))]
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
# Second failure — retry timer still at 5 seconds (5 * 1^1 = 5, no backoff growth)
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)
expected_fire_at = current_timestamp + timedelta(seconds=5)
old_events = old_events + new_events
new_events = [
helpers.new_orchestrator_started_event(current_timestamp),
helpers.new_task_failed_event(1, ValueError("Fail!"))]
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
def test_activity_retry_with_long_timer_preserves_retryable_parent():
"""Tests that long retry timers keep retryable parent state until the final chunk fires."""
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(days=10),
max_number_of_attempts=2,
backoff_coefficient=1,
),
input=orchestrator_input,
)
return result
registry = worker._Registry()
name = registry.add_orchestrator(orchestrator)
executor = worker._OrchestrationExecutor(registry, TEST_LOGGER)
start = datetime.utcnow()
t1 = start + timedelta(days=3)
t2 = start + timedelta(days=6)
t3 = start + timedelta(days=9)
t4 = start + timedelta(days=10)
old_events = [
helpers.new_orchestrator_started_event(timestamp=start),
helpers.new_execution_started_event(name, TEST_INSTANCE_ID, encoded_input=None),
helpers.new_task_scheduled_event(1, task.get_name(dummy_activity)),
]
# First activity failure should create the first long-timer chunk.
new_events = [
helpers.new_orchestrator_started_event(timestamp=start),
helpers.new_task_failed_event(1, ValueError("Kah-BOOOOM!!!")),
]
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert actions[-1].HasField("createTimer")
assert actions[-1].id == 2
assert actions[-1].createTimer.fireAt.ToDatetime() == t1
old_events = old_events + new_events
# Intermediate chunk 1 fires -> schedule next chunk, not activity retry yet.
new_events = [
helpers.new_orchestrator_started_event(t1),
helpers.new_timer_fired_event(2, t1),
]
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert actions[-1].HasField("createTimer")
assert actions[-1].id == 3
assert actions[-1].createTimer.fireAt.ToDatetime() == t2
assert not actions[-1].HasField("scheduleTask")
old_events = old_events + new_events
# Intermediate chunk 2 fires -> schedule next chunk, still no activity retry.
new_events = [
helpers.new_orchestrator_started_event(t2),
helpers.new_timer_fired_event(3, t2),
]
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert actions[-1].HasField("createTimer")
assert actions[-1].id == 4
assert actions[-1].createTimer.fireAt.ToDatetime() == t3
assert not actions[-1].HasField("scheduleTask")
old_events = old_events + new_events
# Intermediate chunk 3 fires -> schedule final chunk, still no activity retry.
new_events = [
helpers.new_orchestrator_started_event(t3),
helpers.new_timer_fired_event(4, t3),
]
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert actions[-1].HasField("createTimer")
assert actions[-1].id == 5
assert actions[-1].createTimer.fireAt.ToDatetime() == t4
assert not actions[-1].HasField("scheduleTask")
old_events = old_events + new_events
# Final chunk fires -> retry activity should be rescheduled with original task ID.
new_events = [
helpers.new_orchestrator_started_event(t4),
helpers.new_timer_fired_event(5, t4),
]
result = executor.execute(TEST_INSTANCE_ID, old_events, new_events)
actions = result.actions
assert actions[-1].HasField("scheduleTask")
assert actions[-1].id == 1
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