Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions temporalio/_workflow_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 53 additions & 28 deletions temporalio/worker/_workflow_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
)
Expand All @@ -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):
Expand Down Expand Up @@ -2266,6 +2264,11 @@ async def _outbound_start_child_workflow(
def apply_child_cancel_error(
err: asyncio.CancelledError,
) -> None:
if self._apply_jobs_first_flag and handle._result_fut.done():
# Core fails the task on a cancel for a terminated child, and a
# child with a result needs no cancel. Without flag 4, keep the
# old commands.
return
cancel_command = self._add_command()
# Send a cancel request to the child, forwarding the msg passed to
# Task.cancel(msg) (if any) as the cancellation reason.
Expand Down Expand Up @@ -2303,7 +2306,7 @@ async def run_child() -> Any:
await self._await_temporal_operation(
handle._start_fut,
apply_child_cancel_error,
reraise_on_workflow_cancellation=True,
is_start=True,
)
return handle

Expand Down Expand Up @@ -2380,7 +2383,7 @@ async def operation_handle_fn() -> OutputT:
await self._await_temporal_operation(
handle._start_fut,
lambda _err: handle._apply_cancel_command(self._add_command()),
reraise_on_workflow_cancellation=True,
is_start=True,
)
return handle

Expand Down Expand Up @@ -2432,7 +2435,7 @@ async def _await_temporal_operation(
],
*,
completed_cancellation_flag: _WorkflowLogicFlag | None = None,
reraise_on_workflow_cancellation: bool = False,
is_start: bool = False,
) -> _T:
while True:
try:
Expand All @@ -2441,19 +2444,16 @@ async def _await_temporal_operation(
# custom shield also avoids spurious error logs on Python 3.11+.
return await _shield_await(fut)
except asyncio.CancelledError as err:
if fut.done():
# Retrying the shield after both futures become ready would
# return the result and erase the task cancellation.
if self._legacy_single_batch or self._preserve_task_cancellation:
raise
if completed_cancellation_flag is not None and (
not self._is_replaying
or completed_cancellation_flag in self._current_internal_flags
):
self._current_completion.successful.used_internal_flags.append(
completed_cancellation_flag
)
raise
# Retrying the shield after both futures become ready would
# return the result and erase the task cancellation.
if fut.done() and self._cancellation_wins_over_result(
completed_cancellation_flag
):
if is_start and self._apply_jobs_first_flag:
# A start that raises gives the caller no handle, so
# the caller cannot cancel the operation itself.
apply_cancel(err)
raise

apply_cancel(err)

Expand All @@ -2462,9 +2462,7 @@ async def _await_temporal_operation(
if (task := asyncio.current_task()) is not None:
task.uncancel()

if reraise_on_workflow_cancellation and (
self._cancel_reason is not None or self._deleting
):
if is_start and (self._cancel_reason is not None or self._deleting):
raise

async def _cancel_external_workflow(
Expand All @@ -2483,6 +2481,33 @@ async def _cancel_external_workflow(
# Wait until done (there is no cancelling a cancel request)
await done_fut

def _cancellation_wins_over_result(
self, completed_cancellation_flag: _WorkflowLogicFlag | None
) -> bool:
"""Decide whether a task cancellation wins over a result that is ready.

The caller uses this when its task is cancelled after the operation
result is already available. True means the caller must raise the
cancellation. False means the caller sends the cancel request and can
still return the result, which is the legacy behavior.

Flag 2 and flag 4 always give the cancellation priority. Otherwise,
``completed_cancellation_flag`` (flag 1 for activities) gives it
priority. On a new workflow task this call records that flag. On replay
the flag applies only if history holds it.
"""
if self._single_batch_flag or self._apply_jobs_first_flag:
return True
if completed_cancellation_flag is None or (
self._is_replaying
and completed_cancellation_flag not in self._current_internal_flags
):
return False
self._current_completion.successful.used_internal_flags.append(
completed_cancellation_flag
)
return True

def _check_condition(self, fn: Callable[[], bool], fut: asyncio.Future) -> bool:
if fn():
fut.set_result(True)
Expand Down
134 changes: 134 additions & 0 deletions tests/nexus/test_workflow_caller_cancel_in_same_activation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
import uuid

import nexusrpc.handler
import pytest

from temporalio import nexus, workflow
from temporalio._workflow_context import _WorkflowLogicFlag
from temporalio.api.enums.v1 import EventType
from temporalio.client import WorkflowFailureError
from temporalio.exceptions import CancelledError
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Replayer, Worker
from tests.helpers import assert_event_subsequence, new_worker
from tests.helpers.nexus import make_nexus_endpoint_name
from tests.worker.test_workflow import CustomWorkflowRunner, WaitForCancelWorkflow

# Cloud CI's namespace credentials cannot manage Nexus endpoints.
# See https://github.com/temporalio/sdk-python/issues/1704.
pytestmark = pytest.mark.requires_local_server


@nexusrpc.handler.service_handler
class WaitForCancelService:
@nexus.workflow_run_operation
async def wait_for_cancel(
self, ctx: nexus.WorkflowRunOperationContext, workflow_id: str
) -> nexus.WorkflowHandle[None]:
return await ctx.start_workflow(WaitForCancelWorkflow.run, id=workflow_id)


@workflow.defn
class CancelAtOperationStartWorkflow:
@workflow.run
async def run(self, endpoint: str) -> None:
nexus_client = workflow.create_nexus_client(
service=WaitForCancelService, endpoint=endpoint
)
await nexus_client.start_operation(
WaitForCancelService.wait_for_cancel,
f"{workflow.info().workflow_id}-operation",
)


@pytest.mark.parametrize(
("flag", "operation_cancel_requested"),
[
pytest.param(None, True, id="no-flag"),
pytest.param(
_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH,
False,
id="original-single-batch",
),
pytest.param(
_WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS,
True,
id="batching-with-task-cancellation",
),
],
)
async def test_workflow_cancel_and_operation_start_in_same_activation(
env: WorkflowEnvironment,
flag: _WorkflowLogicFlag | None,
operation_cancel_requested: bool,
) -> None:
if env.supports_time_skipping_v1:
pytest.skip("Nexus tests don't work with time-skipping server")

caller_task_queue = str(uuid.uuid4())
handler_task_queue = str(uuid.uuid4())
endpoint = make_nexus_endpoint_name(handler_task_queue)
await env.create_nexus_endpoint(endpoint, handler_task_queue)
runner = CustomWorkflowRunner()

def caller_worker() -> Worker:
worker = new_worker(
env.client,
CancelAtOperationStartWorkflow,
task_queue=caller_task_queue,
workflow_runner=runner,
# Keep tasks on the normal queue, which the next worker polls.
max_cached_workflows=0,
)
if flag is not None:
worker._set_default_workflow_logic_flag(flag, enabled=True)
return worker

handle = await env.client.start_workflow(
CancelAtOperationStartWorkflow.run,
endpoint,
id=f"workflow-{uuid.uuid4()}",
task_queue=caller_task_queue,
)
async with caller_worker():
await assert_event_subsequence(
handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_SCHEDULED]
)

# The operation starts only after the caller worker stops, so the start
# and the cancellation reach the caller in one activation.
async with new_worker(
env.client,
WaitForCancelWorkflow,
task_queue=handler_task_queue,
nexus_service_handlers=[WaitForCancelService()],
):
await assert_event_subsequence(
handle, [EventType.EVENT_TYPE_NEXUS_OPERATION_STARTED]
)
await handle.cancel()
async with caller_worker():
with pytest.raises(WorkflowFailureError) as err:
await handle.result()
assert isinstance(err.value.cause, CancelledError)

if flag is not None:
assert any(
flag in completion.successful.used_internal_flags
for _, completion in runner._pairs
)
assert any(
{"resolve_nexus_operation_start", "cancel_workflow"}.issubset(
{job.WhichOneof("variant") for job in activation.jobs}
)
for activation, _ in runner._pairs
)
history = await handle.fetch_history()
assert (
any(
event.event_type == EventType.EVENT_TYPE_NEXUS_OPERATION_CANCEL_REQUESTED
for event in history.events
)
is operation_cancel_requested
)
await Replayer(workflows=[CancelAtOperationStartWorkflow]).replay_workflow(history)
Loading
Loading