diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index ec2192574..47d9ef562 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -34,6 +34,8 @@ class _WorkflowLogicFlag(IntEnum): # Apply all activation jobs before running workflow tasks, as flag 2 does. # Send cancellation only to the task that receives it. Flag 2 checks for # cancellation across the workflow, so it also cancels shielded waits. + # When a child workflow or Nexus operation start resolves with the + # cancellation, send a cancel request to it. Flag 2 sends none. # Added on 2026-11-30. # Not enabled by default. APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 5ab8c5ace..cfbe2b2ad 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -510,22 +510,20 @@ def _activate( self._is_replaying = act.is_replaying self._current_thread_id = threading.get_ident() self._current_internal_flags = act.available_internal_flags - self._legacy_single_batch = self._workflow_logic_flag_enabled( + self._single_batch_flag = self._workflow_logic_flag_enabled( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) # Histories that use the original single-batch flag must keep its # workflow-wide cancellation check, so do not check the newer flag. - self._preserve_task_cancellation = ( - not self._legacy_single_batch + self._apply_jobs_first_flag = ( + not self._single_batch_flag and self._workflow_logic_flag_enabled( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) ) # Both flags apply all jobs before running tasks. They differ only in # how they send cancellation. - single_batch_activation = ( - self._legacy_single_batch or self._preserve_task_cancellation - ) + single_batch_activation = self._single_batch_flag or self._apply_jobs_first_flag # Check this flag before queries can arrive, # even when no input needs decoding. self._workflow_logic_flag_enabled(_WorkflowLogicFlag.DECODE_DATETIME_PROXIES) @@ -726,7 +724,7 @@ def _apply_cancel_workflow( # workflow the ability to receive the cancellation, so we must defer # this cancellation to the next iteration of the event loop. self.call_soon(self._primary_task.cancel) - elif self._legacy_single_batch or self._preserve_task_cancellation: + elif self._single_batch_flag or self._apply_jobs_first_flag: # Initialization is the only job that creates the primary task, so # retain a same-activation cancellation until that task exists. self._cancel_primary_task_pending = True @@ -2054,7 +2052,7 @@ async def workflow_wait_condition( # cancellation and keep going. def cancellation_arrived() -> bool: return ( - self._legacy_single_batch + self._single_batch_flag and not cancellation_requested_before and self._cancel_reason is not None ) @@ -2076,7 +2074,7 @@ def cancellation_arrived() -> bool: _TimerOptions(user_metadata=user_metadata, event_group_markers=markers) ) try: - if self._preserve_task_cancellation: + if self._apply_jobs_first_flag: # A direct await lets the waiting task arbitrate cancellation # and readiness without bypassing shielding or using wait_for. async with asyncio.timeout(timeout): @@ -2266,6 +2264,11 @@ async def _outbound_start_child_workflow( def apply_child_cancel_error( err: asyncio.CancelledError, ) -> None: + if self._apply_jobs_first_flag and handle._result_fut.done(): + # Core fails the task on a cancel for a terminated child, and a + # child with a result needs no cancel. Without flag 4, keep the + # old commands. + return cancel_command = self._add_command() # Send a cancel request to the child, forwarding the msg passed to # Task.cancel(msg) (if any) as the cancellation reason. @@ -2303,7 +2306,7 @@ async def run_child() -> Any: await self._await_temporal_operation( handle._start_fut, apply_child_cancel_error, - reraise_on_workflow_cancellation=True, + is_start=True, ) return handle @@ -2380,7 +2383,7 @@ async def operation_handle_fn() -> OutputT: await self._await_temporal_operation( handle._start_fut, lambda _err: handle._apply_cancel_command(self._add_command()), - reraise_on_workflow_cancellation=True, + is_start=True, ) return handle @@ -2432,7 +2435,7 @@ async def _await_temporal_operation( ], *, completed_cancellation_flag: _WorkflowLogicFlag | None = None, - reraise_on_workflow_cancellation: bool = False, + is_start: bool = False, ) -> _T: while True: try: @@ -2441,19 +2444,16 @@ async def _await_temporal_operation( # custom shield also avoids spurious error logs on Python 3.11+. return await _shield_await(fut) except asyncio.CancelledError as err: - if fut.done(): - # Retrying the shield after both futures become ready would - # return the result and erase the task cancellation. - if self._legacy_single_batch or self._preserve_task_cancellation: - raise - if completed_cancellation_flag is not None and ( - not self._is_replaying - or completed_cancellation_flag in self._current_internal_flags - ): - self._current_completion.successful.used_internal_flags.append( - completed_cancellation_flag - ) - raise + # Retrying the shield after both futures become ready would + # return the result and erase the task cancellation. + if fut.done() and self._cancellation_wins_over_result( + completed_cancellation_flag + ): + if is_start and self._apply_jobs_first_flag: + # A start that raises gives the caller no handle, so + # the caller cannot cancel the operation itself. + apply_cancel(err) + raise apply_cancel(err) @@ -2462,9 +2462,7 @@ async def _await_temporal_operation( if (task := asyncio.current_task()) is not None: task.uncancel() - if reraise_on_workflow_cancellation and ( - self._cancel_reason is not None or self._deleting - ): + if is_start and (self._cancel_reason is not None or self._deleting): raise async def _cancel_external_workflow( @@ -2483,6 +2481,33 @@ async def _cancel_external_workflow( # Wait until done (there is no cancelling a cancel request) await done_fut + def _cancellation_wins_over_result( + self, completed_cancellation_flag: _WorkflowLogicFlag | None + ) -> bool: + """Decide whether a task cancellation wins over a result that is ready. + + The caller uses this when its task is cancelled after the operation + result is already available. True means the caller must raise the + cancellation. False means the caller sends the cancel request and can + still return the result, which is the legacy behavior. + + Flag 2 and flag 4 always give the cancellation priority. Otherwise, + ``completed_cancellation_flag`` (flag 1 for activities) gives it + priority. On a new workflow task this call records that flag. On replay + the flag applies only if history holds it. + """ + if self._single_batch_flag or self._apply_jobs_first_flag: + return True + if completed_cancellation_flag is None or ( + self._is_replaying + and completed_cancellation_flag not in self._current_internal_flags + ): + return False + self._current_completion.successful.used_internal_flags.append( + completed_cancellation_flag + ) + return True + def _check_condition(self, fn: Callable[[], bool], fut: asyncio.Future) -> bool: if fn(): fut.set_result(True) diff --git a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py new file mode 100644 index 000000000..57aefc195 --- /dev/null +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -0,0 +1,134 @@ +import uuid + +import nexusrpc.handler +import pytest + +from temporalio import nexus, workflow +from temporalio._workflow_context import _WorkflowLogicFlag +from temporalio.api.enums.v1 import EventType +from temporalio.client import WorkflowFailureError +from temporalio.exceptions import CancelledError +from temporalio.testing import WorkflowEnvironment +from temporalio.worker import Replayer, Worker +from tests.helpers import assert_event_subsequence, new_worker +from tests.helpers.nexus import make_nexus_endpoint_name +from tests.worker.test_workflow import CustomWorkflowRunner, WaitForCancelWorkflow + +# Cloud CI's namespace credentials cannot manage Nexus endpoints. +# See https://github.com/temporalio/sdk-python/issues/1704. +pytestmark = pytest.mark.requires_local_server + + +@nexusrpc.handler.service_handler +class WaitForCancelService: + @nexus.workflow_run_operation + async def wait_for_cancel( + self, ctx: nexus.WorkflowRunOperationContext, workflow_id: str + ) -> nexus.WorkflowHandle[None]: + return await ctx.start_workflow(WaitForCancelWorkflow.run, id=workflow_id) + + +@workflow.defn +class CancelAtOperationStartWorkflow: + @workflow.run + async def run(self, endpoint: str) -> None: + nexus_client = workflow.create_nexus_client( + service=WaitForCancelService, endpoint=endpoint + ) + await nexus_client.start_operation( + WaitForCancelService.wait_for_cancel, + f"{workflow.info().workflow_id}-operation", + ) + + +@pytest.mark.parametrize( + ("flag", "operation_cancel_requested"), + [ + pytest.param(None, True, id="no-flag"), + pytest.param( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH, + False, + id="original-single-batch", + ), + pytest.param( + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS, + True, + id="batching-with-task-cancellation", + ), + ], +) +async def test_workflow_cancel_and_operation_start_in_same_activation( + env: WorkflowEnvironment, + flag: _WorkflowLogicFlag | None, + operation_cancel_requested: bool, +) -> None: + if env.supports_time_skipping_v1: + pytest.skip("Nexus tests don't work with time-skipping server") + + caller_task_queue = str(uuid.uuid4()) + handler_task_queue = str(uuid.uuid4()) + endpoint = make_nexus_endpoint_name(handler_task_queue) + await env.create_nexus_endpoint(endpoint, handler_task_queue) + runner = CustomWorkflowRunner() + + def caller_worker() -> Worker: + worker = new_worker( + env.client, + CancelAtOperationStartWorkflow, + task_queue=caller_task_queue, + workflow_runner=runner, + # Keep tasks on the normal queue, which the next worker polls. + max_cached_workflows=0, + ) + if flag is not None: + worker._set_default_workflow_logic_flag(flag, enabled=True) + return worker + + handle = await env.client.start_workflow( + CancelAtOperationStartWorkflow.run, + endpoint, + id=f"workflow-{uuid.uuid4()}", + task_queue=caller_task_queue, + ) + async with caller_worker(): + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED] + ) + + # The operation starts only after the caller worker stops, so the start + # and the cancellation reach the caller in one activation. + async with new_worker( + env.client, + WaitForCancelWorkflow, + task_queue=handler_task_queue, + nexus_service_handlers=[WaitForCancelService()], + ): + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED] + ) + await handle.cancel() + async with caller_worker(): + with pytest.raises(WorkflowFailureError) as err: + await handle.result() + assert isinstance(err.value.cause, CancelledError) + + if flag is not None: + assert any( + flag in completion.successful.used_internal_flags + for _, completion in runner._pairs + ) + assert any( + {"resolve_nexus_operation_start", "cancel_workflow"}.issubset( + {job.WhichOneof("variant") for job in activation.jobs} + ) + for activation, _ in runner._pairs + ) + history = await handle.fetch_history() + assert ( + any( + event.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_CANCEL_REQUESTED + for event in history.events + ) + is operation_cancel_requested + ) + await Replayer(workflows=[CancelAtOperationStartWorkflow]).replay_workflow(history) diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 66007ed77..b58ca2df2 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -134,6 +134,7 @@ LogHandler, admitted_update_task, assert_eq_eventually, + assert_event_subsequence, assert_eventually, assert_pending_activity_exists_eventually, assert_task_fail_eventually, @@ -1998,6 +1999,109 @@ async def child_completion_recorded() -> None: ) +@workflow.defn +class CancelAtChildStartWorkflow: + @workflow.run + async def run(self, child_task_queue: str) -> None: + await workflow.start_child_workflow( + CompleteChildOnSignalWorkflow.run, + id=f"{workflow.info().workflow_id}-child", + task_queue=child_task_queue, + ) + # The child starts before the test can cancel. Failed tasks complete + # nothing, so the next activation also gets the later jobs, and there + # the start raises instead. + raise RuntimeError("Intentional task failure") + + +@pytest.mark.parametrize( + ("flag", "terminate_child", "child_cancel_requested"), + [ + pytest.param(None, False, True, id="no-flag"), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, + False, + False, + id="original-single-batch", + ), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + False, + True, + id="batching-with-task-cancellation", + ), + # Core fails the task on a cancel for a terminated child + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + True, + False, + id="batching-with-task-cancellation-child-terminated", + ), + ], +) +async def test_workflow_cancel_and_child_start_in_same_activation( + client: Client, + env: WorkflowEnvironment, + flag: _WorkflowLogicFlag | None, + terminate_child: bool, + child_cancel_requested: bool, +): + if env.supports_time_skipping_v1: + pytest.skip( + "Java test server does not deliver the start and the cancellation in one activation" + ) + runner = CustomWorkflowRunner() + worker = new_worker(client, CancelAtChildStartWorkflow, workflow_runner=runner) + if flag is not None: + worker._set_default_workflow_logic_flag(flag, enabled=True) + async with worker: + handle = await client.start_workflow( + CancelAtChildStartWorkflow.run, + # No worker polls the child's queue, so the child keeps running. + str(uuid.uuid4()), + id=f"workflow-{uuid.uuid4()}", + task_queue=worker.task_queue, + # Core does not report a failure after the first attempt, so the + # server retries only after this timeout. + task_timeout=timedelta(seconds=1), + ) + await assert_task_fail_eventually( + handle, message_contains="Intentional task failure" + ) + if terminate_child: + await client.get_workflow_handle(f"{handle.id}-child").terminate() + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_TERMINATED] + ) + await handle.cancel() + with pytest.raises(WorkflowFailureError) as err: + await handle.result() + assert isinstance(err.value.cause, CancelledError) + + if flag is not None: + assert any( + flag in completion.successful.used_internal_flags + for _, completion in runner._pairs + ) + expected_jobs = {"resolve_child_workflow_execution_start", "cancel_workflow"} + if terminate_child: + expected_jobs.add("resolve_child_workflow_execution") + assert any( + expected_jobs.issubset({job.WhichOneof("variant") for job in activation.jobs}) + for activation, _ in runner._pairs + ) + history = await handle.fetch_history() + assert ( + any( + event.event_type + == EventType.EVENT_TYPE_REQUEST_CANCEL_EXTERNAL_WORKFLOW_EXECUTION_INITIATED + for event in history.events + ) + is child_cancel_requested + ) + await Replayer(workflows=[CancelAtChildStartWorkflow]).replay_workflow(history) + + @activity.defn async def wait_forever() -> NoReturn: await asyncio.Future()