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..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 @@ -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 @@ -321,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 = ( @@ -328,12 +340,22 @@ 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 self.policy.is_complete(succeeded, failed, items_snapshot, decision): - break - if not self.policy.should_continue(failed): - break + 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 + ): + 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 @@ -341,8 +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 @@ -394,12 +424,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 +528,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..7a92bf9e0 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, @@ -5493,3 +5494,210 @@ 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() -> 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 + 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: dict[str, OperationStatus] = { + "op_0": OperationStatus.SUCCEEDED, + "op_1": OperationStatus.SUCCEEDED, + "op_2": OperationStatus.FAILED, + "op_3": OperationStatus.STARTED, + } + started: list[int] = [] + # 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: + both_successes_applied.wait(timeout=5.0) + msg = "recorded failure" + raise ValueError(msg) + return f"result_{executable.index}" + + executor = RecordedExecutor( + executables=[Executable(i, lambda: "unused") 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 = 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 = Mock() + executor_context._parent_id = "batch" # noqa: SLF001 + + 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, + 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 + + +@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