From b4c0f81fe1cd5785ab703ba7af3d83f2e77e63c7 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Thu, 19 Nov 2026 10:28:26 -0800 Subject: [PATCH 01/19] Add batching-only workflow logic flag --- temporalio/_workflow_context.py | 3 ++ temporalio/worker/_workflow_instance.py | 18 +++++++--- tests/worker/test_replayer.py | 23 ++++++++++-- tests/worker/test_workflow.py | 48 ++++++++++++++++--------- 4 files changed, 68 insertions(+), 24 deletions(-) diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 2a9041dcec..a627d8a1dc 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -31,6 +31,9 @@ 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 + # Batch activation jobs without enabling the cancellation changes in flag 2. + # Not enabled by default. + PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY = 4 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bcca2648a8..678902b519 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -510,9 +510,17 @@ 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( + # The original flag also changed cancellation behavior. Histories using + # it must retain those semantics; the new flag only changes scheduling. + self._single_batch_cancellation = self._workflow_logic_flag_enabled( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) + single_batch_activation = ( + self._single_batch_cancellation + or self._workflow_logic_flag_enabled( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY + ) + ) # Check this flag before queries can arrive, # even when no input needs decoding. self._workflow_logic_flag_enabled(_WorkflowLogicFlag.DECODE_DATETIME_PROXIES) @@ -545,7 +553,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 +721,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_cancellation: # 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 +2049,7 @@ async def workflow_wait_condition( # cancellation and keep going. def cancellation_arrived() -> bool: return ( - self._single_batch_activation + self._single_batch_cancellation and not cancellation_requested_before and self._cancel_reason is not None ) @@ -2426,7 +2434,7 @@ async def _await_temporal_operation( 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: + if self._single_batch_cancellation: raise if completed_cancellation_flag is not None and ( not self._is_replaying diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index 8f4b1fd507..8f2e1854f4 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -556,18 +556,37 @@ 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 exercise cancellation, so the batching-only + # flag must replay them with the same scheduling 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.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY + ) + 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 54f64c8552..66e5b11c65 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1530,12 +1530,18 @@ async def run(self) -> str: _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) +_BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY +) -def test_single_batch_workflow_activation_jobs_default_disabled() -> None: - assert ( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG not in _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS - ) +@pytest.mark.parametrize( + "flag", [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _BATCH_ONLY_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 @@ -1792,8 +1798,15 @@ def child_started(self) -> bool: return self._child_started +@pytest.mark.parametrize( + "flag", + [ + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="with-cancellation-changes"), + pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, id="batch-only"), + ], +) async def test_workflow_cancel_and_child_completion_in_same_activation( - client: Client, + client: Client, flag: _WorkflowLogicFlag ): parent_task_queue = str(uuid.uuid4()) child_task_queue = str(uuid.uuid4()) @@ -1806,9 +1819,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 +1836,7 @@ 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 - ) + parent_worker._set_default_workflow_logic_flag(flag, enabled=True) async with parent_worker: async def child_started() -> bool: @@ -1858,14 +1866,20 @@ 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 - ) + parent_worker._set_default_workflow_logic_flag(flag, enabled=True) async with parent_worker: - with pytest.raises(WorkflowFailureError) as err: - await handle.result() - assert isinstance(err.value.cause, CancelledError) + if flag == _BATCH_ONLY_WORKFLOW_LOGIC_FLAG: + # 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) + 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} From 0ac7e28b5732e7f7d97642e090dc9524cffa61db Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Thu, 19 Nov 2026 10:43:30 -0800 Subject: [PATCH 02/19] Name batching flag for activation ordering --- temporalio/_workflow_context.py | 2 +- temporalio/worker/_workflow_instance.py | 2 +- tests/worker/test_replayer.py | 2 +- tests/worker/test_workflow.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index a627d8a1dc..60a36d7675 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -33,7 +33,7 @@ class _WorkflowLogicFlag(IntEnum): DECODE_DATETIME_PROXIES = 3 # Batch activation jobs without enabling the cancellation changes in flag 2. # Not enabled by default. - PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY = 4 + 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 678902b519..9e94465671 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -518,7 +518,7 @@ def _activate( single_batch_activation = ( self._single_batch_cancellation or self._workflow_logic_flag_enabled( - _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) ) # Check this flag before queries can arrive, diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index 8f2e1854f4..b0ef238465 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -581,7 +581,7 @@ async def test_replayer_async_ordering( if _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG in flags: flags.remove(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG) flags.append( - _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) test_replayer_workflow_res = None await replayer.replay_workflow(history) diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 66e5b11c65..3116b9bc03 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1531,7 +1531,7 @@ async def run(self) -> str: _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) _BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( - _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH_ONLY + _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) From e1277e8ef82e38593d39941d8fff532ea6e1b878 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Fri, 20 Nov 2026 17:25:28 -0800 Subject: [PATCH 03/19] Add activation batching changelog fragment --- changelog/added/tumbling-job-basket.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/added/tumbling-job-basket.md diff --git a/changelog/added/tumbling-job-basket.md b/changelog/added/tumbling-job-basket.md new file mode 100644 index 0000000000..e44d97f004 --- /dev/null +++ b/changelog/added/tumbling-job-basket.md @@ -0,0 +1 @@ +Add an opt-in workflow compatibility flag that applies all activation jobs before running workflow tasks, without opting into changes to cancellation handling. From 6e409ef397c94efca0d3744a244524f1ca00fcec Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Thu, 19 Nov 2026 10:30:20 -0800 Subject: [PATCH 04/19] Gate task-local wait condition cancellation --- changelog/fixed/snuggly-cancellation-otter.md | 1 + temporalio/_workflow_context.py | 3 + temporalio/worker/_workflow_instance.py | 17 ++- tests/worker/test_workflow.py | 134 ++++++++++++++++-- 4 files changed, 141 insertions(+), 14 deletions(-) create mode 100644 changelog/fixed/snuggly-cancellation-otter.md diff --git a/changelog/fixed/snuggly-cancellation-otter.md b/changelog/fixed/snuggly-cancellation-otter.md new file mode 100644 index 0000000000..8e86682fab --- /dev/null +++ b/changelog/fixed/snuggly-cancellation-otter.md @@ -0,0 +1 @@ +Add opt-in cancellation handling for `workflow.wait_condition` that respects task shielding and preserves cancellation when a condition becomes ready concurrently. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 60a36d7675..c331f468a8 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -34,6 +34,9 @@ class _WorkflowLogicFlag(IntEnum): # Batch activation jobs without enabling the cancellation changes in flag 2. # Not enabled by default. APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 + # Use task-local cancellation in workflow.wait_condition. + # Not enabled by default. + WAIT_CONDITION_USE_TASK_CANCELLATION = 5 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 9e94465671..433c31118e 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -515,6 +515,14 @@ def _activate( self._single_batch_cancellation = self._workflow_logic_flag_enabled( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) + # Keep the original cancellation semantics for workflows that use flag 2, + # even when the worker opts new workflows into the wait condition fix. + self._wait_condition_task_cancellation = ( + not self._single_batch_cancellation + and self._workflow_logic_flag_enabled( + _WorkflowLogicFlag.WAIT_CONDITION_USE_TASK_CANCELLATION + ) + ) single_batch_activation = ( self._single_batch_cancellation or self._workflow_logic_flag_enabled( @@ -2066,12 +2074,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._wait_condition_task_cancellation: + # 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(): diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 3116b9bc03..960a817aad 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1533,6 +1533,9 @@ async def run(self) -> str: _BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) +_WAIT_CONDITION_CANCELLATION_FLAG = ( + _WorkflowLogicFlag.WAIT_CONDITION_USE_TASK_CANCELLATION +) @pytest.mark.parametrize( @@ -1690,9 +1693,19 @@ def waiting_after_cancel(self) -> bool: return self._waiting_after_cancel +@pytest.mark.parametrize( + "flags", + [ + pytest.param((_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG,), id="original-single-batch"), + pytest.param( + (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _WAIT_CONDITION_CANCELLATION_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, flags: tuple[_WorkflowLogicFlag, ...] ): task_queue = str(uuid.uuid4()) runner = CustomWorkflowRunner() @@ -1713,9 +1726,8 @@ 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 - ) + for flag in flags: + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def ready() -> bool: @@ -1734,9 +1746,8 @@ async def ready() -> bool: task_queue=task_queue, workflow_runner=runner, ) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True - ) + for flag in flags: + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def waiting_after_cancel() -> bool: @@ -1748,10 +1759,12 @@ async def waiting_after_cancel() -> bool: await handle.signal(CancelAtWaitConditionWorkflow.finish_after_cancel) assert await handle.result() == "cancelled" - assert any( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG in completion.successful.used_internal_flags + used_flags = { + flag for _, completion in runner._pairs - ) + for flag in completion.successful.used_internal_flags + } + assert used_flags.issuperset(flags) assert any( {"signal_workflow", "cancel_workflow"}.issubset( {job.WhichOneof("variant") for job in activation.jobs} @@ -1763,6 +1776,98 @@ 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( + ("batch_flag", "cleanup_completes"), + [ + pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, True, id="task-cancellation"), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, False, id="original-behavior-preserved" + ), + ], +) +async def test_workflow_shielded_wait_condition_after_cancel( + client: Client, + timeout: bool, + batch_flag: _WorkflowLogicFlag, + cleanup_completes: bool, +) -> None: + worker = new_worker(client, ShieldedWaitConditionWorkflow) + worker._set_default_workflow_logic_flag(batch_flag, enabled=True) + worker._set_default_workflow_logic_flag( + _WAIT_CONDITION_CANCELLATION_FLAG, enabled=True + ) + 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 cleanup_completes + ) + assert ( + any( + _WAIT_CONDITION_CANCELLATION_FLAG + in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags + for event in history.events + ) + is cleanup_completes + ) + await Replayer(workflows=[ShieldedWaitConditionWorkflow]).replay_workflow(history) + + @workflow.defn class CompleteChildOnSignalWorkflow: def __init__(self) -> None: @@ -8512,14 +8617,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( + _WAIT_CONDITION_CANCELLATION_FLAG, enabled=task_cancellation + ) + async with worker: handle = await client.start_workflow( WaitConditionThenSleepWorkflow.run, id=f"workflow-{uuid.uuid4()}", From 4dc7c35deba4e75e35c66e418089dc8ec609b3c1 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Thu, 19 Nov 2026 10:41:22 -0800 Subject: [PATCH 05/19] Share cancellation fixes across workflow logic flags --- changelog/fixed/snuggly-cancellation-otter.md | 2 +- temporalio/_workflow_context.py | 4 +-- temporalio/worker/_workflow_instance.py | 24 ++++++++-------- tests/worker/test_workflow.py | 28 +++++++++---------- 4 files changed, 28 insertions(+), 30 deletions(-) diff --git a/changelog/fixed/snuggly-cancellation-otter.md b/changelog/fixed/snuggly-cancellation-otter.md index 8e86682fab..c699780424 100644 --- a/changelog/fixed/snuggly-cancellation-otter.md +++ b/changelog/fixed/snuggly-cancellation-otter.md @@ -1 +1 @@ -Add opt-in cancellation handling for `workflow.wait_condition` that respects task shielding and preserves cancellation when a condition becomes ready concurrently. +Add opt-in workflow cancellation fixes that respect shielding in `workflow.wait_condition` and preserve task cancellation when a condition or a Temporal operation completes concurrently. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index c331f468a8..09abea9aa1 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -34,9 +34,9 @@ class _WorkflowLogicFlag(IntEnum): # Batch activation jobs without enabling the cancellation changes in flag 2. # Not enabled by default. APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 - # Use task-local cancellation in workflow.wait_condition. + # Preserve task cancellation when a condition or operation completes concurrently. # Not enabled by default. - WAIT_CONDITION_USE_TASK_CANCELLATION = 5 + FIX_WORKFLOW_CANCELLATION = 5 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 433c31118e..bf4c2820fa 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -510,21 +510,19 @@ def _activate( self._is_replaying = act.is_replaying self._current_thread_id = threading.get_ident() self._current_internal_flags = act.available_internal_flags - # The original flag also changed cancellation behavior. Histories using - # it must retain those semantics; the new flag only changes scheduling. - self._single_batch_cancellation = self._workflow_logic_flag_enabled( + self._legacy_single_batch = self._workflow_logic_flag_enabled( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) - # Keep the original cancellation semantics for workflows that use flag 2, - # even when the worker opts new workflows into the wait condition fix. - self._wait_condition_task_cancellation = ( - not self._single_batch_cancellation + # The task-local wait condition fix must not change the behavior of + # histories that use the original single-batch flag. + self._fix_workflow_cancellation = ( + not self._legacy_single_batch and self._workflow_logic_flag_enabled( - _WorkflowLogicFlag.WAIT_CONDITION_USE_TASK_CANCELLATION + _WorkflowLogicFlag.FIX_WORKFLOW_CANCELLATION ) ) single_batch_activation = ( - self._single_batch_cancellation + self._legacy_single_batch or self._workflow_logic_flag_enabled( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) @@ -729,7 +727,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_cancellation: + elif self._legacy_single_batch or self._fix_workflow_cancellation: # 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 @@ -2057,7 +2055,7 @@ async def workflow_wait_condition( # cancellation and keep going. def cancellation_arrived() -> bool: return ( - self._single_batch_cancellation + self._legacy_single_batch and not cancellation_requested_before and self._cancel_reason is not None ) @@ -2079,7 +2077,7 @@ def cancellation_arrived() -> bool: _TimerOptions(user_metadata=user_metadata, event_group_markers=markers) ) try: - if self._wait_condition_task_cancellation: + if self._fix_workflow_cancellation: # A direct await lets the waiting task arbitrate cancellation # and readiness without bypassing shielding or using wait_for. async with asyncio.timeout(timeout): @@ -2447,7 +2445,7 @@ async def _await_temporal_operation( if fut.done(): # Retrying the shield after both futures become ready would # return the result and erase the task cancellation. - if self._single_batch_cancellation: + if self._legacy_single_batch or self._fix_workflow_cancellation: raise if completed_cancellation_flag is not None and ( not self._is_replaying diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 960a817aad..02d7f3c9da 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1533,9 +1533,7 @@ async def run(self) -> str: _BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) -_WAIT_CONDITION_CANCELLATION_FLAG = ( - _WorkflowLogicFlag.WAIT_CONDITION_USE_TASK_CANCELLATION -) +_FIX_CANCELLATION_FLAG = _WorkflowLogicFlag.FIX_WORKFLOW_CANCELLATION @pytest.mark.parametrize( @@ -1634,8 +1632,12 @@ async def ready() -> bool: ).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, _FIX_CANCELLATION_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( @@ -1646,9 +1648,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() @@ -1698,7 +1699,7 @@ def waiting_after_cancel(self) -> bool: [ pytest.param((_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG,), id="original-single-batch"), pytest.param( - (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _WAIT_CONDITION_CANCELLATION_FLAG), + (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _FIX_CANCELLATION_FLAG), id="batching-with-task-cancellation", ), ], @@ -1827,9 +1828,7 @@ async def test_workflow_shielded_wait_condition_after_cancel( ) -> None: worker = new_worker(client, ShieldedWaitConditionWorkflow) worker._set_default_workflow_logic_flag(batch_flag, enabled=True) - worker._set_default_workflow_logic_flag( - _WAIT_CONDITION_CANCELLATION_FLAG, enabled=True - ) + worker._set_default_workflow_logic_flag(_FIX_CANCELLATION_FLAG, enabled=True) async with worker: handle = await client.start_workflow( ShieldedWaitConditionWorkflow.run, @@ -1859,7 +1858,7 @@ async def state() -> tuple[bool, bool]: ) assert ( any( - _WAIT_CONDITION_CANCELLATION_FLAG + _FIX_CANCELLATION_FLAG in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags for event in history.events ) @@ -1908,6 +1907,7 @@ def child_started(self) -> bool: [ pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="with-cancellation-changes"), pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, id="batch-only"), + pytest.param(_FIX_CANCELLATION_FLAG, id="cancellation-only"), ], ) async def test_workflow_cancel_and_child_completion_in_same_activation( @@ -8627,7 +8627,7 @@ async def test_wait_condition_timer_options_not_used_by_later_timers( ) worker = new_worker(client, WaitConditionThenSleepWorkflow) worker._set_default_workflow_logic_flag( - _WAIT_CONDITION_CANCELLATION_FLAG, enabled=task_cancellation + _FIX_CANCELLATION_FLAG, enabled=task_cancellation ) async with worker: handle = await client.start_workflow( From 8449626afb90a5d1e31e9282c3d99d8d72d74440 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Thu, 19 Nov 2026 10:45:08 -0800 Subject: [PATCH 06/19] Name flag for preserving task cancellation --- temporalio/_workflow_context.py | 2 +- temporalio/worker/_workflow_instance.py | 10 +++++----- tests/worker/test_workflow.py | 16 +++++++++------- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 09abea9aa1..2ea2941dad 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -36,7 +36,7 @@ class _WorkflowLogicFlag(IntEnum): APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 # Preserve task cancellation when a condition or operation completes concurrently. # Not enabled by default. - FIX_WORKFLOW_CANCELLATION = 5 + PRESERVE_TASK_CANCELLATION = 5 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index bf4c2820fa..f88cd5bb90 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -515,10 +515,10 @@ def _activate( ) # The task-local wait condition fix must not change the behavior of # histories that use the original single-batch flag. - self._fix_workflow_cancellation = ( + self._preserve_task_cancellation = ( not self._legacy_single_batch and self._workflow_logic_flag_enabled( - _WorkflowLogicFlag.FIX_WORKFLOW_CANCELLATION + _WorkflowLogicFlag.PRESERVE_TASK_CANCELLATION ) ) single_batch_activation = ( @@ -727,7 +727,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._fix_workflow_cancellation: + elif self._legacy_single_batch or self._preserve_task_cancellation: # 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 @@ -2077,7 +2077,7 @@ def cancellation_arrived() -> bool: _TimerOptions(user_metadata=user_metadata, event_group_markers=markers) ) try: - if self._fix_workflow_cancellation: + if self._preserve_task_cancellation: # A direct await lets the waiting task arbitrate cancellation # and readiness without bypassing shielding or using wait_for. async with asyncio.timeout(timeout): @@ -2445,7 +2445,7 @@ async def _await_temporal_operation( 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._fix_workflow_cancellation: + if self._legacy_single_batch or self._preserve_task_cancellation: raise if completed_cancellation_flag is not None and ( not self._is_replaying diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 02d7f3c9da..346910c044 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1533,7 +1533,7 @@ async def run(self) -> str: _BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) -_FIX_CANCELLATION_FLAG = _WorkflowLogicFlag.FIX_WORKFLOW_CANCELLATION +_PRESERVE_TASK_CANCELLATION_FLAG = _WorkflowLogicFlag.PRESERVE_TASK_CANCELLATION @pytest.mark.parametrize( @@ -1633,7 +1633,7 @@ async def ready() -> bool: @pytest.mark.parametrize( - "flag", [None, _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _FIX_CANCELLATION_FLAG] + "flag", [None, _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _PRESERVE_TASK_CANCELLATION_FLAG] ) async def test_workflow_cancel_before_run( client: Client, flag: _WorkflowLogicFlag | None @@ -1699,7 +1699,7 @@ def waiting_after_cancel(self) -> bool: [ pytest.param((_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG,), id="original-single-batch"), pytest.param( - (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _FIX_CANCELLATION_FLAG), + (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _PRESERVE_TASK_CANCELLATION_FLAG), id="batching-with-task-cancellation", ), ], @@ -1828,7 +1828,9 @@ async def test_workflow_shielded_wait_condition_after_cancel( ) -> None: worker = new_worker(client, ShieldedWaitConditionWorkflow) worker._set_default_workflow_logic_flag(batch_flag, enabled=True) - worker._set_default_workflow_logic_flag(_FIX_CANCELLATION_FLAG, enabled=True) + worker._set_default_workflow_logic_flag( + _PRESERVE_TASK_CANCELLATION_FLAG, enabled=True + ) async with worker: handle = await client.start_workflow( ShieldedWaitConditionWorkflow.run, @@ -1858,7 +1860,7 @@ async def state() -> tuple[bool, bool]: ) assert ( any( - _FIX_CANCELLATION_FLAG + _PRESERVE_TASK_CANCELLATION_FLAG in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags for event in history.events ) @@ -1907,7 +1909,7 @@ def child_started(self) -> bool: [ pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="with-cancellation-changes"), pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, id="batch-only"), - pytest.param(_FIX_CANCELLATION_FLAG, id="cancellation-only"), + pytest.param(_PRESERVE_TASK_CANCELLATION_FLAG, id="cancellation-only"), ], ) async def test_workflow_cancel_and_child_completion_in_same_activation( @@ -8627,7 +8629,7 @@ async def test_wait_condition_timer_options_not_used_by_later_timers( ) worker = new_worker(client, WaitConditionThenSleepWorkflow) worker._set_default_workflow_logic_flag( - _FIX_CANCELLATION_FLAG, enabled=task_cancellation + _PRESERVE_TASK_CANCELLATION_FLAG, enabled=task_cancellation ) async with worker: handle = await client.start_workflow( From 26f6f8b3f75e42a6f70f2e0b3c717abd0be60441 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Fri, 20 Nov 2026 17:25:39 -0800 Subject: [PATCH 07/19] Clarify task cancellation changelog fragment --- changelog/fixed/snuggly-cancellation-otter.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog/fixed/snuggly-cancellation-otter.md b/changelog/fixed/snuggly-cancellation-otter.md index c699780424..d2aafa04e6 100644 --- a/changelog/fixed/snuggly-cancellation-otter.md +++ b/changelog/fixed/snuggly-cancellation-otter.md @@ -1 +1 @@ -Add opt-in workflow cancellation fixes that respect shielding in `workflow.wait_condition` and preserve task cancellation when a condition or a Temporal operation completes concurrently. +Add opt-in workflow cancellation handling that lets shielded tasks finish `workflow.wait_condition` and prevents a concurrently completed condition or Temporal operation from swallowing cancellation delivered to the waiting task. From e63a750632abd822f6061fc13ea5abe1db48f141 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Fri, 20 Nov 2026 17:30:54 -0800 Subject: [PATCH 08/19] Document legacy single-batch flag rollout --- temporalio/_workflow_context.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index 2ea2941dad..b429e95246 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. From 64c5ad2b59ccb9f205891ca3b6134d3cff7645be Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Mon, 30 Nov 2026 16:09:12 -0800 Subject: [PATCH 09/19] Combine activation batching and task cancellation flags Flag 4 now applies all activation jobs before it runs workflow tasks, and sends cancellation only to the task that receives it. Remove flag 5. Batching alone changes which result wins when a cancellation arrives in the same workflow task, so one flag controls both behaviors. Co-Authored-By: Claude Opus 5.5 --- changelog/added/tumbling-job-basket.md | 2 +- changelog/fixed/snuggly-cancellation-otter.md | 1 - temporalio/_workflow_context.py | 8 +- temporalio/worker/_workflow_instance.py | 13 ++-- tests/worker/test_replayer.py | 5 +- tests/worker/test_workflow.py | 78 +++++++++---------- 6 files changed, 53 insertions(+), 54 deletions(-) delete mode 100644 changelog/fixed/snuggly-cancellation-otter.md diff --git a/changelog/added/tumbling-job-basket.md b/changelog/added/tumbling-job-basket.md index e44d97f004..1c96ceeb1b 100644 --- a/changelog/added/tumbling-job-basket.md +++ b/changelog/added/tumbling-job-basket.md @@ -1 +1 @@ -Add an opt-in workflow compatibility flag that applies all activation jobs before running workflow tasks, without opting into changes to cancellation handling. +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. Cancellation also takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task as the cancellation. Unlike flag 2, flag 4 cancels only the task that receives the cancellation, so a shielded `workflow.wait_condition` can finish. The flag remains disabled by default in this release. diff --git a/changelog/fixed/snuggly-cancellation-otter.md b/changelog/fixed/snuggly-cancellation-otter.md deleted file mode 100644 index d2aafa04e6..0000000000 --- a/changelog/fixed/snuggly-cancellation-otter.md +++ /dev/null @@ -1 +0,0 @@ -Add opt-in workflow cancellation handling that lets shielded tasks finish `workflow.wait_condition` and prevents a concurrently completed condition or Temporal operation from swallowing cancellation delivered to the waiting task. diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index b429e95246..ec21925742 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -31,12 +31,12 @@ 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 - # Batch activation jobs without enabling the cancellation changes in flag 2. + # 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. + # Added on 2026-11-30. # Not enabled by default. APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 - # Preserve task cancellation when a condition or operation completes concurrently. - # Not enabled by default. - PRESERVE_TASK_CANCELLATION = 5 _DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset() diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index f88cd5bb90..5ab8c5ace2 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -513,19 +513,18 @@ def _activate( self._legacy_single_batch = self._workflow_logic_flag_enabled( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) - # The task-local wait condition fix must not change the behavior of - # histories that use the original single-batch flag. + # 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 and self._workflow_logic_flag_enabled( - _WorkflowLogicFlag.PRESERVE_TASK_CANCELLATION + _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._workflow_logic_flag_enabled( - _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS - ) + self._legacy_single_batch or self._preserve_task_cancellation ) # Check this flag before queries can arrive, # even when no input needs decoding. diff --git a/tests/worker/test_replayer.py b/tests/worker/test_replayer.py index b0ef238465..27a8455710 100644 --- a/tests/worker/test_replayer.py +++ b/tests/worker/test_replayer.py @@ -573,8 +573,9 @@ async def test_replayer_async_ordering( assert test_replayer_workflow_res == expected if uses_single_batch: - # These histories do not exercise cancellation, so the batching-only - # flag must replay them with the same scheduling order. + # 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 diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 346910c044..66007ed77b 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1530,14 +1530,13 @@ async def run(self) -> str: _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH ) -_BATCH_ONLY_WORKFLOW_LOGIC_FLAG = ( +_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG = ( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) -_PRESERVE_TASK_CANCELLATION_FLAG = _WorkflowLogicFlag.PRESERVE_TASK_CANCELLATION @pytest.mark.parametrize( - "flag", [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _BATCH_ONLY_WORKFLOW_LOGIC_FLAG] + "flag", [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG] ) def test_single_batch_workflow_activation_jobs_default_disabled( flag: _WorkflowLogicFlag, @@ -1633,7 +1632,8 @@ async def ready() -> bool: @pytest.mark.parametrize( - "flag", [None, _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _PRESERVE_TASK_CANCELLATION_FLAG] + "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 @@ -1695,18 +1695,17 @@ def waiting_after_cancel(self) -> bool: @pytest.mark.parametrize( - "flags", + "flag", [ - pytest.param((_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG,), id="original-single-batch"), + pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="original-single-batch"), pytest.param( - (_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, _PRESERVE_TASK_CANCELLATION_FLAG), - id="batching-with-task-cancellation", + _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, flags: tuple[_WorkflowLogicFlag, ...] + client: Client, timeout: bool, flag: _WorkflowLogicFlag ): task_queue = str(uuid.uuid4()) runner = CustomWorkflowRunner() @@ -1727,8 +1726,7 @@ async def test_workflow_cancel_and_condition_ready_in_same_activation( # the normal queue. max_cached_workflows=0, ) - for flag in flags: - worker._set_default_workflow_logic_flag(flag, enabled=True) + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def ready() -> bool: @@ -1747,8 +1745,7 @@ async def ready() -> bool: task_queue=task_queue, workflow_runner=runner, ) - for flag in flags: - worker._set_default_workflow_logic_flag(flag, enabled=True) + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: async def waiting_after_cancel() -> bool: @@ -1760,12 +1757,10 @@ async def waiting_after_cancel() -> bool: await handle.signal(CancelAtWaitConditionWorkflow.finish_after_cancel) assert await handle.result() == "cancelled" - used_flags = { - flag + assert any( + flag in completion.successful.used_internal_flags for _, completion in runner._pairs - for flag in completion.successful.used_internal_flags - } - assert used_flags.issuperset(flags) + ) assert any( {"signal_workflow", "cancel_workflow"}.issubset( {job.WhichOneof("variant") for job in activation.jobs} @@ -1812,24 +1807,24 @@ def state(self) -> tuple[bool, bool]: @pytest.mark.parametrize("timeout", [False, True]) @pytest.mark.parametrize( - ("batch_flag", "cleanup_completes"), + ("original_single_batch", "cleanup_completes"), [ - pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, True, id="task-cancellation"), - pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, False, id="original-behavior-preserved" - ), + pytest.param(False, True, id="task-cancellation"), + pytest.param(True, False, id="original-behavior-preserved"), ], ) async def test_workflow_shielded_wait_condition_after_cancel( client: Client, timeout: bool, - batch_flag: _WorkflowLogicFlag, + original_single_batch: bool, cleanup_completes: bool, ) -> None: worker = new_worker(client, ShieldedWaitConditionWorkflow) - worker._set_default_workflow_logic_flag(batch_flag, enabled=True) worker._set_default_workflow_logic_flag( - _PRESERVE_TASK_CANCELLATION_FLAG, enabled=True + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=original_single_batch + ) + worker._set_default_workflow_logic_flag( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=True ) async with worker: handle = await client.start_workflow( @@ -1860,7 +1855,7 @@ async def state() -> tuple[bool, bool]: ) assert ( any( - _PRESERVE_TASK_CANCELLATION_FLAG + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags for event in history.events ) @@ -1907,13 +1902,15 @@ def child_started(self) -> bool: @pytest.mark.parametrize( "flag", [ - pytest.param(_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, id="with-cancellation-changes"), - pytest.param(_BATCH_ONLY_WORKFLOW_LOGIC_FLAG, id="batch-only"), - pytest.param(_PRESERVE_TASK_CANCELLATION_FLAG, id="cancellation-only"), + 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, flag: _WorkflowLogicFlag + client: Client, flag: _WorkflowLogicFlag | None ): parent_task_queue = str(uuid.uuid4()) child_task_queue = str(uuid.uuid4()) @@ -1943,7 +1940,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(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: @@ -1973,9 +1971,10 @@ async def child_completion_recorded() -> None: task_queue=parent_task_queue, workflow_runner=runner, ) - parent_worker._set_default_workflow_logic_flag(flag, enabled=True) + if flag is not None: + parent_worker._set_default_workflow_logic_flag(flag, enabled=True) async with parent_worker: - if flag == _BATCH_ONLY_WORKFLOW_LOGIC_FLAG: + if flag is None: # Legacy cancellation handling lets the completed child result win. assert await handle.result() == "child complete" else: @@ -1983,10 +1982,11 @@ async def child_completion_recorded() -> None: await handle.result() assert isinstance(err.value.cause, CancelledError) - assert any( - flag in completion.successful.used_internal_flags - for _, completion in runner._pairs - ) + 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} @@ -8629,7 +8629,7 @@ async def test_wait_condition_timer_options_not_used_by_later_timers( ) worker = new_worker(client, WaitConditionThenSleepWorkflow) worker._set_default_workflow_logic_flag( - _PRESERVE_TASK_CANCELLATION_FLAG, enabled=task_cancellation + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=task_cancellation ) async with worker: handle = await client.start_workflow( From e6e2a6d4e2c0327c74b21d0e54c6320e67e99493 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 11:57:15 -0800 Subject: [PATCH 10/19] Cancel a started child or Nexus operation on start cancellation With flag 4, a start that resolves in the same activation as a cancellation raises CancelledError. The caller gets no handle, so the SDK now sends the cancel request to the child or operation before it raises. Flag 2 behavior does not change. Refs SDK-604. Co-Authored-By: Claude Opus 5.5 --- temporalio/worker/_workflow_instance.py | 8 +- ...rkflow_caller_cancel_in_same_activation.py | 139 ++++++++++++++++++ tests/worker/test_workflow.py | 91 ++++++++++++ 3 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 tests/nexus/test_workflow_caller_cancel_in_same_activation.py diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 5ab8c5ace2..5b2a81c9a0 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2444,7 +2444,13 @@ async def _await_temporal_operation( 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: + if self._preserve_task_cancellation: + if reraise_on_workflow_cancellation: + # A start that raises gives the caller no handle, + # so the caller cannot cancel the operation itself. + apply_cancel(err) + raise + if self._legacy_single_batch: raise if completed_cancellation_flag is not None and ( not self._is_replaying 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 0000000000..90abb462cc --- /dev/null +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -0,0 +1,139 @@ +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 + +pytestmark = pytest.mark.requires_local_server + + +@workflow.defn +class WaitForCancelWorkflow: + @workflow.run + async def run(self) -> None: + await workflow.wait_condition(lambda: False) + + +@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: + 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 66007ed77b..da8c90ca6b 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1998,6 +1998,97 @@ 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 too fast to stop the worker before the start + # resolves. Failed tasks keep the start pending until the cancellation + # arrives in the same activation, where the start raises instead. + raise RuntimeError("Intentional task failure") + + +@pytest.mark.parametrize( + ("flag", "child_cancel_requested"), + [ + pytest.param(None, True, id="no-flag"), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, False, id="original-single-batch" + ), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + True, + id="batching-with-task-cancellation", + ), + ], +) +async def test_workflow_cancel_and_child_start_in_same_activation( + client: Client, flag: _WorkflowLogicFlag | None, child_cancel_requested: bool +): + task_queue = str(uuid.uuid4()) + runner = CustomWorkflowRunner() + + def parent_worker() -> Worker: + worker = new_worker( + client, + CancelAtChildStartWorkflow, + task_queue=task_queue, + workflow_runner=runner, + # 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, + ) + if flag is not None: + worker._set_default_workflow_logic_flag(flag, enabled=True) + return 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=task_queue, + ) + async with parent_worker(): + await assert_task_fail_eventually( + handle, message_contains="Intentional task failure" + ) + await handle.cancel() + + async with parent_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_child_workflow_execution_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_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() From 2013a056c6a85417ee1e7d2ebd3e5316ccf40392 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 13:55:15 -0800 Subject: [PATCH 11/19] Skip the cancel for a child that already resolved With flag 4, the start cancel path can run after the child result resolved in the same activation. Core fails the task on a cancel for a terminated child, so skip the cancel when the result is known. Also address review findings in the start cancellation tests: - Use one worker for the child test, with a short task timeout. - Add a case where the child terminates in the same activation. - Skip the child test on the Java test server. - Run the Nexus test on time-skipping V2, and reuse WaitForCancelWorkflow. Refs SDK-604. Co-Authored-By: Claude Opus 5.5 --- temporalio/_workflow_context.py | 2 + temporalio/worker/_workflow_instance.py | 20 +++-- ...rkflow_caller_cancel_in_same_activation.py | 13 +-- tests/worker/test_workflow.py | 87 +++++++++++-------- 4 files changed, 69 insertions(+), 53 deletions(-) diff --git a/temporalio/_workflow_context.py b/temporalio/_workflow_context.py index ec21925742..47d9ef5621 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 5b2a81c9a0..ab86ead762 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2266,6 +2266,11 @@ async def _outbound_start_child_workflow( def apply_child_cancel_error( err: asyncio.CancelledError, ) -> None: + if self._preserve_task_cancellation 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. @@ -2442,15 +2447,16 @@ async def _await_temporal_operation( return await _shield_await(fut) except asyncio.CancelledError as err: if fut.done(): + if ( + self._preserve_task_cancellation + and reraise_on_workflow_cancellation + ): + # A start that raises gives the caller no handle, so + # the caller cannot cancel the operation itself. + apply_cancel(err) # Retrying the shield after both futures become ready would # return the result and erase the task cancellation. - if self._preserve_task_cancellation: - if reraise_on_workflow_cancellation: - # A start that raises gives the caller no handle, - # so the caller cannot cancel the operation itself. - apply_cancel(err) - raise - if self._legacy_single_batch: + if self._legacy_single_batch or self._preserve_task_cancellation: raise if completed_cancellation_flag is not None and ( not self._is_replaying diff --git a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py index 90abb462cc..57aefc1953 100644 --- a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -12,18 +12,13 @@ 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 +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 -@workflow.defn -class WaitForCancelWorkflow: - @workflow.run - async def run(self) -> None: - await workflow.wait_condition(lambda: False) - - @nexusrpc.handler.service_handler class WaitForCancelService: @nexus.workflow_run_operation @@ -67,7 +62,7 @@ async def test_workflow_cancel_and_operation_start_in_same_activation( flag: _WorkflowLogicFlag | None, operation_cancel_requested: bool, ) -> None: - if env.supports_time_skipping: + if env.supports_time_skipping_v1: pytest.skip("Nexus tests don't work with time-skipping server") caller_task_queue = str(uuid.uuid4()) diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index da8c90ca6b..b58ca2df2a 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, @@ -2007,61 +2008,72 @@ async def run(self, child_task_queue: str) -> None: id=f"{workflow.info().workflow_id}-child", task_queue=child_task_queue, ) - # The child starts too fast to stop the worker before the start - # resolves. Failed tasks keep the start pending until the cancellation - # arrives in the same activation, where the start raises instead. + # 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", "child_cancel_requested"), + ("flag", "terminate_child", "child_cancel_requested"), [ - pytest.param(None, True, id="no-flag"), + pytest.param(None, False, True, id="no-flag"), pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, False, id="original-single-batch" + _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, flag: _WorkflowLogicFlag | None, child_cancel_requested: bool + client: Client, + env: WorkflowEnvironment, + flag: _WorkflowLogicFlag | None, + terminate_child: bool, + child_cancel_requested: bool, ): - task_queue = str(uuid.uuid4()) + if env.supports_time_skipping_v1: + pytest.skip( + "Java test server does not deliver the start and the cancellation in one activation" + ) runner = CustomWorkflowRunner() - - def parent_worker() -> Worker: - worker = new_worker( - client, - CancelAtChildStartWorkflow, - task_queue=task_queue, - workflow_runner=runner, - # 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, + 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), ) - if flag is not None: - worker._set_default_workflow_logic_flag(flag, enabled=True) - return 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=task_queue, - ) - async with parent_worker(): await assert_task_fail_eventually( handle, message_contains="Intentional task failure" ) - await handle.cancel() - - async with parent_worker(): + 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) @@ -2071,10 +2083,11 @@ def parent_worker() -> Worker: 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( - {"resolve_child_workflow_execution_start", "cancel_workflow"}.issubset( - {job.WhichOneof("variant") for job in activation.jobs} - ) + expected_jobs.issubset({job.WhichOneof("variant") for job in activation.jobs}) for activation, _ in runner._pairs ) history = await handle.fetch_history() From 88f51cd4b483251457f433786fe417a40dc54e49 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 16:10:13 -0800 Subject: [PATCH 12/19] Clarify flag names in operation cancellation Name the flag 2 and flag 4 attributes after their flags, and name the start parameter after what the caller awaits. Move the decision that a cancellation wins over a resolved operation into its own helper, so _await_temporal_operation has one branch for resolved operations. Refs SDK-604. Co-Authored-By: Claude Opus 5.5 --- temporalio/worker/_workflow_instance.py | 67 +++++++++++++------------ 1 file changed, 34 insertions(+), 33 deletions(-) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index ab86ead762..76c990942c 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,7 +2264,7 @@ async def _outbound_start_child_workflow( def apply_child_cancel_error( err: asyncio.CancelledError, ) -> None: - if self._preserve_task_cancellation and handle._result_fut.done(): + 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. @@ -2308,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 @@ -2385,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 @@ -2437,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: @@ -2446,26 +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(): - if ( - self._preserve_task_cancellation - and reraise_on_workflow_cancellation - ): + # 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) - # 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 + raise apply_cancel(err) @@ -2474,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( @@ -2495,6 +2481,21 @@ 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: + 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) From 05dd78ee54526e2171082d09ba24a6f768d89eff Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 16:13:25 -0800 Subject: [PATCH 13/19] Document when a cancellation wins over a ready result Refs SDK-604. Co-Authored-By: Claude Opus 5.5 --- temporalio/worker/_workflow_instance.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 76c990942c..cfbe2b2ade 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -2484,6 +2484,18 @@ async def _cancel_external_workflow( 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 ( From 61ae7cab55aa2d22b3d642995704ea8df94f1816 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 13:57:52 -0800 Subject: [PATCH 14/19] Add missing flag 4 behavior changes to the changelog List the flag 4 effects that users can see but the fragment left out: external and child signals, handle cancel after a result, all_handlers_finished(), job failures during apply, Python 3.11 timeout rounding, and handler waits after cancellation. Also add a reminder to name the minimum replay version when flag 4 becomes a default. Refs SDK-605. Co-Authored-By: Claude Opus 5.5 --- changelog/added/tumbling-job-basket.md | 7 ++++++- temporalio/_workflow_context.py | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/changelog/added/tumbling-job-basket.md b/changelog/added/tumbling-job-basket.md index 1c96ceeb1b..0058eed603 100644 --- a/changelog/added/tumbling-job-basket.md +++ b/changelog/added/tumbling-job-basket.md @@ -1 +1,6 @@ -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. Cancellation also takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task as the cancellation. Unlike flag 2, flag 4 cancels only the task that receives the cancellation, so a shielded `workflow.wait_condition` can finish. The flag remains disabled by default in this release. +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. Cancellation also takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task as the cancellation. Unlike flag 2, flag 4 cancels only the task that receives the cancellation. A shielded `workflow.wait_condition`, or a wait in a signal or update handler, can therefore finish after cancellation. The flag remains disabled by default in this release. +With flag 4, a signal to an external or child workflow raises `CancelledError` if it completes in the same workflow task as a workflow cancellation. Before, the signal call returned and the workflow did not see the cancellation. +With flag 4, user code can cancel a child workflow or Nexus operation handle in the same workflow task as its result. Awaiting that handle then raises `CancelledError` instead of returning the result. +With flag 4, `workflow.all_handlers_finished()` can return `False` in the workflow task in which a handler finishes. To wait for handlers to finish, use `await workflow.wait_condition(workflow.all_handlers_finished)`. +With flag 4, a job can fail while the worker applies it, for example when a payload decode error fails the workflow. Signal handlers delivered in the same workflow task then do not run. +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 47d9ef5621..a0315545c7 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -38,6 +38,10 @@ class _WorkflowLogicFlag(IntEnum): # cancellation, send a cancel request to it. Flag 2 sends none. # Added on 2026-11-30. # Not enabled by default. + # TODO: When a release enables this flag by default, name in its changelog + # the minimum SDK version that can replay histories with this flag. An older + # SDK can replay them with different results and no nondeterminism error. + # Then remove this reminder. APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4 From 282c4464c7b36ac89cc387f171b85503f31393c7 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 14:10:34 -0800 Subject: [PATCH 15/19] Make the flag 4 changelog entries more precise Address review findings on the flag 4 fragment: - Split the first entry into three entries. - Name the exact call or handler that each entry affects. - Add update handlers to the job failure entry. - Name asyncio.CancelledError. - Follow the existing flag reminder form in the TODO. Refs SDK-605. Co-Authored-By: Claude Opus 5.5 --- changelog/added/tumbling-job-basket.md | 14 ++++++++------ temporalio/_workflow_context.py | 9 +++++---- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/changelog/added/tumbling-job-basket.md b/changelog/added/tumbling-job-basket.md index 0058eed603..3ecf15c76f 100644 --- a/changelog/added/tumbling-job-basket.md +++ b/changelog/added/tumbling-job-basket.md @@ -1,6 +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. Cancellation also takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task as the cancellation. Unlike flag 2, flag 4 cancels only the task that receives the cancellation. A shielded `workflow.wait_condition`, or a wait in a signal or update handler, can therefore finish after cancellation. The flag remains disabled by default in this release. -With flag 4, a signal to an external or child workflow raises `CancelledError` if it completes in the same workflow task as a workflow cancellation. Before, the signal call returned and the workflow did not see the cancellation. -With flag 4, user code can cancel a child workflow or Nexus operation handle in the same workflow task as its result. Awaiting that handle then raises `CancelledError` instead of returning the result. -With flag 4, `workflow.all_handlers_finished()` can return `False` in the workflow task in which a handler finishes. To wait for handlers to finish, use `await workflow.wait_condition(workflow.all_handlers_finished)`. -With flag 4, a job can fail while the worker applies it, for example when a payload decode error fails the workflow. Signal handlers delivered in the same workflow task then do not run. -With flag 4 on Python 3.11, `workflow.wait_condition` timeouts round to the nearest millisecond, as on Python 3.12 and later. +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 a0315545c7..e35b6d6e65 100644 --- a/temporalio/_workflow_context.py +++ b/temporalio/_workflow_context.py @@ -38,10 +38,11 @@ class _WorkflowLogicFlag(IntEnum): # cancellation, send a cancel request to it. Flag 2 sends none. # Added on 2026-11-30. # Not enabled by default. - # TODO: When a release enables this flag by default, name in its changelog - # the minimum SDK version that can replay histories with this flag. An older - # SDK can replay them with different results and no nondeterminism error. - # Then remove this reminder. + # 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 From bb07afdb6592ff649358aa61fb85de57dcb84e35 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 14:13:30 -0800 Subject: [PATCH 16/19] Keep flag 2 out of runs that use flag 4 The worker checked flag 2 before flag 4. A worker with flag 2 as a default then recorded flag 2 on a run whose history holds flag 4, and the run changed to flag 2 behavior. Check flag 4 first when history does not hold flag 2, and check flag 2 last. A new run on a worker with both flags as defaults now records flag 4. Refs SDK-606. Co-Authored-By: Claude Opus 5.5 --- temporalio/worker/_workflow_instance.py | 14 ++- tests/worker/test_workflow.py | 142 ++++++++++++++++++++++-- 2 files changed, 142 insertions(+), 14 deletions(-) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index cfbe2b2ade..c8c79c2169 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -510,17 +510,23 @@ 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_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._apply_jobs_first_flag = ( - not self._single_batch_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 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 diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index b58ca2df2a..165c08682d 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1808,25 +1808,30 @@ def state(self) -> tuple[bool, bool]: @pytest.mark.parametrize("timeout", [False, True]) @pytest.mark.parametrize( - ("original_single_batch", "cleanup_completes"), + ("flags", "cleanup_completes"), [ - pytest.param(False, True, id="task-cancellation"), - pytest.param(True, False, id="original-behavior-preserved"), + pytest.param( + [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], True, id="task-cancellation" + ), + pytest.param( + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], False, id="original-single-batch" + ), + pytest.param( + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + True, + id="both-flags", + ), ], ) async def test_workflow_shielded_wait_condition_after_cancel( client: Client, timeout: bool, - original_single_batch: bool, + flags: list[_WorkflowLogicFlag], cleanup_completes: bool, ) -> None: worker = new_worker(client, ShieldedWaitConditionWorkflow) - worker._set_default_workflow_logic_flag( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=original_single_batch - ) - worker._set_default_workflow_logic_flag( - _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=True - ) + for flag in flags: + worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: handle = await client.start_workflow( ShieldedWaitConditionWorkflow.run, @@ -1865,6 +1870,123 @@ async def state() -> tuple[bool, bool]: 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) + return f"handler-{self._handler}" + + @workflow.signal + async def start_handler(self) -> None: + self._handler = "waiting" + try: + await workflow.wait_condition(lambda: self._release) + except asyncio.CancelledError: + self._handler = "CancelledError" + return + self._handler = "returned" + + @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_flag", "later_flags", "expected"), + [ + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], + "handler-returned", + id="task-cancellation-then-original", + ), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "handler-returned", + id="task-cancellation-then-both", + ), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, + [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "handler-CancelledError", + id="original-then-task-cancellation", + ), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, + [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], + "handler-CancelledError", + id="original-then-both", + ), + ], +) +async def test_workflow_logic_flag_kept_after_worker_flags_change( + client: Client, + first_flag: _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, + ) + await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler) + + async def state() -> tuple[str, bool]: + return await handle.query(HandlerWaitConditionAfterCancelWorkflow.state) + + def flag_worker(flags: list[_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 flags: + worker._set_default_workflow_logic_flag(flag, enabled=True) + return worker + + async with flag_worker([first_flag]): + await assert_eq_eventually(("waiting", False), state) + + async with flag_worker(later_flags): + await handle.cancel() + await assert_eq_eventually(("waiting", True), state) + await handle.signal(HandlerWaitConditionAfterCancelWorkflow.release) + assert await handle.result() == expected + + # The flag that the first task recorded decides the behavior of the run. + history = await handle.fetch_history() + assert { + 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 + } == {first_flag} + await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow( + history + ) + + @workflow.defn class CompleteChildOnSignalWorkflow: def __init__(self) -> None: From bfae0e5f21e763bba7a5c1d1524c3f36c628611f Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 14:36:24 -0800 Subject: [PATCH 17/19] Tighten the flag precedence tests Address review findings on the flag precedence tests: - Start the handler wait on the second worker, so the result shows which flag the run uses. - Compare the full set of recorded flags. - Set both flags explicitly on each worker. - Remove cases that run the same code path. Refs SDK-606. Co-Authored-By: Claude Opus 5.5 --- temporalio/worker/_workflow_instance.py | 4 +- tests/worker/test_workflow.py | 124 ++++++++++-------------- 2 files changed, 53 insertions(+), 75 deletions(-) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index c8c79c2169..d6a267d364 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -519,8 +519,8 @@ def _activate( _WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS ) ) - # Check the original flag last, so a run that uses the newer flag never - # records it. + # 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( diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 165c08682d..e345e50fd5 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -70,6 +70,7 @@ WorkflowExecutionStatus, WorkflowFailureError, WorkflowHandle, + WorkflowHistory, WorkflowQueryFailedError, WorkflowUpdateFailedError, WorkflowUpdateHandle, @@ -1536,6 +1537,15 @@ async def run(self) -> str: ) +def _recorded_workflow_logic_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 + } + + @pytest.mark.parametrize( "flag", [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG] ) @@ -1807,31 +1817,18 @@ def state(self) -> tuple[bool, bool]: @pytest.mark.parametrize("timeout", [False, True]) -@pytest.mark.parametrize( - ("flags", "cleanup_completes"), - [ - pytest.param( - [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], True, id="task-cancellation" - ), - pytest.param( - [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], False, id="original-single-batch" - ), - pytest.param( - [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], - True, - id="both-flags", - ), - ], -) +@pytest.mark.parametrize("task_cancellation", [False, True]) async def test_workflow_shielded_wait_condition_after_cancel( - client: Client, - timeout: bool, - flags: list[_WorkflowLogicFlag], - cleanup_completes: bool, + client: Client, timeout: bool, task_cancellation: bool ) -> None: worker = new_worker(client, ShieldedWaitConditionWorkflow) - for flag in flags: - worker._set_default_workflow_logic_flag(flag, enabled=True) + # 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, @@ -1857,16 +1854,13 @@ async def state() -> tuple[bool, bool]: event.event_type == EventType.EVENT_TYPE_TIMER_FIRED for event in history.events ) - is cleanup_completes - ) - assert ( - any( - _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG - in event.workflow_task_completed_event_attributes.sdk_metadata.lang_used_flags - for event in history.events - ) - is cleanup_completes + is task_cancellation ) + assert _recorded_workflow_logic_flags(history) == { + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG + if task_cancellation + else _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG + } await Replayer(workflows=[ShieldedWaitConditionWorkflow]).replay_workflow(history) @@ -1884,17 +1878,16 @@ async def run(self) -> str: except asyncio.CancelledError: self._caught_cancel = True await workflow.wait_condition(workflow.all_handlers_finished) - return f"handler-{self._handler}" + 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 = "CancelledError" - return - self._handler = "returned" + self._handler = "cancelled" @workflow.signal def release(self) -> None: @@ -1906,39 +1899,20 @@ def state(self) -> tuple[str, bool]: @pytest.mark.parametrize( - ("first_flag", "later_flags", "expected"), + ("first_flag", "expected"), [ pytest.param( _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, - [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG], - "handler-returned", - id="task-cancellation-then-original", + "returned", + id="batching-with-task-cancellation", ), pytest.param( - _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, - [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], - "handler-returned", - id="task-cancellation-then-both", - ), - pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, - [_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], - "handler-CancelledError", - id="original-then-task-cancellation", - ), - pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, - [_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG], - "handler-CancelledError", - id="original-then-both", + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, "cancelled", id="original-single-batch" ), ], ) async def test_workflow_logic_flag_kept_after_worker_flags_change( - client: Client, - first_flag: _WorkflowLogicFlag, - later_flags: list[_WorkflowLogicFlag], - expected: str, + client: Client, first_flag: _WorkflowLogicFlag, expected: str ) -> None: task_queue = str(uuid.uuid4()) handle = await client.start_workflow( @@ -1946,12 +1920,11 @@ async def test_workflow_logic_flag_kept_after_worker_flags_change( id=f"workflow-{uuid.uuid4()}", task_queue=task_queue, ) - await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler) async def state() -> tuple[str, bool]: return await handle.query(HandlerWaitConditionAfterCancelWorkflow.state) - def flag_worker(flags: list[_WorkflowLogicFlag]) -> Worker: + def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: worker = new_worker( client, HandlerWaitConditionAfterCancelWorkflow, @@ -1961,27 +1934,32 @@ def flag_worker(flags: list[_WorkflowLogicFlag]) -> Worker: # worker stops on the normal queue. max_cached_workflows=0, ) - for flag in flags: - worker._set_default_workflow_logic_flag(flag, enabled=True) + 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_flag]): - await assert_eq_eventually(("waiting", False), state) + async with flag_worker(first_flag): + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED] + ) - async with flag_worker(later_flags): + # The handler wait starts on this worker, so its result shows which flag + # the run uses after the worker defaults change. + async with flag_worker( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG + ): + 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 - # The flag that the first task recorded decides the behavior of the run. history = await handle.fetch_history() - assert { - 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 - } == {first_flag} + assert _recorded_workflow_logic_flags(history) == {first_flag} await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow( history ) From 7f1e9dfbc899746391348ba33de3d9704c98c731 Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 15:02:08 -0800 Subject: [PATCH 18/19] Add missing flag 4 tests Add tests that run with no flag, flag 2 and flag 4: - A Nexus operation result and a workflow cancellation in one activation. - An external signal and a workflow cancellation in one activation. - A signal handler wait after workflow cancellation on one worker. Also run the test for a flag first enabled on a later task with flag 4. The child start test now ends its hold when the cancellation arrives, so a regression fails instead of hanging. Refs SDK-607. Co-Authored-By: Claude Opus 5.5 --- ...rkflow_caller_cancel_in_same_activation.py | 171 ++++++++++++++++-- tests/worker/test_workflow.py | 158 +++++++++++++--- 2 files changed, 285 insertions(+), 44 deletions(-) diff --git a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py index 57aefc1953..e71e297185 100644 --- a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -6,13 +6,17 @@ 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.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 +from tests.worker.test_workflow import ( + CompleteChildOnSignalWorkflow, + CustomWorkflowRunner, + WaitForCancelWorkflow, +) # Cloud CI's namespace credentials cannot manage Nexus endpoints. # See https://github.com/temporalio/sdk-python/issues/1704. @@ -28,6 +32,37 @@ async def wait_for_cancel( return await ctx.start_workflow(WaitForCancelWorkflow.run, id=workflow_id) +@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( + CompleteChildOnSignalWorkflow.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 @@ -71,26 +106,15 @@ async def test_workflow_cancel_and_operation_start_in_same_activation( 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(): + async with caller_worker( + env.client, CancelAtOperationStartWorkflow, caller_task_queue, runner, flag + ): await assert_event_subsequence( handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED] ) @@ -107,7 +131,9 @@ def caller_worker() -> Worker: handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED] ) await handle.cancel() - async with caller_worker(): + 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) @@ -132,3 +158,114 @@ def caller_worker() -> Worker: is operation_cancel_requested ) await Replayer(workflows=[CancelAtOperationStartWorkflow]).replay_workflow(history) + + +@workflow.defn +class CancelAtOperationResultWorkflow: + @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", "result_cancelled"), + [ + pytest.param(None, False, id="no-flag"), + pytest.param( + _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH, + True, + 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_result_in_same_activation( + env: WorkflowEnvironment, + flag: _WorkflowLogicFlag | None, + result_cancelled: 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() + + async with new_worker( + env.client, + CompleteChildOnSignalWorkflow, + task_queue=handler_task_queue, + nexus_service_handlers=[CompleteOnSignalService()], + ): + handle = await env.client.start_workflow( + CancelAtOperationResultWorkflow.run, + endpoint, + id=f"workflow-{uuid.uuid4()}", + task_queue=caller_task_queue, + ) + async with caller_worker( + env.client, + CancelAtOperationResultWorkflow, + 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( + CompleteChildOnSignalWorkflow.finish + ) + await assert_event_subsequence( + handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED] + ) + await handle.cancel() + async with caller_worker( + env.client, + CancelAtOperationResultWorkflow, + caller_task_queue, + runner, + flag, + ): + if result_cancelled: + with pytest.raises(WorkflowFailureError) as err: + await handle.result() + assert isinstance(err.value.cause, CancelledError) + else: + assert await handle.result() == "child complete" + + 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=[CancelAtOperationResultWorkflow]).replay_workflow( + await handle.fetch_history() + ) diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index e345e50fd5..76da81f57c 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1576,7 +1576,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, @@ -1594,9 +1605,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: @@ -1613,17 +1622,14 @@ 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 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 + and flag in completion.successful.used_internal_flags for activation, completion in runner._pairs ) @@ -1633,10 +1639,8 @@ 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) @@ -1899,20 +1903,41 @@ def state(self) -> tuple[str, bool]: @pytest.mark.parametrize( - ("first_flag", "expected"), + ("first_flags", "later_flags", "expected"), [ + pytest.param([], [], "returned", id="no-flag"), pytest.param( - _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + [_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", ), + # After the first task, the flag in history decides the behavior. pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, "cancelled", id="original-single-batch" + [_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_logic_flag_kept_after_worker_flags_change( - client: Client, first_flag: _WorkflowLogicFlag, expected: str +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( @@ -1941,16 +1966,14 @@ def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: worker._set_default_workflow_logic_flag(flag, enabled=flag in flags) return worker - async with flag_worker(first_flag): + async with flag_worker(*first_flags): await assert_event_subsequence( handle, [EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED] ) # The handler wait starts on this worker, so its result shows which flag # the run uses after the worker defaults change. - async with flag_worker( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG - ): + async with flag_worker(*later_flags): await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler) await assert_eq_eventually(("waiting", False), state) await handle.cancel() @@ -1959,7 +1982,7 @@ def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: assert await handle.result() == expected history = await handle.fetch_history() - assert _recorded_workflow_logic_flags(history) == {first_flag} + assert _recorded_workflow_logic_flags(history) == set(first_flags) await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow( history ) @@ -2108,10 +2131,10 @@ async def run(self, child_task_queue: str) -> None: 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") + 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( @@ -2202,6 +2225,87 @@ async def test_workflow_cancel_and_child_start_in_same_activation( await Replayer(workflows=[CancelAtChildStartWorkflow]).replay_workflow(history) +@workflow.defn +class CancelAtExternalSignalWorkflow: + @workflow.run + async def run(self, target_id: str) -> str: + try: + await workflow.get_external_workflow_handle(target_id).signal("unhandled") + except asyncio.CancelledError: + return "cancelled" + 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", "expected"), + [ + pytest.param(None, "returned", id="no-flag"), + pytest.param( + _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, "cancelled", id="original-single-batch" + ), + pytest.param( + _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, + "cancelled", + id="batching-with-task-cancellation", + ), + ], +) +async def test_workflow_cancel_and_external_signal_in_same_activation( + client: Client, + env: WorkflowEnvironment, + flag: _WorkflowLogicFlag | None, + expected: str, +): + 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( + WaitForCancelWorkflow.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() + assert await handle.result() == expected + + if flag is not None: + assert any( + flag in completion.successful.used_internal_flags + for _, completion in runner._pairs + ) + assert any( + {"resolve_signal_external_workflow", "cancel_workflow"}.issubset( + {job.WhichOneof("variant") for job in activation.jobs} + ) + for activation, _ in runner._pairs + ) + await Replayer(workflows=[CancelAtExternalSignalWorkflow]).replay_workflow( + await handle.fetch_history() + ) + + @activity.defn async def wait_forever() -> NoReturn: await asyncio.Future() From dbfcd227967ce426e0e4cc53494f96c675769d8f Mon Sep 17 00:00:00 2001 From: Alex Mazzeo Date: Wed, 2 Dec 2026 15:25:01 -0800 Subject: [PATCH 19/19] Make the flag 4 tests catch replay regressions Address review findings on the new flag 4 tests: - Give each outcome different commands, so replay detects a wrong flag decision. - Use a condition and timeout race in the later task test, so the result shows that the flag takes effect there. - Compare only the two batching flags in recorded flag sets. - Name the Nexus helpers and handler workflow for their role. Refs SDK-607. Co-Authored-By: Claude Opus 5.5 --- ...rkflow_caller_cancel_in_same_activation.py | 72 +++++++++++-------- tests/worker/test_workflow.py | 69 +++++++++--------- 2 files changed, 79 insertions(+), 62 deletions(-) diff --git a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py index e71e297185..76685ce7d3 100644 --- a/tests/nexus/test_workflow_caller_cancel_in_same_activation.py +++ b/tests/nexus/test_workflow_caller_cancel_in_same_activation.py @@ -1,4 +1,5 @@ import uuid +from datetime import timedelta import nexusrpc.handler import pytest @@ -12,11 +13,7 @@ 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 ( - CompleteChildOnSignalWorkflow, - CustomWorkflowRunner, - WaitForCancelWorkflow, -) +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. @@ -32,6 +29,21 @@ async def wait_for_cancel( 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 @@ -39,11 +51,11 @@ async def complete_on_signal( self, ctx: nexus.WorkflowRunOperationContext, workflow_id: str ) -> nexus.WorkflowHandle[str]: return await ctx.start_workflow( - CompleteChildOnSignalWorkflow.run, id=workflow_id + CompleteOnSignalOperationWorkflow.run, id=workflow_id ) -def caller_worker( +def _caller_worker( client: Client, workflow_class: type, task_queue: str, @@ -112,7 +124,7 @@ async def test_workflow_cancel_and_operation_start_in_same_activation( id=f"workflow-{uuid.uuid4()}", task_queue=caller_task_queue, ) - async with caller_worker( + async with _caller_worker( env.client, CancelAtOperationStartWorkflow, caller_task_queue, runner, flag ): await assert_event_subsequence( @@ -131,7 +143,7 @@ async def test_workflow_cancel_and_operation_start_in_same_activation( handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED] ) await handle.cancel() - async with caller_worker( + async with _caller_worker( env.client, CancelAtOperationStartWorkflow, caller_task_queue, runner, flag ): with pytest.raises(WorkflowFailureError) as err: @@ -161,7 +173,7 @@ async def test_workflow_cancel_and_operation_start_in_same_activation( @workflow.defn -class CancelAtOperationResultWorkflow: +class CancelAtOperationCompletionWorkflow: @workflow.run async def run(self, endpoint: str) -> str: nexus_client = workflow.create_nexus_client( @@ -175,25 +187,21 @@ async def run(self, endpoint: str) -> str: @pytest.mark.parametrize( - ("flag", "result_cancelled"), + "flag", [ - pytest.param(None, False, id="no-flag"), + pytest.param(None, id="no-flag"), pytest.param( _WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH, - True, 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_result_in_same_activation( - env: WorkflowEnvironment, - flag: _WorkflowLogicFlag | None, - result_cancelled: bool, +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") @@ -206,19 +214,19 @@ async def test_workflow_cancel_and_operation_result_in_same_activation( async with new_worker( env.client, - CompleteChildOnSignalWorkflow, + CompleteOnSignalOperationWorkflow, task_queue=handler_task_queue, nexus_service_handlers=[CompleteOnSignalService()], ): handle = await env.client.start_workflow( - CancelAtOperationResultWorkflow.run, + CancelAtOperationCompletionWorkflow.run, endpoint, id=f"workflow-{uuid.uuid4()}", task_queue=caller_task_queue, ) - async with caller_worker( + async with _caller_worker( env.client, - CancelAtOperationResultWorkflow, + CancelAtOperationCompletionWorkflow, caller_task_queue, runner, flag, @@ -235,25 +243,29 @@ async def test_workflow_cancel_and_operation_result_in_same_activation( # 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( - CompleteChildOnSignalWorkflow.finish + CompleteOnSignalOperationWorkflow.finish ) + # A server callback delivers the completion to the caller. await assert_event_subsequence( - handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED] + handle, + [EventType.EVENT_TYPE_NEXUS_OPERATION_COMPLETED], + timeout=timedelta(seconds=10), ) await handle.cancel() - async with caller_worker( + async with _caller_worker( env.client, - CancelAtOperationResultWorkflow, + CancelAtOperationCompletionWorkflow, caller_task_queue, runner, flag, ): - if result_cancelled: + 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) - else: - assert await handle.result() == "child complete" if flag is not None: assert any( @@ -266,6 +278,6 @@ async def test_workflow_cancel_and_operation_result_in_same_activation( ) for activation, _ in runner._pairs ) - await Replayer(workflows=[CancelAtOperationResultWorkflow]).replay_workflow( + await Replayer(workflows=[CancelAtOperationCompletionWorkflow]).replay_workflow( await handle.fetch_history() ) diff --git a/tests/worker/test_workflow.py b/tests/worker/test_workflow.py index 76da81f57c..d9c3315742 100644 --- a/tests/worker/test_workflow.py +++ b/tests/worker/test_workflow.py @@ -1537,12 +1537,14 @@ async def run(self) -> str: ) -def _recorded_workflow_logic_flags(history: WorkflowHistory) -> set[int]: +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) } @@ -1564,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: @@ -1613,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() @@ -1624,14 +1634,9 @@ async def ready() -> bool: ) 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 flag in completion.successful.used_internal_flags - for activation, completion in runner._pairs - ) history = await handle.fetch_history() workflow_task_flags = [ @@ -1860,7 +1865,7 @@ async def state() -> tuple[bool, bool]: ) is task_cancellation ) - assert _recorded_workflow_logic_flags(history) == { + assert _recorded_batching_flags(history) == { _APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG if task_cancellation else _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG @@ -1882,6 +1887,9 @@ async def run(self) -> str: 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 @@ -1918,7 +1926,8 @@ def state(self) -> tuple[str, bool]: "returned", id="batching-with-task-cancellation", ), - # After the first task, the flag in history decides the behavior. + # 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], @@ -1971,8 +1980,6 @@ def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: handle, [EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED] ) - # The handler wait starts on this worker, so its result shows which flag - # the run uses after the worker defaults change. async with flag_worker(*later_flags): await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler) await assert_eq_eventually(("waiting", False), state) @@ -1982,7 +1989,7 @@ def flag_worker(*flags: _WorkflowLogicFlag) -> Worker: assert await handle.result() == expected history = await handle.fetch_history() - assert _recorded_workflow_logic_flags(history) == set(first_flags) + assert _recorded_batching_flags(history) == set(first_flags) await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow( history ) @@ -2229,10 +2236,9 @@ async def test_workflow_cancel_and_child_start_in_same_activation( class CancelAtExternalSignalWorkflow: @workflow.run async def run(self, target_id: str) -> str: - try: - await workflow.get_external_workflow_handle(target_id).signal("unhandled") - except asyncio.CancelledError: - return "cancelled" + 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. @@ -2241,24 +2247,17 @@ async def run(self, target_id: str) -> str: @pytest.mark.parametrize( - ("flag", "expected"), + "flag", [ - pytest.param(None, "returned", id="no-flag"), - pytest.param( - _SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, "cancelled", id="original-single-batch" - ), + 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, - "cancelled", - id="batching-with-task-cancellation", + _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, - expected: str, + client: Client, env: WorkflowEnvironment, flag: _WorkflowLogicFlag | None ): if env.supports_time_skipping_v1: pytest.skip( @@ -2270,7 +2269,7 @@ async def test_workflow_cancel_and_external_signal_in_same_activation( worker._set_default_workflow_logic_flag(flag, enabled=True) async with worker: target = await client.start_workflow( - WaitForCancelWorkflow.run, + CompleteChildOnSignalWorkflow.run, id=f"workflow-{uuid.uuid4()}", # No worker polls this queue, so the target keeps running. task_queue=str(uuid.uuid4()), @@ -2288,7 +2287,13 @@ async def test_workflow_cancel_and_external_signal_in_same_activation( handle, message_contains="Intentional task failure" ) await handle.cancel() - assert await handle.result() == expected + 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(