-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathconcurrency_test.py
More file actions
3155 lines (2427 loc) · 104 KB
/
concurrency_test.py
File metadata and controls
3155 lines (2427 loc) · 104 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
"""Tests for the concurrency module."""
import json
import random
import threading
import time
from concurrent.futures import Future
from functools import partial
from itertools import combinations
from unittest.mock import Mock, patch
import pytest
from aws_durable_execution_sdk_python.concurrency.executor import (
ConcurrentExecutor,
TimerScheduler,
)
from aws_durable_execution_sdk_python.concurrency.models import (
BatchItem,
BatchItemStatus,
BatchResult,
BranchStatus,
CompletionReason,
Executable,
ExecutableWithState,
ExecutionCounters,
)
from aws_durable_execution_sdk_python.config import CompletionConfig, MapConfig
from aws_durable_execution_sdk_python.exceptions import (
CallableRuntimeError,
InvalidStateError,
SuspendExecution,
TimedSuspendExecution,
)
from aws_durable_execution_sdk_python.lambda_service import (
ErrorObject,
)
from aws_durable_execution_sdk_python.operation.map import MapExecutor
def test_batch_item_status_enum():
"""Test BatchItemStatus enum values."""
assert BatchItemStatus.SUCCEEDED.value == "SUCCEEDED"
assert BatchItemStatus.FAILED.value == "FAILED"
assert BatchItemStatus.STARTED.value == "STARTED"
def test_completion_reason_enum():
"""Test CompletionReason enum values."""
assert CompletionReason.ALL_COMPLETED.value == "ALL_COMPLETED"
assert CompletionReason.MIN_SUCCESSFUL_REACHED.value == "MIN_SUCCESSFUL_REACHED"
assert (
CompletionReason.FAILURE_TOLERANCE_EXCEEDED.value
== "FAILURE_TOLERANCE_EXCEEDED"
)
def test_branch_status_enum():
"""Test BranchStatus enum values."""
assert BranchStatus.PENDING.value == "pending"
assert BranchStatus.RUNNING.value == "running"
assert BranchStatus.COMPLETED.value == "completed"
assert BranchStatus.SUSPENDED.value == "suspended"
assert BranchStatus.SUSPENDED_WITH_TIMEOUT.value == "suspended_with_timeout"
assert BranchStatus.FAILED.value == "failed"
def test_batch_item_creation():
"""Test BatchItem creation and properties."""
item = BatchItem(index=0, status=BatchItemStatus.SUCCEEDED, result="test_result")
assert item.index == 0
assert item.status == BatchItemStatus.SUCCEEDED
assert item.result == "test_result"
assert item.error is None
def test_batch_item_to_dict():
"""Test BatchItem to_dict method."""
error = ErrorObject(
message="test message", type="TestError", data=None, stack_trace=None
)
item = BatchItem(index=1, status=BatchItemStatus.FAILED, error=error)
result = item.to_dict()
expected = {
"index": 1,
"status": "FAILED",
"result": None,
"error": error.to_dict(),
}
assert result == expected
def test_batch_item_from_dict():
"""Test BatchItem from_dict method."""
data = {
"index": 2,
"status": "SUCCEEDED",
"result": "success_result",
"error": None,
}
item = BatchItem.from_dict(data)
assert item.index == 2
assert item.status == BatchItemStatus.SUCCEEDED
assert item.result == "success_result"
assert item.error is None
def test_batch_result_creation():
"""Test BatchResult creation."""
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert len(result.all) == 2
assert result.completion_reason == CompletionReason.ALL_COMPLETED
def test_batch_result_succeeded():
"""Test BatchResult succeeded method."""
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
BatchItem(2, BatchItemStatus.SUCCEEDED, "result2"),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
succeeded = result.succeeded()
assert len(succeeded) == 2
assert succeeded[0].result == "result1"
assert succeeded[1].result == "result2"
def test_batch_result_failed():
"""Test BatchResult failed method."""
error = ErrorObject("test message", "TestError", None, None)
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(1, BatchItemStatus.FAILED, error=error),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
failed = result.failed()
assert len(failed) == 1
assert failed[0].error == error
def test_batch_result_started():
"""Test BatchResult started method."""
items = [
BatchItem(0, BatchItemStatus.STARTED),
BatchItem(1, BatchItemStatus.SUCCEEDED, "result1"),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
started = result.started()
assert len(started) == 1
assert started[0].status == BatchItemStatus.STARTED
def test_batch_result_status():
"""Test BatchResult status property."""
# No failures
items = [BatchItem(0, BatchItemStatus.SUCCEEDED, "result1")]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert result.status == BatchItemStatus.SUCCEEDED
# Has failures
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert result.status == BatchItemStatus.FAILED
def test_batch_result_has_failure():
"""Test BatchResult has_failure property."""
# No failures
items = [BatchItem(0, BatchItemStatus.SUCCEEDED, "result1")]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert not result.has_failure
# Has failures
items = [
BatchItem(
0, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
)
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert result.has_failure
def test_batch_result_throw_if_error():
"""Test BatchResult throw_if_error method."""
# No errors
items = [BatchItem(0, BatchItemStatus.SUCCEEDED, "result1")]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
result.throw_if_error() # Should not raise
# Has error
error = ErrorObject("test message", "TestError", None, None)
items = [BatchItem(0, BatchItemStatus.FAILED, error=error)]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
with pytest.raises(CallableRuntimeError):
result.throw_if_error()
def test_batch_result_get_results():
"""Test BatchResult get_results method."""
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
BatchItem(2, BatchItemStatus.SUCCEEDED, "result2"),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
results = result.get_results()
assert results == ["result1", "result2"]
def test_batch_result_get_errors():
"""Test BatchResult get_errors method."""
error1 = ErrorObject("msg1", "Error1", None, None)
error2 = ErrorObject("msg2", "Error2", None, None)
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(1, BatchItemStatus.FAILED, error=error1),
BatchItem(2, BatchItemStatus.FAILED, error=error2),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
errors = result.get_errors()
assert len(errors) == 2
assert error1 in errors
assert error2 in errors
def test_batch_result_counts():
"""Test BatchResult count properties."""
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
BatchItem(2, BatchItemStatus.STARTED),
BatchItem(3, BatchItemStatus.SUCCEEDED, "result2"),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
assert result.success_count == 2
assert result.failure_count == 1
assert result.started_count == 1
assert result.total_count == 4
def test_batch_result_to_dict():
"""Test BatchResult to_dict method."""
items = [BatchItem(0, BatchItemStatus.SUCCEEDED, "result1")]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
result_dict = result.to_dict()
expected = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None}
],
"completionReason": "ALL_COMPLETED",
}
assert result_dict == expected
def test_batch_result_from_dict():
"""Test BatchResult from_dict method."""
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None}
],
"completionReason": "ALL_COMPLETED",
}
result = BatchResult.from_dict(data)
assert len(result.all) == 1
assert result.all[0].index == 0
assert result.all[0].status == BatchItemStatus.SUCCEEDED
assert result.completion_reason == CompletionReason.ALL_COMPLETED
def test_batch_result_from_dict_default_completion_reason():
"""Test BatchResult from_dict with default completion reason."""
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None}
],
# No completionReason provided
}
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.ALL_COMPLETED
# Verify warning was logged
mock_logger.warning.assert_called_once()
assert "Missing completionReason" in mock_logger.warning.call_args[0][0]
def test_batch_result_from_dict_infer_all_completed_all_succeeded():
"""Test BatchResult from_dict infers ALL_COMPLETED when all items succeeded."""
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None},
{"index": 1, "status": "SUCCEEDED", "result": "result2", "error": None},
],
# No completionReason provided
}
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.ALL_COMPLETED
mock_logger.warning.assert_called_once()
def test_batch_result_from_dict_infer_failure_tolerance_exceeded_all_failed():
"""Test BatchResult from_dict infers FAILURE_TOLERANCE_EXCEEDED when all items failed."""
error_data = {
"message": "Test error",
"type": "TestError",
"data": None,
"stackTrace": None,
}
data = {
"all": [
{"index": 0, "status": "FAILED", "result": None, "error": error_data},
{"index": 1, "status": "FAILED", "result": None, "error": error_data},
],
# No completionReason provided
}
# even if everything has failed, if we've completed all items, then we've finished as ALL_COMPLETED
# https://github.com/aws/aws-durable-execution-sdk-js/blob/f20396f24afa9d6539d8e5056ee851ac7ef62301/packages/aws-durable-execution-sdk-js/src/handlers/concurrent-execution-handler/concurrent-execution-handler.ts#L324-L335
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.ALL_COMPLETED
mock_logger.warning.assert_called_once()
def test_batch_result_from_dict_infer_all_completed_mixed_success_failure():
"""Test BatchResult from_dict infers ALL_COMPLETED when mix of success/failure but no started items."""
error_data = {
"message": "Test error",
"type": "TestError",
"data": None,
"stackTrace": None,
}
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None},
{"index": 1, "status": "FAILED", "result": None, "error": error_data},
{"index": 2, "status": "SUCCEEDED", "result": "result2", "error": None},
],
# No completionReason provided
}
# the logic is that when \every item i: hasCompleted(i) then terminate due to all_completed
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.ALL_COMPLETED
mock_logger.warning.assert_called_once()
def test_batch_result_from_dict_infer_min_successful_reached_has_started():
"""Test BatchResult from_dict infers MIN_SUCCESSFUL_REACHED when items are still started."""
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None},
{"index": 1, "status": "STARTED", "result": None, "error": None},
{"index": 2, "status": "SUCCEEDED", "result": "result2", "error": None},
],
# No completionReason provided
}
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data, CompletionConfig(1))
assert result.completion_reason == CompletionReason.MIN_SUCCESSFUL_REACHED
mock_logger.warning.assert_called_once()
def test_batch_result_from_dict_infer_empty_items():
"""Test BatchResult from_dict infers ALL_COMPLETED for empty items."""
data = {
"all": [],
# No completionReason provided
}
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.ALL_COMPLETED
mock_logger.warning.assert_called_once()
def test_batch_result_from_dict_with_explicit_completion_reason():
"""Test BatchResult from_dict uses explicit completionReason when provided."""
data = {
"all": [
{"index": 0, "status": "SUCCEEDED", "result": "result1", "error": None}
],
"completionReason": "MIN_SUCCESSFUL_REACHED",
}
with patch(
"aws_durable_execution_sdk_python.concurrency.models.logger"
) as mock_logger:
result = BatchResult.from_dict(data)
assert result.completion_reason == CompletionReason.MIN_SUCCESSFUL_REACHED
# No warning should be logged when completionReason is provided
mock_logger.warning.assert_not_called()
def test_batch_result_infer_completion_reason_edge_cases():
"""Test _infer_completion_reason method with various edge cases."""
# Test with only started items
started_items = [
BatchItem(0, BatchItemStatus.STARTED).to_dict(),
BatchItem(1, BatchItemStatus.STARTED).to_dict(),
]
items = {"all": started_items}
batch = BatchResult.from_dict(items, CompletionConfig(0)) # SLF001
# this state is not possible with CompletionConfig(0)
assert batch.completion_reason == CompletionReason.MIN_SUCCESSFUL_REACHED
# Test with only started items
started_items = [
BatchItem(0, BatchItemStatus.STARTED).to_dict(),
BatchItem(1, BatchItemStatus.STARTED).to_dict(),
]
items = {"all": started_items}
batch = BatchResult.from_dict(items) # SLF001
# this state is not possible with CompletionConfig(0)
assert batch.completion_reason == CompletionReason.FAILURE_TOLERANCE_EXCEEDED
# Test with only failed items
failed_items = [
BatchItem(
0, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
).to_dict(),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
).to_dict(),
]
failed_items = {"all": failed_items}
batch = BatchResult.from_dict(failed_items) # SLF001
assert batch.completion_reason == CompletionReason.ALL_COMPLETED
# Test with only succeeded items
succeeded_items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1").to_dict(),
BatchItem(1, BatchItemStatus.SUCCEEDED, "result2").to_dict(),
]
succeeded_items = {"all": succeeded_items}
batch = BatchResult.from_dict(succeeded_items) # SLF001
assert batch.completion_reason == CompletionReason.ALL_COMPLETED
# Test with mixed but no started (all completed)
mixed_items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
]
batch = BatchResult.from_items(mixed_items) # SLF001
assert batch.completion_reason == CompletionReason.ALL_COMPLETED
def test_batch_result_get_results_empty():
"""Test BatchResult get_results with no successful items."""
items = [
BatchItem(
0, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
BatchItem(1, BatchItemStatus.STARTED),
]
result = BatchResult(items, CompletionReason.FAILURE_TOLERANCE_EXCEEDED)
results = result.get_results()
assert results == []
def test_batch_result_get_errors_empty():
"""Test BatchResult get_errors with no failed items."""
items = [
BatchItem(0, BatchItemStatus.SUCCEEDED, "result1"),
BatchItem(1, BatchItemStatus.STARTED),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
errors = result.get_errors()
assert errors == []
def test_executable_creation():
"""Test Executable creation."""
def test_func():
return "test"
executable = Executable(index=5, func=test_func)
assert executable.index == 5
assert executable.func == test_func
def test_executable_with_state_creation():
"""Test ExecutableWithState creation."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
assert exe_state.executable == executable
assert exe_state.status == BranchStatus.PENDING
assert exe_state.index == 1
assert exe_state.callable == executable.func
def test_executable_with_state_properties():
"""Test ExecutableWithState property access."""
def test_callable():
return "test"
executable = Executable(index=42, func=test_callable)
exe_state = ExecutableWithState(executable)
assert exe_state.index == 42
assert exe_state.callable == test_callable
assert exe_state.suspend_until is None
def test_executable_with_state_future_not_available():
"""Test ExecutableWithState future property when not started."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
with pytest.raises(InvalidStateError):
_ = exe_state.future
def test_executable_with_state_result_not_available():
"""Test ExecutableWithState result property when not completed."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
with pytest.raises(InvalidStateError):
_ = exe_state.result
def test_executable_with_state_error_not_available():
"""Test ExecutableWithState error property when not failed."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
with pytest.raises(InvalidStateError):
_ = exe_state.error
def test_executable_with_state_is_running():
"""Test ExecutableWithState is_running property."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
assert not exe_state.is_running
future = Future()
exe_state.run(future)
assert exe_state.is_running
def test_executable_with_state_can_resume():
"""Test ExecutableWithState can_resume property."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
# Not suspended
assert not exe_state.can_resume
# Suspended indefinitely
exe_state.suspend()
assert exe_state.can_resume
# Suspended with timeout in future
future_time = time.time() + 10
exe_state.suspend_with_timeout(future_time)
assert not exe_state.can_resume
# Suspended with timeout in past
past_time = time.time() - 10
exe_state.suspend_with_timeout(past_time)
assert exe_state.can_resume
def test_executable_with_state_run():
"""Test ExecutableWithState run method."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
future = Future()
exe_state.run(future)
assert exe_state.status == BranchStatus.RUNNING
assert exe_state.future == future
def test_executable_with_state_run_invalid_state():
"""Test ExecutableWithState run method from invalid state."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
future1 = Future()
future2 = Future()
exe_state.run(future1)
with pytest.raises(InvalidStateError):
exe_state.run(future2)
def test_executable_with_state_suspend():
"""Test ExecutableWithState suspend method."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
exe_state.suspend()
assert exe_state.status == BranchStatus.SUSPENDED
assert exe_state.suspend_until is None
def test_executable_with_state_suspend_with_timeout():
"""Test ExecutableWithState suspend_with_timeout method."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
timestamp = time.time() + 5
exe_state.suspend_with_timeout(timestamp)
assert exe_state.status == BranchStatus.SUSPENDED_WITH_TIMEOUT
assert exe_state.suspend_until == timestamp
def test_executable_with_state_complete():
"""Test ExecutableWithState complete method."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
exe_state.complete("test_result")
assert exe_state.status == BranchStatus.COMPLETED
assert exe_state.result == "test_result"
def test_executable_with_state_fail():
"""Test ExecutableWithState fail method."""
executable = Executable(index=1, func=lambda: "test")
exe_state = ExecutableWithState(executable)
error = Exception("test error")
exe_state.fail(error)
assert exe_state.status == BranchStatus.FAILED
assert exe_state.error == error
def test_execution_counters_creation():
"""Test ExecutionCounters creation."""
counters = ExecutionCounters(
total_tasks=10,
min_successful=8,
tolerated_failure_count=2,
tolerated_failure_percentage=20.0,
)
assert counters.total_tasks == 10
assert counters.min_successful == 8
assert counters.tolerated_failure_count == 2
assert counters.tolerated_failure_percentage == 20.0
assert counters.success_count == 0
assert counters.failure_count == 0
def test_execution_counters_complete_task():
"""Test ExecutionCounters complete_task method."""
counters = ExecutionCounters(5, 3, None, None)
counters.complete_task()
assert counters.success_count == 1
def test_execution_counters_fail_task():
"""Test ExecutionCounters fail_task method."""
counters = ExecutionCounters(5, 3, None, None)
counters.fail_task()
assert counters.failure_count == 1
def test_execution_counters_should_complete_min_successful():
"""Test ExecutionCounters should_complete with min successful reached."""
counters = ExecutionCounters(5, 3, None, None)
assert not counters.should_complete()
counters.complete_task()
counters.complete_task()
counters.complete_task()
assert counters.should_complete()
def test_execution_counters_should_complete_failure_count():
"""Test ExecutionCounters should_complete with failure count exceeded."""
counters = ExecutionCounters(5, 3, 1, None)
assert not counters.should_complete()
counters.fail_task()
assert not counters.should_complete()
counters.fail_task()
assert counters.should_complete()
def test_execution_counters_should_complete_failure_percentage():
"""Test ExecutionCounters should_complete with failure percentage exceeded."""
counters = ExecutionCounters(10, 8, None, 15.0)
assert not counters.should_complete()
counters.fail_task()
assert not counters.should_complete()
counters.fail_task()
assert counters.should_complete() # 20% > 15%
def test_execution_counters_is_all_completed():
"""Test ExecutionCounters is_all_completed method."""
counters = ExecutionCounters(3, 2, None, None)
assert not counters.is_all_completed()
counters.complete_task()
counters.complete_task()
assert not counters.is_all_completed()
counters.complete_task()
assert counters.is_all_completed()
def test_execution_counters_is_min_successful_reached():
"""Test ExecutionCounters is_min_successful_reached method."""
counters = ExecutionCounters(5, 3, None, None)
assert not counters.is_min_successful_reached()
counters.complete_task()
counters.complete_task()
assert not counters.is_min_successful_reached()
counters.complete_task()
assert counters.is_min_successful_reached()
def test_execution_counters_is_failure_tolerance_exceeded():
"""Test ExecutionCounters is_failure_tolerance_exceeded method."""
counters = ExecutionCounters(10, 8, 2, None)
assert not counters.is_failure_tolerance_exceeded()
counters.fail_task()
counters.fail_task()
assert not counters.is_failure_tolerance_exceeded()
counters.fail_task()
assert counters.is_failure_tolerance_exceeded()
def test_execution_counters_zero_total_tasks():
"""Test ExecutionCounters with zero total tasks."""
counters = ExecutionCounters(0, 0, None, 50.0)
# Should not fail with division by zero
assert not counters.is_failure_tolerance_exceeded()
def test_execution_counters_failure_percentage_edge_case():
"""Test ExecutionCounters failure percentage at exact threshold."""
counters = ExecutionCounters(10, 5, None, 20.0)
# Exactly at threshold (20%)
counters.failure_count = 2
assert not counters.is_failure_tolerance_exceeded()
# Just over threshold
counters.failure_count = 3
assert counters.is_failure_tolerance_exceeded()
def test_execution_counters_thread_safety():
"""Test ExecutionCounters thread safety."""
counters = ExecutionCounters(100, 50, None, None)
def worker():
for _ in range(10):
counters.complete_task()
threads = [threading.Thread(target=worker) for _ in range(5)]
for t in threads:
t.start()
for t in threads:
t.join()
assert counters.success_count == 50
def test_batch_result_failed_with_none_error():
"""Test BatchResult failed method filters out None errors."""
items = [
BatchItem(0, BatchItemStatus.FAILED, error=None), # Should be filtered out
BatchItem(
1, BatchItemStatus.FAILED, error=ErrorObject("msg", "Error", None, None)
),
]
result = BatchResult(items, CompletionReason.ALL_COMPLETED)
failed = result.failed()
assert len(failed) == 1
assert failed[0].error is not None
def test_concurrent_executor_properties():
"""Test ConcurrentExecutor basic properties."""
class TestExecutor(ConcurrentExecutor):
def execute_item(self, child_context, executable):
return f"result_{executable.index}"
executables = [Executable(0, lambda: "test"), Executable(1, lambda: "test2")]
completion_config = CompletionConfig(
min_successful=1,
tolerated_failure_count=None,
tolerated_failure_percentage=None,
)
executor = TestExecutor(
executables=executables,
max_concurrency=2,
completion_config=completion_config,
sub_type_top="TOP",
sub_type_iteration="ITER",
name_prefix="test_",
serdes=None,
)
# Test basic properties
assert executor.executables == executables
assert executor.max_concurrency == 2
assert executor.completion_config == completion_config
assert executor.sub_type_top == "TOP"
assert executor.sub_type_iteration == "ITER"
assert executor.name_prefix == "test_"
def test_concurrent_executor_full_execution_path():
"""Test ConcurrentExecutor full execution."""
class TestExecutor(ConcurrentExecutor):
def execute_item(self, child_context, executable):
return f"result_{executable.index}"
executables = [Executable(0, lambda: "test"), Executable(1, lambda: "test2")]
completion_config = CompletionConfig(
min_successful=2,
tolerated_failure_count=None,
tolerated_failure_percentage=None,
)
executor = TestExecutor(
executables=executables,
max_concurrency=2,
completion_config=completion_config,
sub_type_top="TOP",
sub_type_iteration="ITER",
name_prefix="test_",
serdes=None,
)
execution_state = Mock()
execution_state.create_checkpoint = Mock()
# Mock ChildConfig from the config module
with patch(
"aws_durable_execution_sdk_python.config.ChildConfig"
) as mock_child_config:
mock_child_config.return_value = Mock()
def mock_run_in_child_context(func, name, config):
return func(Mock())
result = executor.execute(execution_state, mock_run_in_child_context)
assert len(result.all) >= 1
def test_timer_scheduler_double_check_resume_queue():
"""Test TimerScheduler double-check logic in scheduler loop."""
callback = Mock()
with TimerScheduler(callback) as scheduler:
exe_state1 = ExecutableWithState(Executable(0, lambda: "test"))
exe_state2 = ExecutableWithState(Executable(1, lambda: "test"))
# Schedule two tasks with different times to avoid comparison issues
past_time1 = time.time() - 2
past_time2 = time.time() - 1
scheduler.schedule_resume(exe_state1, past_time1)
scheduler.schedule_resume(exe_state2, past_time2)
# Give scheduler time to process
time.sleep(0.1)
# At least one callback should have been made
assert callback.call_count >= 0
def test_concurrent_executor_on_task_complete_timed_suspend():
"""Test ConcurrentExecutor _on_task_complete with TimedSuspendExecution."""
class TestExecutor(ConcurrentExecutor):
def execute_item(self, child_context, executable):
return f"result_{executable.index}"
executables = [Executable(0, lambda: "test")]
completion_config = CompletionConfig(
min_successful=1,
tolerated_failure_count=None,
tolerated_failure_percentage=None,
)
executor = TestExecutor(
executables=executables,
max_concurrency=1,
completion_config=completion_config,
sub_type_top="TOP",
sub_type_iteration="ITER",
name_prefix="test_",
serdes=None,
)
exe_state = ExecutableWithState(executables[0])
future = Mock()
future.result.side_effect = TimedSuspendExecution("test message", time.time() + 1)
future.cancelled.return_value = False
scheduler = Mock()
scheduler.schedule_resume = Mock()
executor._on_task_complete(exe_state, future, scheduler) # noqa: SLF001
assert exe_state.status == BranchStatus.SUSPENDED_WITH_TIMEOUT
scheduler.schedule_resume.assert_called_once()
def test_concurrent_executor_on_task_complete_suspend():
"""Test ConcurrentExecutor _on_task_complete with SuspendExecution."""
class TestExecutor(ConcurrentExecutor):
def execute_item(self, child_context, executable):
return f"result_{executable.index}"
executables = [Executable(0, lambda: "test")]
completion_config = CompletionConfig(
min_successful=1,
tolerated_failure_count=None,
tolerated_failure_percentage=None,
)
executor = TestExecutor(
executables=executables,
max_concurrency=1,