From 9719f6fda0c46bc6570220efc9bbdcd69494dad0 Mon Sep 17 00:00:00 2001 From: Ym <173550318+MaxonT@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:55:19 -0600 Subject: [PATCH 1/3] fix(sdk): settle recorded terminal items before a resumed batch completes Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com> --- .../concurrency/executor.py | 43 +++++++++++-- .../tests/concurrency_test.py | 63 +++++++++++++++++++ 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py index e62c3e1f9..abc16e433 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py @@ -45,7 +45,11 @@ OperationIdentifier, OperationIdNamespace, ) -from aws_durable_execution_sdk_python.lambda_service import ErrorObject, OperationType +from aws_durable_execution_sdk_python.lambda_service import ( + ErrorObject, + OperationStatus, + OperationType, +) from aws_durable_execution_sdk_python.operation.child import child_handler @@ -276,6 +280,13 @@ def execute( branch.index: branch for branch in self.branches } + # A resumed batch can hold child contexts that already recorded a + # terminal outcome. Their replays reach the coordinator in thread + # completion order, so the batch decides completion only after every + # one has settled, and starts no item past the last recorded one. + recorded_unsettled: set[int] = self._recorded_terminal_indexes(execution_state) + last_recorded: int = max(recorded_unsettled, default=-1) + in_flight: int = 0 running: int = 0 succeeded: int = 0 @@ -330,10 +341,13 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: ) decision = self.policy.evaluate(succeeded, failed, items_snapshot) needs_snapshot_rebuild = False - if self.policy.is_complete(succeeded, failed, items_snapshot, decision): - break - if not self.policy.should_continue(failed): - break + if not recorded_unsettled: + if self.policy.is_complete( + succeeded, failed, items_snapshot, decision + ): + break + if not self.policy.should_continue(failed): + break # Start branches in index order up to the in-flight limit. # Suspended branches keep their slot: in_flight only @@ -342,6 +356,7 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: pending and in_flight < max_in_flight and self.policy.should_continue(failed) + and (not recorded_unsettled or pending[0].index <= last_recorded) ): submit(pending.popleft()) in_flight += 1 @@ -394,12 +409,14 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: match event.kind: case BranchEventKind.COMPLETED: applied.complete(event.result) + recorded_unsettled.discard(event.index) succeeded += 1 running -= 1 in_flight -= 1 needs_snapshot_rebuild = True case BranchEventKind.FAILED if event.error is not None: applied.fail(event.error) + recorded_unsettled.discard(event.index) failed += 1 running -= 1 in_flight -= 1 @@ -496,6 +513,22 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: return self._create_result(completion_reason) + def _recorded_terminal_indexes(self, execution_state: ExecutionState) -> set[int]: + """Return the indexes whose NESTED child context is already terminal. + + FLAT branches never checkpoint themselves, so they have no record. + """ + if self.nesting_type is NestingType.FLAT: + return set() + return { + executable.index + for executable in self.executables + if execution_state.get_checkpoint_result( + self.operation_id_namespace.create_id_for_step(executable.index) + ).status + in (OperationStatus.SUCCEEDED, OperationStatus.FAILED) + } + def _create_result( self, completion_reason: CompletionReason | None = None ) -> BatchResult[ResultType]: diff --git a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py index 1aaae311c..09ac44fe4 100644 --- a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py @@ -5493,3 +5493,66 @@ def _execute_item_in_child_context( call.args[0].shutdown(wait=True) binding.reset(token) assert binding.get() == "empty" + + +def test_resumed_batch_settles_recorded_terminal_items_before_completing(): + """Recorded terminal items settle before the batch decides completion. + + Items 0 and 1 are recorded SUCCEEDED, item 2 FAILED and item 3 STARTED. The + recorded outcomes replay on worker threads in thread-completion order, so + item 2's recorded failure can arrive after the second success has already + met min_successful. The result must still carry the recorded failure, and + item 3 (not a terminal outcome) must not be started. + """ + recorded = { + "op_0": OperationStatus.SUCCEEDED, + "op_1": OperationStatus.SUCCEEDED, + "op_2": OperationStatus.FAILED, + "op_3": OperationStatus.STARTED, + } + started: list[int] = [] + + class RecordedExecutor(ConcurrentExecutor): + def _execute_item_in_child_context(self, executor_context, executable): + started.append(executable.index) + if executable.index == 2: + time.sleep(0.2) # replays its recorded failure after items 0, 1 + msg = "recorded failure" + raise ValueError(msg) + return f"result_{executable.index}" + + executor = RecordedExecutor( + executables=[Executable(i, lambda: None) for i in range(4)], + max_concurrency=2, + completion_config=CompletionConfig(min_successful=2), + sub_type_top="TOP", + sub_type_iteration="ITER", + name_prefix="test_", + serdes=None, + operation_id_namespace=_StubNamespace(), + ) + + execution_state = Mock() + execution_state.get_checkpoint_result.side_effect = lambda operation_id: ( + CheckpointedResult.create_from_operation( + Operation( + operation_id=operation_id, + operation_type=OperationType.CONTEXT, + status=recorded[operation_id], + ) + ) + ) + executor_context = Mock() + executor_context._parent_id = "batch" # noqa: SLF001 + + result = executor.execute(execution_state, executor_context) + + assert [item.status for item in result.all] == [ + BatchItemStatus.SUCCEEDED, + BatchItemStatus.SUCCEEDED, + BatchItemStatus.FAILED, + ] + assert result.success_count == 2 + assert result.failure_count == 1 + assert result.completion_reason is CompletionReason.MIN_SUCCESSFUL_REACHED + assert 3 not in started From 237016fc7503488bc154d55f37dc3133e7efac2b Mon Sep 17 00:00:00 2001 From: Ym <173550318+MaxonT@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:17:34 -0600 Subject: [PATCH 2/3] test(sdk): type and gate resumed-batch test Annotate the regression test and its executor override so mypy checks their bodies, and replace the fixed 200 ms delay with an event that releases the failing item only after the coordinator has applied both recorded successes. The test still fails on the base executor. --- .../tests/concurrency_test.py | 40 ++++++++++++++----- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py index 09ac44fe4..16741b94a 100644 --- a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py @@ -35,6 +35,7 @@ ChildConfig, CompletionConfig, CompletionDecision, + CompletionItemStatus, CompletionOutcome, CompletionStatus, complete_batch, @@ -5495,7 +5496,7 @@ def _execute_item_in_child_context( assert binding.get() == "empty" -def test_resumed_batch_settles_recorded_terminal_items_before_completing(): +def test_resumed_batch_settles_recorded_terminal_items_before_completing() -> None: """Recorded terminal items settle before the batch decides completion. Items 0 and 1 are recorded SUCCEEDED, item 2 FAILED and item 3 STARTED. The @@ -5504,25 +5505,43 @@ def test_resumed_batch_settles_recorded_terminal_items_before_completing(): met min_successful. The result must still carry the recorded failure, and item 3 (not a terminal outcome) must not be started. """ - recorded = { + recorded: dict[str, OperationStatus] = { "op_0": OperationStatus.SUCCEEDED, "op_1": OperationStatus.SUCCEEDED, "op_2": OperationStatus.FAILED, "op_3": OperationStatus.STARTED, } started: list[int] = [] - - class RecordedExecutor(ConcurrentExecutor): - def _execute_item_in_child_context(self, executor_context, executable): + # Item 2 fails only after the coordinator has applied both recorded + # successes, the point where the batch would complete without the fix. + both_successes_applied: threading.Event = threading.Event() + original_evaluate = CompletionPolicy.evaluate + + def evaluate_and_signal( + self: CompletionPolicy, + succeeded: int, + failed: int, + items: tuple[CompletionItemStatus, ...] = (), + ) -> CompletionDecision | None: + if succeeded >= 2: + both_successes_applied.set() + return original_evaluate(self, succeeded, failed, items) + + class RecordedExecutor(ConcurrentExecutor[Callable[[], str], str]): + def _execute_item_in_child_context( + self, + executor_context: DurableContext, + executable: Executable[Callable[[], str]], + ) -> str: started.append(executable.index) if executable.index == 2: - time.sleep(0.2) # replays its recorded failure after items 0, 1 + both_successes_applied.wait(timeout=5.0) msg = "recorded failure" raise ValueError(msg) return f"result_{executable.index}" executor = RecordedExecutor( - executables=[Executable(i, lambda: None) for i in range(4)], + executables=[Executable(i, lambda: "unused") for i in range(4)], max_concurrency=2, completion_config=CompletionConfig(min_successful=2), sub_type_top="TOP", @@ -5532,7 +5551,7 @@ def _execute_item_in_child_context(self, executor_context, executable): operation_id_namespace=_StubNamespace(), ) - execution_state = Mock() + execution_state: Mock = Mock() execution_state.get_checkpoint_result.side_effect = lambda operation_id: ( CheckpointedResult.create_from_operation( Operation( @@ -5542,10 +5561,11 @@ def _execute_item_in_child_context(self, executor_context, executable): ) ) ) - executor_context = Mock() + executor_context: Mock = Mock() executor_context._parent_id = "batch" # noqa: SLF001 - result = executor.execute(execution_state, executor_context) + with patch.object(CompletionPolicy, "evaluate", evaluate_and_signal): + result: BatchResult[str] = executor.execute(execution_state, executor_context) assert [item.status for item in result.all] == [ BatchItemStatus.SUCCEEDED, From 99090511a53a3ff47692fd7ebf330db468921b66 Mon Sep 17 00:00:00 2001 From: Ym <173550318+MaxonT@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:50:19 -0600 Subject: [PATCH 3/3] fix(sdk): reconcile stopped batch replays Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com> --- .../concurrency/executor.py | 19 ++- .../tests/concurrency_test.py | 125 ++++++++++++++++++ 2 files changed, 142 insertions(+), 2 deletions(-) diff --git a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py index abc16e433..35946ea41 100644 --- a/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py +++ b/packages/aws-durable-execution-sdk-python/src/aws_durable_execution_sdk_python/concurrency/executor.py @@ -332,6 +332,7 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: # once per state change and reused for both the completion check # and the reason, so user code runs at most once per change. decision: CompletionDecision | None = None + first_complete_decision: CompletionDecision | None = None while True: if needs_snapshot_rebuild: items_snapshot = ( @@ -339,8 +340,15 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: if self.policy.should_complete is not None else () ) - decision = self.policy.evaluate(succeeded, failed, items_snapshot) + if first_complete_decision is None: + decision = self.policy.evaluate( + succeeded, failed, items_snapshot + ) + if decision is not None and decision.complete: + first_complete_decision = decision needs_snapshot_rebuild = False + if first_complete_decision is not None: + decision = first_complete_decision if not recorded_unsettled: if self.policy.is_complete( succeeded, failed, items_snapshot, decision @@ -355,9 +363,16 @@ def submit(branch: Branch[CallableType, ResultType]) -> None: while ( pending and in_flight < max_in_flight - and self.policy.should_continue(failed) and (not recorded_unsettled or pending[0].index <= last_recorded) ): + if ( + not self.policy.should_continue(failed) + or self.policy.is_complete( + succeeded, failed, items_snapshot, decision + ) + ) and pending[0].index not in recorded_unsettled: + pending.popleft() + continue submit(pending.popleft()) in_flight += 1 running += 1 diff --git a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py index 16741b94a..7a92bf9e0 100644 --- a/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py +++ b/packages/aws-durable-execution-sdk-python/tests/concurrency_test.py @@ -5576,3 +5576,128 @@ def _execute_item_in_child_context( assert result.failure_count == 1 assert result.completion_reason is CompletionReason.MIN_SUCCESSFUL_REACHED assert 3 not in started + + +@pytest.mark.parametrize("tolerance", [None, 0]) +def test_replay_reconciles_recorded_outcomes_after_failure( + tolerance: int | None, +) -> None: + """A stop condition must not prevent replay of later terminal records.""" + statuses = [ + OperationStatus.FAILED, + OperationStatus.SUCCEEDED, + OperationStatus.SUCCEEDED, + OperationStatus.STARTED, + OperationStatus.SUCCEEDED, + ] + started: list[int] = [] + failure_applied = threading.Event() + original_evaluate = CompletionPolicy.evaluate + + def evaluate_and_signal( + self: CompletionPolicy, + succeeded: int, + failed: int, + items: tuple[CompletionItemStatus, ...] = (), + ) -> CompletionDecision | None: + if failed: + failure_applied.set() + return original_evaluate(self, succeeded, failed, items) + + class RecordedExecutor(ConcurrentExecutor[Callable[[], str], str]): + def _execute_item_in_child_context( + self, + executor_context: DurableContext, + executable: Executable[Callable[[], str]], + ) -> str: + started.append(executable.index) + if executable.index == 0: + raise ValueError("recorded failure") + if executable.index in (1, 2): + assert failure_applied.wait(timeout=5) + return "success" + + config = CompletionConfig(tolerated_failure_count=tolerance) + executor = RecordedExecutor( + executables=[Executable(i, lambda: "unused") for i in range(5)], + max_concurrency=3, + completion_config=config, + sub_type_top="TOP", + sub_type_iteration="ITER", + name_prefix="test_", + serdes=None, + operation_id_namespace=_StubNamespace(), + ) + execution_state = Mock() + execution_state.get_checkpoint_result.side_effect = lambda op: ( + CheckpointedResult.create_from_operation( + Operation( + operation_id=op, + operation_type=OperationType.CONTEXT, + status=statuses[int(op.split("_")[-1])], + ) + ) + ) + context = Mock() + context._parent_id = "batch" + with patch.object(CompletionPolicy, "evaluate", evaluate_and_signal): + result = executor.execute(execution_state, context) + assert sorted(started) == [0, 1, 2, 4] + assert [item.status for item in result.all] == [ + BatchItemStatus.FAILED, + BatchItemStatus.SUCCEEDED, + BatchItemStatus.SUCCEEDED, + BatchItemStatus.SUCCEEDED, + ] + assert result.completion_reason is CompletionReason.FAILURE_TOLERANCE_EXCEEDED + + +def test_replay_keeps_first_custom_completion_decision() -> None: + """Later replayed outcomes must not overwrite the original decision.""" + success_applied = threading.Event() + + def predicate(status: CompletionStatus) -> CompletionDecision: + if status.failure_count: + return complete_batch(CompletionOutcome.FAILED) + if status.success_count: + success_applied.set() + return complete_batch() + return continue_batch() + + class RecordedExecutor(ConcurrentExecutor[Callable[[], str], str]): + def _execute_item_in_child_context( + self, + executor_context: DurableContext, + executable: Executable[Callable[[], str]], + ) -> str: + if executable.index == 1: + assert success_applied.wait(timeout=5) + raise ValueError("recorded failure") + return "success" + + executor = RecordedExecutor( + executables=[Executable(i, lambda: "unused") for i in range(2)], + max_concurrency=2, + completion_config=CompletionConfig(should_complete=predicate), + sub_type_top="TOP", + sub_type_iteration="ITER", + name_prefix="test_", + serdes=None, + operation_id_namespace=_StubNamespace(), + ) + execution_state = Mock() + execution_state.get_checkpoint_result.side_effect = lambda op: ( + CheckpointedResult.create_from_operation( + Operation( + operation_id=op, + operation_type=OperationType.CONTEXT, + status=OperationStatus.SUCCEEDED + if op == "op_0" + else OperationStatus.FAILED, + ) + ) + ) + context = Mock() + context._parent_id = "batch" + result = executor.execute(execution_state, context) + assert result.completion_reason is CompletionReason.CUSTOM_COMPLETION_SUCCEEDED