diff --git a/changelog/added/tumbling-job-basket.md b/changelog/added/tumbling-job-basket.md new file mode 100644 index 000000000..3ecf15c76 --- /dev/null +++ b/changelog/added/tumbling-job-basket.md @@ -0,0 +1,8 @@ +Add flag-controlled workflow activation processing (workflow logic flag 4). With the flag, signal and update handlers no longer run before other jobs delivered in the same workflow task. The flag remains disabled by default in this release. +With flag 4, cancellation takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task. +Unlike flag 2, flag 4 cancels only the task that receives the cancellation. A `workflow.wait_condition()` call that is shielded or in another task, such as a signal or update handler, can therefore finish after cancellation. +With flag 4, a signal to an external or child workflow raises `asyncio.CancelledError` when it completes in the same workflow task as a workflow cancellation. Previously, a successful signal call returned and the workflow did not see the cancellation. +With flag 4, cancelling a child workflow or Nexus operation handle in the workflow task that delivers its result can take priority over the result. Awaiting the handle then raises `asyncio.CancelledError` instead of returning the result. +With flag 4, `workflow.all_handlers_finished()` can return `False` more often in the workflow task where a signal handler finishes. Use `await workflow.wait_condition(workflow.all_handlers_finished)` instead. +With flag 4, signal and update handlers do not run if applying another job in the same workflow task fails the workflow. +With flag 4 on Python 3.11, `workflow.wait_condition()` timeouts round to the nearest millisecond, as on Python 3.12 and later. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 2a9041dce..e35b6d6e6 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -22,7 +22,7 @@ class _WorkflowLogicFlag(IntEnum): RAISE_ON_CANCELLING_COMPLETED_ACTIVITY = 1 # Process all activation jobs in one batch instead of separate batches by job type. # Added in version 1.31.0. - # Not enabled by default. + # Enabled by default in version 1.36.0. Removed from default in version 1.36.1. PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH = 2 # Recognize sandbox proxies for datetime type hints during payload decoding. # Added on 2026-11-05. @@ -31,6 +31,19 @@ class _WorkflowLogicFlag(IntEnum): # Remove the explicit overrides for this flag from tests/worker/test_workflow_flags.py # when enabling it. Then remove this reminder. DECODE_DATETIME_PROXIES = 3 + # 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. + # TODO: When enabling APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS by default, + # remove the explicit overrides for this flag from the tests. The changelog + # must also name the minimum SDK version that replays histories with this + # flag, because older SDKs can give different replay results without a + # nondeterminism error. Then remove this reminder. + APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a..d6a267d36 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -510,9 +510,26 @@ def _activate( self._is_replaying = act.is_replaying self._current_thread_id = threading.get_ident() self._current_internal_flags = act.available_internal_flags - self._single_batch_activation = self._workflow_logic_flag_enabled( + # Histories that use the original single-batch flag must keep its + # workflow-wide cancellation check, so do not check the newer flag. + self._apply_jobs_first_flag = ( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH + not in self._current_internal_flags + and self._workflow_logic_flag_enabled( + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS + ) + ) + # Check the original single-batch flag last, so a run that uses the + # newer flag never records it. + self._single_batch_flag = ( + not self._apply_jobs_first_flag + and self._workflow_logic_flag_enabled( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH + ) ) + # Both flags apply all jobs before running tasks. They differ only in + # how they send 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) @@ -545,7 +562,7 @@ def _activate( if start_job: self._workflow_input = self._make_workflow_input(start_job) - if self._single_batch_activation: + if single_batch_activation: # Applying every job before giving workflow tasks a chance to # run prevents their order in the activation from hiding state # that arrived in the same workflow task. @@ -713,7 +730,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._single_batch_activation: + 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 @@ -2041,7 +2058,7 @@ async def workflow_wait_condition( # cancellation and keep going. def cancellation_arrived() -> bool: return ( - self._single_batch_activation + self._single_batch_flag and not cancellation_requested_before and self._cancel_reason is not None ) @@ -2058,12 +2075,17 @@ def cancellation_arrived() -> bool: else None ) markers = _capture_event_group_markers(event_groups) - # asyncio.wait_for() starts its timer from this task, so the options are - # set in the task's context and reset once the wait ends + # Scope the timer options so later timers in this task don't inherit them. token = _TimerOptionsCtxVar.set( _TimerOptions(user_metadata=user_metadata, event_group_markers=markers) ) try: + 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): + await fut + return await asyncio.wait_for(fut, timeout) except asyncio.TimeoutError: if cancellation_arrived(): @@ -2248,6 +2270,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. @@ -2285,7 +2312,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 @@ -2362,7 +2389,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 @@ -2414,7 +2441,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: @@ -2423,19 +2450,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._single_batch_activation: - 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) @@ -2444,9 +2468,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( @@ -2465,6 +2487,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..76685ce7d --- /dev/null +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -0,0 +1,283 @@ +import uuid +from datetime import timedelta + +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 Client, 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 CompleteOnSignalOperationWorkflow: + def __init__(self) -> None: + self._finish = False + + @workflow.run + async def run(self) -> str: + await workflow.wait_condition(lambda: self._finish) + return "operation complete" + + @workflow.signal + def finish(self) -> None: + self._finish = True + + +@nexusrpc.handler.service_handler +class CompleteOnSignalService: + @nexus.workflow_run_operation + async def complete_on_signal( + self, ctx: nexus.WorkflowRunOperationContext, workflow_id: str + ) -> nexus.WorkflowHandle[str]: + return await ctx.start_workflow( + CompleteOnSignalOperationWorkflow.run, id=workflow_id + ) + + +def _caller_worker( + client: Client, + workflow_class: type, + task_queue: str, + runner: CustomWorkflowRunner, + flag: _WorkflowLogicFlag | None, +) -> Worker: + worker = new_worker( + client, + workflow_class, + task_queue=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 + + +@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() + + handle = await env.client.start_workflow( + CancelAtOperationStartWorkflow.run, + endpoint, + id=f"workflow-{uuid.uuid4()}", + task_queue=caller_task_queue, + ) + async with _caller_worker( + env.client, CancelAtOperationStartWorkflow, caller_task_queue, runner, flag + ): + 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( + env.client, CancelAtOperationStartWorkflow, caller_task_queue, runner, flag + ): + 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) + + +@workflow.defn +class CancelAtOperationCompletionWorkflow: + @workflow.run + async def run(self, endpoint: str) -> str: + nexus_client = workflow.create_nexus_client( + service=CompleteOnSignalService, endpoint=endpoint + ) + handle = await nexus_client.start_operation( + CompleteOnSignalService.complete_on_signal, + f"{workflow.info().workflow_id}-operation", + ) + return await handle + + +@pytest.mark.parametrize( + "flag", + [ + pytest.param(None, id="no-flag"), + pytest.param( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH, + id="original-single-batch", + ), + pytest.param( + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS, + id="batching-with-task-cancellation", + ), + ], +) +async def test_workflow_cancel_and_operation_completion_in_same_activation( + env: WorkflowEnvironment, flag: _WorkflowLogicFlag | None +) -> 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() + + async with new_worker( + env.client, + CompleteOnSignalOperationWorkflow, + task_queue=handler_task_queue, + nexus_service_handlers=[CompleteOnSignalService()], + ): + handle = await env.client.start_workflow( + CancelAtOperationCompletionWorkflow.run, + endpoint, + id=f"workflow-{uuid.uuid4()}", + task_queue=caller_task_queue, + ) + async with _caller_worker( + env.client, + CancelAtOperationCompletionWorkflow, + caller_task_queue, + runner, + flag, + ): + # The caller must wait for the result, not for the start. + await assert_event_subsequence( + handle, + [ + EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED, + EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED, + ], + ) + + # The operation completes while no caller worker runs, so the result + # and the cancellation reach the caller in one activation. + await env.client.get_workflow_handle(f"{handle.id}-operation").signal( + CompleteOnSignalOperationWorkflow.finish + ) + # A server callback delivers the completion to the caller. + await assert_event_subsequence( + handle, + [EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED], + timeout=timedelta(seconds=10), + ) + await handle.cancel() + async with _caller_worker( + env.client, + CancelAtOperationCompletionWorkflow, + caller_task_queue, + runner, + flag, + ): + if flag is None: + # Legacy cancellation handling lets the completed operation win. + assert await handle.result() == "operation complete" + else: + 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", "cancel_workflow"}.issubset( + {job.WhichOneof("variant") for job in activation.jobs} + ) + for activation, _ in runner._pairs + ) + await Replayer(workflows=[CancelAtOperationCompletionWorkflow]).replay_workflow( + await handle.fetch_history() + ) diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index 8f4b1fd50..27a845571 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -556,18 +556,38 @@ async def test_replayer_async_ordering( Verify legacy and single-batch histories replay with the asyncio scheduling order that their original executions observed. """ + global test_replayer_workflow_res + with Path(__file__).with_name(history_filename).open() as f: history = WorkflowHistory.from_json("fake", f.read()) assert ( _history_uses_workflow_logic_flag(history, _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG) is uses_single_batch ) - await Replayer( + replayer = Replayer( workflows=[SignalsActivitiesTimersUpdatesTracingWorkflow], interceptors=[WorkerWorkflowResultInterceptor()], - ).replay_workflow(history) + ) + test_replayer_workflow_res = None + await replayer.replay_workflow(history) assert test_replayer_workflow_res == expected + if uses_single_batch: + # These histories do not cancel the workflow. The newer flag differs + # from flag 2 only in how it sends cancellation, so it must replay + # them with the same order. + for event in history.events: + if event.HasField("workflow_task_completed_event_attributes"): + flags = event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags + if _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG in flags: + flags.remove(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG) + flags.append( + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS + ) + test_replayer_workflow_res = None + await replayer.replay_workflow(history) + assert test_replayer_workflow_res == expected + async def test_replayer_unflagged_history_uses_legacy_async_ordering() -> None: with ( diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 54f64c855..d9c331574 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -70,6 +70,7 @@ WorkflowExecutionStatus, WorkflowFailureError, WorkflowHandle, + WorkflowHistory, WorkflowQueryFailedError, WorkflowUpdateFailedError, WorkflowUpdateHandle, @@ -134,6 +135,7 @@ LogHandler, admitted_update_task, assert_eq_eventually, + assert_event_subsequence, assert_eventually, assert_pending_activity_exists_eventually, assert_task_fail_eventually, @@ -1530,12 +1532,29 @@ async def run(self) -> str: _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) +_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG = ( + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS +) -def test_single_batch_workflow_activation_jobs_default_disabled() -> None: - assert ( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG not in _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS - ) +def _recorded_batching_flags(history: WorkflowHistory) -> set[int]: + return { + flag + for event in history.events + if event.HasField("workflow_task_completed_event_attributes") + for flag in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags + if flag + in (_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG) + } + + +@pytest.mark.parametrize( + "flag", [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG] +) +def test_single_batch_workflow_activation_jobs_default_disabled( + flag: _WorkflowLogicFlag, +) -> None: + assert flag not in _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS @workflow.defn @@ -1547,8 +1566,13 @@ def __init__(self) -> None: @workflow.run async def run(self) -> str: self._ready = True - await workflow.wait_condition(lambda: self._finish) - return "done" + try: + await workflow.wait_condition(lambda: self._finish, timeout=2) + except asyncio.TimeoutError: + return "timeout" + # A timer only on this branch lets replay see which branch ran. + await workflow.sleep(0.01) + return "condition" @workflow.signal def finish(self) -> None: @@ -1559,7 +1583,18 @@ def ready(self) -> bool: return self._ready -async def test_workflow_logic_flag_enabled_after_replay(client: Client) -> None: +@pytest.mark.parametrize( + "flag", + [ + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="original-single-batch"), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, id="batching-with-task-cancellation" + ), + ], +) +async def test_workflow_logic_flag_enabled_after_replay( + client: Client, flag: _WorkflowLogicFlag +) -> None: task_queue = str(uuid.uuid4()) handle = await client.start_workflow( EnableWorkflowLogicFlagAfterReplayWorkflow.run, @@ -1577,9 +1612,7 @@ async def test_workflow_logic_flag_enabled_after_replay(client: Client) -> None: max_cached_workflows=0, ) # Start under the legacy ordering so the first task does not record the flag - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=False - ) + worker._set_default_workflow_logic_flag(flag, enabled=False) async with worker: async def ready() -> bool: @@ -1587,6 +1620,9 @@ async def ready() -> bool: await assert_eq_eventually(True, ready) + # The timer fire and the signal reach the next worker in one activation. + # Without the flag, the signal handler runs first and the condition wins. + await assert_event_subsequence(handle, [EventType.EVENT_TYPE_TIMER_FIRED]) await handle.signal(EnableWorkflowLogicFlagAfterReplayWorkflow.finish) runner = CustomWorkflowRunner() @@ -1596,19 +1632,11 @@ async def ready() -> bool: task_queue=task_queue, workflow_runner=runner, ) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: - assert await handle.result() == "done" + assert await handle.result() == "timeout" assert any(activation.is_replaying for activation, _ in runner._pairs) - assert any( - not activation.is_replaying - and _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG - in completion.successful.used_internal_flags - for activation, completion in runner._pairs - ) history = await handle.fetch_history() workflow_task_flags = [ @@ -1616,17 +1644,20 @@ async def ready() -> bool: for event in history.events if event.HasField("workflow_task_completed_event_attributes") ] - assert _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG not in workflow_task_flags[0] - assert any( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG in flags for flags in workflow_task_flags[1:] - ) + assert flag not in workflow_task_flags[0] + assert any(flag in flags for flags in workflow_task_flags[1:]) await Replayer( workflows=[EnableWorkflowLogicFlagAfterReplayWorkflow] ).replay_workflow(history) -@pytest.mark.parametrize("single_batch", [False, True]) -async def test_workflow_cancel_before_run(client: Client, single_batch: bool): +@pytest.mark.parametrize( + "flag", + [None, _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], +) +async def test_workflow_cancel_before_run( + client: Client, flag: _WorkflowLogicFlag | None +): # Start the workflow _and_ send cancel before even starting the workflow task_queue = str(uuid.uuid4()) handle = await client.start_workflow( @@ -1637,9 +1668,8 @@ async def test_workflow_cancel_before_run(client: Client, single_batch: bool): await handle.cancel() # Start worker and wait for result worker = new_worker(client, TrapCancelWorkflow, task_queue=task_queue) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=single_batch - ) + if flag is not None: + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: assert "cancelled" == await handle.result() @@ -1684,9 +1714,18 @@ def waiting_after_cancel(self) -> bool: return self._waiting_after_cancel +@pytest.mark.parametrize( + "flag", + [ + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="original-single-batch"), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, id="batching-with-task-cancellation" + ), + ], +) @pytest.mark.parametrize("timeout", [False, True]) async def test_workflow_cancel_and_condition_ready_in_same_activation( - client: Client, timeout: bool + client: Client, timeout: bool, flag: _WorkflowLogicFlag ): task_queue = str(uuid.uuid4()) runner = CustomWorkflowRunner() @@ -1707,9 +1746,7 @@ async def test_workflow_cancel_and_condition_ready_in_same_activation( # the normal queue. max_cached_workflows=0, ) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def ready() -> bool: @@ -1728,9 +1765,7 @@ async def ready() -> bool: task_queue=task_queue, workflow_runner=runner, ) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def waiting_after_cancel() -> bool: @@ -1743,7 +1778,7 @@ async def waiting_after_cancel() -> bool: assert await handle.result() == "cancelled" assert any( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG in completion.successful.used_internal_flags + flag in completion.successful.used_internal_flags for _, completion in runner._pairs ) assert any( @@ -1757,6 +1792,209 @@ async def waiting_after_cancel() -> bool: ) +@workflow.defn +class ShieldedWaitConditionWorkflow: + def __init__(self) -> None: + self._confirmed = False + self._waiting = False + self._caught_cancel = False + + async def _cleanup(self, timeout: bool) -> None: + self._waiting = True + await workflow.wait_condition( + lambda: self._confirmed, timeout=1000 if timeout else None + ) + await workflow.sleep(0.01, summary="shielded cleanup") + + @workflow.run + async def run(self, timeout: bool) -> None: + cleanup = asyncio.create_task(self._cleanup(timeout)) + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError: + self._caught_cancel = True + await cleanup + raise + + @workflow.signal + def confirm(self) -> None: + self._confirmed = True + + @workflow.query + def state(self) -> tuple[bool, bool]: + return self._waiting, self._caught_cancel + + +@pytest.mark.parametrize("timeout", [False, True]) +@pytest.mark.parametrize("task_cancellation", [False, True]) +async def test_workflow_shielded_wait_condition_after_cancel( + client: Client, timeout: bool, task_cancellation: bool +) -> None: + worker = new_worker(client, ShieldedWaitConditionWorkflow) + # A new run uses the newer flag when the worker enables both. + worker._set_default_workflow_logic_flag( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True + ) + worker._set_default_workflow_logic_flag( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=task_cancellation + ) + async with worker: + handle = await client.start_workflow( + ShieldedWaitConditionWorkflow.run, + timeout, + id=f"workflow-{uuid.uuid4()}", + task_queue=worker.task_queue, + ) + + async def state() -> tuple[bool, bool]: + return await handle.query(ShieldedWaitConditionWorkflow.state) + + await assert_eq_eventually((True, False), state) + await handle.cancel() + await assert_eq_eventually((True, True), state) + await handle.signal(ShieldedWaitConditionWorkflow.confirm) + with pytest.raises(WorkflowFailureError) as err: + await handle.result() + assert isinstance(err.value.cause, CancelledError) + + history = await handle.fetch_history() + assert ( + any( + event.event_type == EventType.EVENT_TYPE_TIMER_FIRED + for event in history.events + ) + is task_cancellation + ) + assert _recorded_batching_flags(history) == { + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG + if task_cancellation + else _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG + } + await Replayer(workflows=[ShieldedWaitConditionWorkflow]).replay_workflow(history) + + +@workflow.defn +class HandlerWaitConditionAfterCancelWorkflow: + def __init__(self) -> None: + self._release = False + self._handler = "not-started" + self._caught_cancel = False + + @workflow.run + async def run(self) -> str: + try: + await workflow.wait_condition(lambda: False) + except asyncio.CancelledError: + self._caught_cancel = True + await workflow.wait_condition(workflow.all_handlers_finished) + if self._handler == "cancelled": + # A timer only on this branch lets replay see which branch ran. + await workflow.sleep(0.01) + return self._handler + + @workflow.signal + async def start_handler(self) -> None: + self._handler = "waiting" + try: + await workflow.wait_condition(lambda: self._release) + self._handler = "returned" + except asyncio.CancelledError: + self._handler = "cancelled" + + @workflow.signal + def release(self) -> None: + self._release = True + + @workflow.query + def state(self) -> tuple[str, bool]: + return self._handler, self._caught_cancel + + +@pytest.mark.parametrize( + ("first_flags", "later_flags", "expected"), + [ + pytest.param([], [], "returned", id="no-flag"), + pytest.param( + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], + "cancelled", + id="original-single-batch", + ), + pytest.param( + [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "returned", + id="batching-with-task-cancellation", + ), + # The first worker records the flag, and the handler wait starts on the + # second worker, so the flag in history decides the behavior. + pytest.param( + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "cancelled", + id="original-single-batch-then-both-flags", + ), + pytest.param( + [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "returned", + id="batching-with-task-cancellation-then-both-flags", + ), + ], +) +async def test_workflow_handler_wait_condition_after_cancel( + client: Client, + first_flags: list[_WorkflowLogicFlag], + later_flags: list[_WorkflowLogicFlag], + expected: str, +) -> None: + task_queue = str(uuid.uuid4()) + handle = await client.start_workflow( + HandlerWaitConditionAfterCancelWorkflow.run, + id=f"workflow-{uuid.uuid4()}", + task_queue=task_queue, + ) + + async def state() -> tuple[str, bool]: + return await handle.query(HandlerWaitConditionAfterCancelWorkflow.state) + + def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: + worker = new_worker( + client, + HandlerWaitConditionAfterCancelWorkflow, + task_queue=task_queue, + # The Java test server does not reliably reschedule an abandoned + # sticky task after its timeout, so keep events sent after this + # worker stops on the normal queue. + max_cached_workflows=0, + ) + for flag in ( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + ): + worker._set_default_workflow_logic_flag(flag, enabled=flag in flags) + return worker + + async with flag_worker(*first_flags): + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED] + ) + + async with flag_worker(*later_flags): + await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler) + await assert_eq_eventually(("waiting", False), state) + await handle.cancel() + await assert_eq_eventually(("waiting", True), state) + await handle.signal(HandlerWaitConditionAfterCancelWorkflow.release) + assert await handle.result() == expected + + history = await handle.fetch_history() + assert _recorded_batching_flags(history) == set(first_flags) + await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow( + history + ) + + @workflow.defn class CompleteChildOnSignalWorkflow: def __init__(self) -> None: @@ -1792,8 +2030,18 @@ def child_started(self) -> bool: return self._child_started +@pytest.mark.parametrize( + "flag", + [ + pytest.param(None, id="no-flag"), + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="original-single-batch"), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, id="batching-with-task-cancellation" + ), + ], +) async def test_workflow_cancel_and_child_completion_in_same_activation( - client: Client, + client: Client, flag: _WorkflowLogicFlag | None ): parent_task_queue = str(uuid.uuid4()) child_task_queue = str(uuid.uuid4()) @@ -1806,9 +2054,6 @@ async def test_workflow_cancel_and_child_completion_in_same_activation( CompleteChildOnSignalWorkflow, task_queue=child_task_queue, ) - child_worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) async with child_worker: handle = await client.start_workflow( CancelAtChildCompletionWorkflow.run, @@ -1826,9 +2071,8 @@ async def test_workflow_cancel_and_child_completion_in_same_activation( # worker stops on the normal queue. max_cached_workflows=0, ) - parent_worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + if flag is not None: + parent_worker._set_default_workflow_logic_flag(flag, enabled=True) async with parent_worker: async def child_started() -> bool: @@ -1858,21 +2102,211 @@ async def child_completion_recorded() -> None: task_queue=parent_task_queue, workflow_runner=runner, ) - parent_worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + if flag is not None: + parent_worker._set_default_workflow_logic_flag(flag, enabled=True) async with parent_worker: + if flag is None: + # Legacy cancellation handling lets the completed child result win. + assert await handle.result() == "child complete" + else: + 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_child_workflow_execution", "cancel_workflow"}.issubset( + {job.WhichOneof("variant") for job in activation.jobs} + ) + for activation, _ in runner._pairs + ) + await Replayer(workflows=[CancelAtChildCompletionWorkflow]).replay_workflow( + await handle.fetch_history() + ) + + +@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, + ) + if workflow.cancellation_reason() is None: + # The child starts before the test can cancel. Failed tasks + # complete nothing, so a later activation also gets the cancellation. + 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) + + +@workflow.defn +class CancelAtExternalSignalWorkflow: + @workflow.run + async def run(self, target_id: str) -> str: + await workflow.get_external_workflow_handle(target_id).signal( + CompleteChildOnSignalWorkflow.finish + ) + if workflow.cancellation_reason() is None: + # The signal completes before the test can cancel. Failed tasks + # complete nothing, so a later activation also gets the cancellation. + raise RuntimeError("Intentional task failure") + return "returned" + + +@pytest.mark.parametrize( + "flag", + [ + pytest.param(None, id="no-flag"), + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="original-single-batch"), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, id="batching-with-task-cancellation" + ), + ], +) +async def test_workflow_cancel_and_external_signal_in_same_activation( + client: Client, env: WorkflowEnvironment, flag: _WorkflowLogicFlag | None +): + if env.supports_time_skipping_v1: + pytest.skip( + "Java test server does not deliver the signal result and the cancellation in one activation" + ) + runner = CustomWorkflowRunner() + worker = new_worker(client, CancelAtExternalSignalWorkflow, workflow_runner=runner) + if flag is not None: + worker._set_default_workflow_logic_flag(flag, enabled=True) + async with worker: + target = await client.start_workflow( + CompleteChildOnSignalWorkflow.run, + id=f"workflow-{uuid.uuid4()}", + # No worker polls this queue, so the target keeps running. + task_queue=str(uuid.uuid4()), + ) + handle = await client.start_workflow( + CancelAtExternalSignalWorkflow.run, + target.id, + 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" + ) + await handle.cancel() + if flag is None: + # Legacy cancellation handling lets the completed signal win. + assert await handle.result() == "returned" + else: 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_child_workflow_execution", "cancel_workflow"}.issubset( + {"resolve_signal_external_workflow", "cancel_workflow"}.issubset( {job.WhichOneof("variant") for job in activation.jobs} ) for activation, _ in runner._pairs ) - await Replayer(workflows=[CancelAtChildCompletionWorkflow]).replay_workflow( + await Replayer(workflows=[CancelAtExternalSignalWorkflow]).replay_workflow( await handle.fetch_history() ) @@ -8498,14 +8932,19 @@ async def run(self) -> None: await asyncio.sleep(0.01) +@pytest.mark.parametrize("task_cancellation", [False, True]) async def test_wait_condition_timer_options_not_used_by_later_timers( - client: Client, env: WorkflowEnvironment + client: Client, env: WorkflowEnvironment, task_cancellation: bool ): if env.supports_time_skipping_v1: pytest.skip( "Java test server: https://github.com/temporalio/sdk-java/issues/2219" ) - async with new_worker(client, WaitConditionThenSleepWorkflow) as worker: + worker = new_worker(client, WaitConditionThenSleepWorkflow) + worker._set_default_workflow_logic_flag( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=task_cancellation + ) + async with worker: handle = await client.start_workflow( WaitConditionThenSleepWorkflow.run, id=f"workflow-{uuid.uuid4()}",