-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathstate_test.py
More file actions
3343 lines (2703 loc) · 113 KB
/
state_test.py
File metadata and controls
3343 lines (2703 loc) · 113 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
"""Unit tests for execution state."""
from __future__ import annotations
import contextlib
import datetime
import json
import threading
import time
import unittest.mock
from concurrent.futures import ThreadPoolExecutor
from unittest.mock import Mock, call
import pytest
from aws_durable_execution_sdk_python.exceptions import (
BackgroundThreadError,
CallableRuntimeError,
OrphanedChildException,
)
from aws_durable_execution_sdk_python.identifier import OperationIdentifier
from aws_durable_execution_sdk_python.lambda_service import (
CallbackDetails,
ChainedInvokeDetails,
CheckpointOutput,
CheckpointUpdatedExecutionState,
ContextDetails,
ErrorObject,
LambdaClient,
Operation,
OperationAction,
OperationStatus,
OperationType,
OperationUpdate,
StateOutput,
StepDetails,
)
from aws_durable_execution_sdk_python.state import (
CheckpointBatcherConfig,
CheckpointedResult,
ExecutionState,
QueuedOperation,
ReplayStatus,
)
from aws_durable_execution_sdk_python.threading import CompletionEvent
def test_checkpointed_result_create_from_operation_step():
"""Test CheckpointedResult.create_from_operation with STEP operation."""
step_details = StepDetails(result="test_result")
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.SUCCEEDED,
step_details=step_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.SUCCEEDED
assert result.result == "test_result"
assert result.error is None
def test_checkpointed_result_create_from_operation_callback():
"""Test CheckpointedResult.create_from_operation with CALLBACK operation."""
callback_details = CallbackDetails(callback_id="cb1", result="callback_result")
operation = Operation(
operation_id="op1",
operation_type=OperationType.CALLBACK,
status=OperationStatus.SUCCEEDED,
callback_details=callback_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.SUCCEEDED
assert result.result == "callback_result"
assert result.error is None
def test_checkpointed_result_create_from_operation_invoke():
"""Test CheckpointedResult.create_from_operation with INVOKE operation."""
chained_invoke_details = ChainedInvokeDetails(result="invoke_result")
operation = Operation(
operation_id="op1",
operation_type=OperationType.CHAINED_INVOKE,
status=OperationStatus.SUCCEEDED,
chained_invoke_details=chained_invoke_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.SUCCEEDED
assert result.result == "invoke_result"
assert result.error is None
def test_checkpointed_result_create_from_operation_invoke_with_error():
"""Test CheckpointedResult.create_from_operation with INVOKE operation and error."""
error = ErrorObject(
message="Invoke error", type="InvokeError", data=None, stack_trace=None
)
chained_invoke_details = ChainedInvokeDetails(error=error)
operation = Operation(
operation_id="op1",
operation_type=OperationType.CHAINED_INVOKE,
status=OperationStatus.FAILED,
chained_invoke_details=chained_invoke_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.FAILED
assert result.result is None
assert result.error == error
def test_checkpointed_result_create_from_operation_invoke_no_details():
"""Test CheckpointedResult.create_from_operation with INVOKE operation but no chained_invoke_details."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.CHAINED_INVOKE,
status=OperationStatus.STARTED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.STARTED
assert result.result is None
assert result.error is None
def test_checkpointed_result_create_from_operation_invoke_with_both_result_and_error():
"""Test CheckpointedResult.create_from_operation with INVOKE operation having both result and error."""
error = ErrorObject(
message="Invoke error", type="InvokeError", data=None, stack_trace=None
)
chained_invoke_details = ChainedInvokeDetails(result="invoke_result", error=error)
operation = Operation(
operation_id="op1",
operation_type=OperationType.CHAINED_INVOKE,
status=OperationStatus.FAILED,
chained_invoke_details=chained_invoke_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.FAILED
assert result.result == "invoke_result"
assert result.error == error
def test_checkpointed_result_create_from_operation_context():
"""Test CheckpointedResult.create_from_operation with CONTEXT operation."""
context_details = ContextDetails(result="context_result")
operation = Operation(
operation_id="op1",
operation_type=OperationType.CONTEXT,
status=OperationStatus.SUCCEEDED,
context_details=context_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.SUCCEEDED
assert result.result == "context_result"
assert result.error is None
def test_checkpointed_result_create_from_operation_context_with_error():
"""Test CheckpointedResult.create_from_operation with CONTEXT operation and error."""
error = ErrorObject(
message="Context error", type="ContextError", data=None, stack_trace=None
)
context_details = ContextDetails(error=error)
operation = Operation(
operation_id="op1",
operation_type=OperationType.CONTEXT,
status=OperationStatus.FAILED,
context_details=context_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.FAILED
assert result.result is None
assert result.error == error
def test_checkpointed_result_create_from_operation_context_no_details():
"""Test CheckpointedResult.create_from_operation with CONTEXT operation but no context_details."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.CONTEXT,
status=OperationStatus.STARTED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.STARTED
assert result.result is None
assert result.error is None
def test_checkpointed_result_create_from_operation_context_with_both_result_and_error():
"""Test CheckpointedResult.create_from_operation with CONTEXT operation having both result and error."""
error = ErrorObject(
message="Context error", type="ContextError", data=None, stack_trace=None
)
context_details = ContextDetails(result="context_result", error=error)
operation = Operation(
operation_id="op1",
operation_type=OperationType.CONTEXT,
status=OperationStatus.FAILED,
context_details=context_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.FAILED
assert result.result == "context_result"
assert result.error == error
def test_checkpointed_result_create_from_operation_unknown_type():
"""Test CheckpointedResult.create_from_operation with unknown operation type."""
# Create operation with a mock operation type that doesn't match any case
operation = Operation(
operation_id="op1",
operation_type="UNKNOWN_TYPE", # This will not match any case
status=OperationStatus.STARTED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.STARTED
assert result.result is None
assert result.error is None
def test_checkpointed_result_create_from_operation_with_error():
"""Test CheckpointedResult.create_from_operation with error."""
error = ErrorObject(
message="Test error", type="TestError", data=None, stack_trace=None
)
step_details = StepDetails(error=error)
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.FAILED,
step_details=step_details,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.FAILED
assert result.result is None
assert result.error == error
def test_checkpointed_result_create_from_operation_no_details():
"""Test CheckpointedResult.create_from_operation with no details."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.operation == operation
assert result.status == OperationStatus.STARTED
assert result.result is None
assert result.error is None
def test_checkpointed_result_create_not_found():
"""Test CheckpointedResult.create_not_found class method."""
result = CheckpointedResult.create_not_found()
assert result.operation is None
assert result.status is None
assert result.result is None
assert result.error is None
def test_checkpointed_result_is_succeeded():
"""Test CheckpointedResult.is_succeeded method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.SUCCEEDED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_succeeded() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_succeeded() is False
def test_checkpointed_result_is_failed():
"""Test CheckpointedResult.is_failed method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.FAILED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_failed() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_failed() is False
def test_checkpointed_result_is_cancelled():
"""Test CheckpointedResult.is_cancelled method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.CANCELLED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_cancelled() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_cancelled() is False
def test_checkpointerd_result_is_pending():
"""Test CheckpointedResult.is_pending method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.PENDING,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_pending() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_pending() is False
def test_checkpointed_result_is_started():
"""Test CheckpointedResult.is_started method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_started() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_started() is False
def test_checkpointed_result_raise_callable_error():
"""Test CheckpointedResult.raise_callable_error method."""
error = Mock(spec=ErrorObject)
error.to_callable_runtime_error.return_value = RuntimeError("Test error")
result = CheckpointedResult(error=error)
with pytest.raises(RuntimeError, match="Test error"):
result.raise_callable_error()
error.to_callable_runtime_error.assert_called_once()
def test_checkpointed_result_raise_callable_error_no_error():
"""Test CheckpointedResult.raise_callable_error with no error."""
result = CheckpointedResult()
with pytest.raises(CallableRuntimeError, match="Unknown error"):
result.raise_callable_error()
def test_checkpointed_result_raise_callable_error_no_error_with_message():
"""Test CheckpointedResult.raise_callable_error with no error and custom message."""
result = CheckpointedResult()
with pytest.raises(CallableRuntimeError, match="Custom error message"):
result.raise_callable_error("Custom error message")
def test_checkpointed_result_immutable():
"""Test that CheckpointedResult is immutable."""
result = CheckpointedResult(status=OperationStatus.SUCCEEDED)
with pytest.raises(AttributeError):
result.status = OperationStatus.FAILED
def test_execution_state_creation():
"""Test ExecutionState creation."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="test_token", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
assert state.durable_execution_arn == "test_arn"
assert state.operations == {}
def test_get_checkpoint_result_success_with_result():
"""Test get_checkpoint_result with successful operation and result."""
mock_lambda_client = Mock(spec=LambdaClient)
step_details = StepDetails(result="test_result")
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.SUCCEEDED,
step_details=step_details,
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={"op1": operation},
service_client=mock_lambda_client,
)
result = state.get_checkpoint_result("op1")
assert result.is_succeeded() is True
assert result.result == "test_result"
assert result.operation == operation
def test_get_checkpoint_result_success_without_step_details():
"""Test get_checkpoint_result with successful operation but no step details."""
mock_lambda_client = Mock(spec=LambdaClient)
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.SUCCEEDED,
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={"op1": operation},
service_client=mock_lambda_client,
)
result = state.get_checkpoint_result("op1")
assert result.is_succeeded() is True
assert result.result is None
assert result.operation == operation
def test_get_checkpoint_result_operation_not_succeeded():
"""Test get_checkpoint_result with failed operation."""
mock_lambda_client = Mock(spec=LambdaClient)
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.FAILED,
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={"op1": operation},
service_client=mock_lambda_client,
)
result = state.get_checkpoint_result("op1")
assert result.is_failed() is True
assert result.result is None
assert result.operation == operation
def test_get_checkpoint_result_operation_not_found():
"""Test get_checkpoint_result with nonexistent operation."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
result = state.get_checkpoint_result("nonexistent")
assert result.is_succeeded() is False
assert result.result is None
assert result.operation is None
def test_create_checkpoint():
"""Test create_checkpoint method enqueues operations asynchronously."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
operation_update = OperationUpdate(
operation_id="test_op",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
# create_checkpoint with is_sync=False just enqueues without blocking
state.create_checkpoint(operation_update, is_sync=False)
# Verify the operation was enqueued (not immediately processed)
assert not mock_lambda_client.checkpoint.called
assert state._checkpoint_queue.qsize() == 1
# Verify we can retrieve the queued operation
queued_op = state._checkpoint_queue.get_nowait()
assert queued_op.operation_update == operation_update
assert queued_op.completion_event is None # Async operation has no completion event
def test_create_checkpoint_with_none():
"""Test create_checkpoint method with None operation_update (empty checkpoint)."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
# create_checkpoint with None and is_sync=False enqueues an empty checkpoint
state.create_checkpoint(None, is_sync=False)
# Verify the operation was enqueued (not immediately processed)
assert not mock_lambda_client.checkpoint.called
assert state._checkpoint_queue.qsize() == 1
# Verify we can retrieve the queued operation
queued_op = state._checkpoint_queue.get_nowait()
assert queued_op.operation_update is None # Empty checkpoint
assert queued_op.completion_event is None # Async operation
def test_create_checkpoint_with_no_args():
"""Test create_checkpoint method with no arguments (default None)."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
# create_checkpoint with no args and is_sync=False enqueues an empty checkpoint
state.create_checkpoint(is_sync=False)
# Verify the operation was enqueued (not immediately processed)
assert not mock_lambda_client.checkpoint.called
assert state._checkpoint_queue.qsize() == 1
# Verify we can retrieve the queued operation
queued_op = state._checkpoint_queue.get_nowait()
assert queued_op.operation_update is None # Empty checkpoint (default)
assert queued_op.completion_event is None # Async operation
def test_get_checkpoint_result_started():
"""Test get_checkpoint_result with started operation."""
mock_lambda_client = Mock(spec=LambdaClient)
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={"op1": operation},
service_client=mock_lambda_client,
)
result = state.get_checkpoint_result("op1")
assert result.is_started() is True
assert result.is_succeeded() is False
assert result.is_failed() is False
assert result.operation == operation
def test_checkpointed_result_is_timed_out():
"""Test CheckpointedResult.is_timed_out method."""
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=OperationStatus.TIMED_OUT,
)
result = CheckpointedResult.create_from_operation(operation)
assert result.is_timed_out() is True
# Test with no operation
result_no_op = CheckpointedResult.create_not_found()
assert result_no_op.is_timed_out() is False
def test_checkpointed_result_is_timed_out_false_for_other_statuses():
"""Test CheckpointedResult.is_timed_out returns False for non-timed-out statuses."""
statuses = [
OperationStatus.STARTED,
OperationStatus.SUCCEEDED,
OperationStatus.FAILED,
OperationStatus.CANCELLED,
OperationStatus.PENDING,
OperationStatus.READY,
OperationStatus.STOPPED,
]
for status in statuses:
operation = Operation(
operation_id="op1",
operation_type=OperationType.STEP,
status=status,
)
result = CheckpointedResult.create_from_operation(operation)
assert (
result.is_timed_out() is False
), f"is_timed_out should be False for status {status}"
def test_fetch_paginated_operations_with_marker():
mock_lambda_client = Mock(spec=LambdaClient)
def mock_get_execution_state(durable_execution_arn, checkpoint_token, next_marker):
resp = {
"marker1": StateOutput(
operations=[
Operation(
operation_id="1",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
],
next_marker="marker2",
),
"marker2": StateOutput(
operations=[
Operation(
operation_id="2",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
],
next_marker="marker3",
),
"marker3": StateOutput(
operations=[
Operation(
operation_id="3",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
],
next_marker=None,
),
}
return resp.get(next_marker)
mock_lambda_client.get_execution_state.side_effect = mock_get_execution_state
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
state.fetch_paginated_operations(
initial_operations=[
Operation(
operation_id="0",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
)
],
checkpoint_token="test_token", # noqa: S106
next_marker="marker1",
)
assert mock_lambda_client.get_execution_state.call_count == 3
mock_lambda_client.get_execution_state.assert_has_calls(
[
call(
durable_execution_arn="test_arn",
checkpoint_token="test_token", # noqa: S106
next_marker="marker1",
),
call(
durable_execution_arn="test_arn",
checkpoint_token="test_token", # noqa: S106
next_marker="marker2",
),
call(
durable_execution_arn="test_arn",
checkpoint_token="test_token", # noqa: S106
next_marker="marker3",
),
]
)
expected_operations = {
"0": Operation(
operation_id="0",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
),
"1": Operation(
operation_id="1",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
),
"2": Operation(
operation_id="2",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
),
"3": Operation(
operation_id="3",
operation_type=OperationType.STEP,
status=OperationStatus.STARTED,
),
}
assert len(state.operations) == len(expected_operations)
for op_id, operation in state.operations.items():
assert op_id in expected_operations
expected_op = expected_operations[op_id]
assert operation.operation_id == expected_op.operation_id
# ============================================================================
# Checkpoint Batching Tests
# ============================================================================
# Note: These tests access private members (_checkpoint_queue, _overflow_queue,
# _parent_to_children, etc.) to test internal batching logic. This is justified
# for unit testing the core batching functionality that cannot be tested through
# public APIs alone.
# ruff: noqa: SLF001, BLE001
# Test 8.1: QueuedOperation wrapper and CheckpointBatcherConfig
def test_queued_operation_creation_with_completion_event():
"""Test QueuedOperation creation with completion event for synchronous operations."""
operation_update = OperationUpdate(
operation_id="test_op",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
completion_event = CompletionEvent()
queued_op = QueuedOperation(operation_update, completion_event)
assert queued_op.operation_update == operation_update
assert queued_op.completion_event == completion_event
assert not completion_event.is_set()
def test_queued_operation_creation_without_completion_event():
"""Test QueuedOperation creation without completion event for async operations."""
operation_update = OperationUpdate(
operation_id="test_op",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
queued_op = QueuedOperation(operation_update, completion_event=None)
assert queued_op.operation_update == operation_update
assert queued_op.completion_event is None
def test_queued_operation_with_none_operation_update():
"""Test QueuedOperation with None operation_update for empty checkpoints."""
queued_op = QueuedOperation(operation_update=None, completion_event=None)
assert queued_op.operation_update is None
assert queued_op.completion_event is None
def test_checkpoint_batcher_config_default_values():
"""Test CheckpointBatcherConfig default values."""
config = CheckpointBatcherConfig()
assert config.max_batch_size_bytes == 750 * 1024 # 750KB
assert config.max_batch_time_seconds == 1.0
assert config.max_batch_operations == 250
def test_checkpoint_batcher_config_custom_values():
"""Test CheckpointBatcherConfig with custom values."""
config = CheckpointBatcherConfig(
max_batch_size_bytes=500 * 1024,
max_batch_time_seconds=0.5,
max_batch_operations=10,
)
assert config.max_batch_size_bytes == 500 * 1024
assert config.max_batch_time_seconds == 0.5
assert config.max_batch_operations == 10
def test_checkpoint_batcher_config_immutable():
"""Test that CheckpointBatcherConfig is immutable."""
config = CheckpointBatcherConfig()
with pytest.raises(AttributeError):
config.max_batch_size_bytes = 1000
def test_checkpoint_batch_respects_default_max_items_limit():
"""Test that batch collection respects the default MAX_ITEMS_IN_BATCH (250) limit.
This ensures consistency across all Durable Execution SDK implementations.
"""
mock_lambda_client = Mock(spec=LambdaClient)
# Use default config (max_batch_operations=250)
config = CheckpointBatcherConfig(
max_batch_size_bytes=10 * 1024 * 1024,
max_batch_time_seconds=10.0,
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
batcher_config=config,
)
# Enqueue 300 small operations (exceeds MAX_ITEMS_IN_BATCH of 250)
for i in range(300):
operation_update = OperationUpdate(
operation_id=f"op_{i}",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
state._checkpoint_queue.put(QueuedOperation(operation_update, None))
# Collect first batch
batch1 = state._collect_checkpoint_batch()
# First batch should have exactly 250 items
assert len(batch1) == 250
# Collect second batch
batch2 = state._collect_checkpoint_batch()
# Second batch should have remaining 50 items
assert len(batch2) == 50
def test_calculate_operation_size_with_operation():
"""Test _calculate_operation_size with a real operation."""
operation_update = OperationUpdate(
operation_id="test_op_123",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
queued_op = QueuedOperation(operation_update, completion_event=None)
size = ExecutionState._calculate_operation_size(queued_op)
# Verify size is positive and reasonable
assert size > 0
# Verify it matches JSON serialization size
expected_size = len(json.dumps(operation_update.to_dict()).encode("utf-8"))
assert size == expected_size
def test_calculate_operation_size_with_none():
"""Test _calculate_operation_size with None operation_update (empty checkpoint)."""
queued_op = QueuedOperation(operation_update=None, completion_event=None)
size = ExecutionState._calculate_operation_size(queued_op)
assert size == 0
# Test 8.2: Batching logic and size limits
def test_collect_checkpoint_batch_respects_size_limit():
"""Test that batch collection respects max_batch_size_bytes limit."""
mock_lambda_client = Mock(spec=LambdaClient)
# Create config with small size limit
config = CheckpointBatcherConfig(
max_batch_size_bytes=200, # Small limit to trigger overflow
max_batch_time_seconds=10.0, # Long time to avoid time-based flush
)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
batcher_config=config,
)
# Enqueue multiple operations
for i in range(5):
operation_update = OperationUpdate(
operation_id=f"op_{i}",
operation_type=OperationType.STEP,
action=OperationAction.START,
)
state._checkpoint_queue.put(QueuedOperation(operation_update, None))
# Collect batch
batch = state._collect_checkpoint_batch()
# Verify batch size is limited
assert len(batch) < 5 # Should not include all operations
assert len(batch) > 0 # Should include at least one
# Verify total size doesn't exceed limit
total_size = sum(state._calculate_operation_size(op) for op in batch)
assert total_size <= config.max_batch_size_bytes
def test_collect_checkpoint_batch_uses_overflow_queue():
"""Test that overflow queue is processed first to maintain FIFO order."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
# Put operations in overflow queue
overflow_op1 = QueuedOperation(
OperationUpdate(
operation_id="overflow_1",
operation_type=OperationType.STEP,
action=OperationAction.START,
),
None,
)
overflow_op2 = QueuedOperation(
OperationUpdate(
operation_id="overflow_2",
operation_type=OperationType.STEP,
action=OperationAction.START,
),
None,
)
state._overflow_queue.put(overflow_op1)
state._overflow_queue.put(overflow_op2)
# Put operation in main queue
main_op = QueuedOperation(
OperationUpdate(
operation_id="main_1",
operation_type=OperationType.STEP,
action=OperationAction.START,
),
None,
)
state._checkpoint_queue.put(main_op)
# Collect batch
batch = state._collect_checkpoint_batch()
# Verify overflow operations come first
assert len(batch) >= 2
assert batch[0].operation_update.operation_id == "overflow_1"
assert batch[1].operation_update.operation_id == "overflow_2"
def test_collect_checkpoint_batch_handles_empty_checkpoint():
"""Test batch collection with empty checkpoints (None operation_update)."""
mock_lambda_client = Mock(spec=LambdaClient)
state = ExecutionState(
durable_execution_arn="test_arn",
initial_checkpoint_token="token123", # noqa: S106
operations={},
service_client=mock_lambda_client,
)
# Enqueue empty checkpoint
state._checkpoint_queue.put(QueuedOperation(None, None))
# Enqueue regular checkpoint
state._checkpoint_queue.put(
QueuedOperation(
OperationUpdate(
operation_id="op_1",
operation_type=OperationType.STEP,
action=OperationAction.START,
),
None,
)
)
# Collect batch
batch = state._collect_checkpoint_batch()
# Verify both operations are in batch
assert len(batch) == 2
assert batch[0].operation_update is None # Empty checkpoint
assert batch[1].operation_update is not None