Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
b4c0f81
Add batching-only workflow logic flag
VegetarianOrc Nov 19, 2026
0ac7e28
Name batching flag for activation ordering
VegetarianOrc Nov 19, 2026
e1277e8
Add activation batching changelog fragment
VegetarianOrc Nov 21, 2026
6e409ef
Gate task-local wait condition cancellation
VegetarianOrc Nov 19, 2026
4dc7c35
Share cancellation fixes across workflow logic flags
VegetarianOrc Nov 19, 2026
8449626
Name flag for preserving task cancellation
VegetarianOrc Nov 19, 2026
26f6f8b
Clarify task cancellation changelog fragment
VegetarianOrc Nov 21, 2026
e63a750
Document legacy single-batch flag rollout
VegetarianOrc Nov 21, 2026
64c5ad2
Combine activation batching and task cancellation flags
VegetarianOrc Dec 1, 2026
e6e2a6d
Cancel a started child or Nexus operation on start cancellation
VegetarianOrc Dec 2, 2026
2013a05
Skip the cancel for a child that already resolved
VegetarianOrc Dec 2, 2026
88f51cd
Clarify flag names in operation cancellation
VegetarianOrc Dec 3, 2026
05dd78e
Document when a cancellation wins over a ready result
VegetarianOrc Dec 3, 2026
61ae7ca
Add missing flag 4 behavior changes to the changelog
VegetarianOrc Dec 2, 2026
282c446
Make the flag 4 changelog entries more precise
VegetarianOrc Dec 2, 2026
bb07afd
Keep flag 2 out of runs that use flag 4
VegetarianOrc Dec 2, 2026
bfae0e5
Tighten the flag precedence tests
VegetarianOrc Dec 2, 2026
7f1e9df
Add missing flag 4 tests
VegetarianOrc Dec 2, 2026
dbfcd22
Make the flag 4 tests catch replay regressions
VegetarianOrc Dec 2, 2026
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
8 changes: 8 additions & 0 deletions changelog/added/tumbling-job-basket.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
Add flag-controlled workflow activation processing (workflow logic flag 4). With the flag, signal and update handlers no longer run before other jobs delivered in the same workflow task. The flag remains disabled by default in this release.
With flag 4, cancellation takes priority over a condition, child workflow result or Nexus operation result that becomes ready in the same workflow task.
Unlike flag 2, flag 4 cancels only the task that receives the cancellation. A `workflow.wait_condition()` call that is shielded or in another task, such as a signal or update handler, can therefore finish after cancellation.
With flag 4, a signal to an external or child workflow raises `asyncio.CancelledError` when it completes in the same workflow task as a workflow cancellation. Previously, a successful signal call returned and the workflow did not see the cancellation.
With flag 4, cancelling a child workflow or Nexus operation handle in the workflow task that delivers its result can take priority over the result. Awaiting the handle then raises `asyncio.CancelledError` instead of returning the result.
With flag 4, `workflow.all_handlers_finished()` can return `False` more often in the workflow task where a signal handler finishes. Use `await workflow.wait_condition(workflow.all_handlers_finished)` instead.
With flag 4, signal and update handlers do not run if applying another job in the same workflow task fails the workflow.
With flag 4 on Python 3.11, `workflow.wait_condition()` timeouts round to the nearest millisecond, as on Python 3.12 and later.
15 changes: 14 additions & 1 deletion temporalio/_workflow_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -31,6 +31,19 @@ class _WorkflowLogicFlag(IntEnum):
# Remove the explicit overrides for this flag from tests/worker/test_workflow_flags.py
# when enabling it. Then remove this reminder.
DECODE_DATETIME_PROXIES = 3
# Apply all activation jobs before running workflow tasks, as flag 2 does.
# Send cancellation only to the task that receives it. Flag 2 checks for
# cancellation across the workflow, so it also cancels shielded waits.
# When a child workflow or Nexus operation start resolves with the
# cancellation, send a cancel request to it. Flag 2 sends none.
# Added on 2026-11-30.
# Not enabled by default.
# TODO: When enabling APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS by default,
# remove the explicit overrides for this flag from the tests. The changelog
# must also name the minimum SDK version that replays histories with this
# flag, because older SDKs can give different replay results without a
# nondeterminism error. Then remove this reminder.
APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS = 4


_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS: frozenset[_WorkflowLogicFlag] = frozenset()
Expand Down
99 changes: 74 additions & 25 deletions temporalio/worker/_workflow_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,9 +510,26 @@ def _activate(
self._is_replaying = act.is_replaying
self._current_thread_id = threading.get_ident()
self._current_internal_flags = act.available_internal_flags
self._single_batch_activation = self._workflow_logic_flag_enabled(
# Histories that use the original single-batch flag must keep its
# workflow-wide cancellation check, so do not check the newer flag.
self._apply_jobs_first_flag = (
_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH
not in self._current_internal_flags
and self._workflow_logic_flag_enabled(
_WorkflowLogicFlag.APPLY_ACTIVATION_JOBS_BEFORE_RUNNING_TASKS
)
)
# Check the original single-batch flag last, so a run that uses the
# newer flag never records it.
self._single_batch_flag = (
not self._apply_jobs_first_flag
and self._workflow_logic_flag_enabled(
_WorkflowLogicFlag.PROCESS_WORKFLOW_ACTIVATION_JOBS_AS_SINGLE_BATCH
)
)
# Both flags apply all jobs before running tasks. They differ only in
# how they send cancellation.
single_batch_activation = self._single_batch_flag or self._apply_jobs_first_flag
# Check this flag before queries can arrive,
# even when no input needs decoding.
self._workflow_logic_flag_enabled(_WorkflowLogicFlag.DECODE_DATETIME_PROXIES)
Expand Down Expand Up @@ -545,7 +562,7 @@ def _activate(
if start_job:
self._workflow_input = self._make_workflow_input(start_job)

if self._single_batch_activation:
if single_batch_activation:
# Applying every job before giving workflow tasks a chance to
# run prevents their order in the activation from hiding state
# that arrived in the same workflow task.
Expand Down Expand Up @@ -713,7 +730,7 @@ def _apply_cancel_workflow(
# workflow the ability to receive the cancellation, so we must defer
# this cancellation to the next iteration of the event loop.
self.call_soon(self._primary_task.cancel)
elif self._single_batch_activation:
elif self._single_batch_flag or self._apply_jobs_first_flag:
# Initialization is the only job that creates the primary task, so
# retain a same-activation cancellation until that task exists.
self._cancel_primary_task_pending = True
Expand Down Expand Up @@ -2041,7 +2058,7 @@ async def workflow_wait_condition(
# cancellation and keep going.
def cancellation_arrived() -> bool:
return (
self._single_batch_activation
self._single_batch_flag
and not cancellation_requested_before
and self._cancel_reason is not None
)
Expand All @@ -2058,12 +2075,17 @@ def cancellation_arrived() -> bool:
else None
)
markers = _capture_event_group_markers(event_groups)
# asyncio.wait_for() starts its timer from this task, so the options are
# set in the task's context and reset once the wait ends
# Scope the timer options so later timers in this task don't inherit them.
token = _TimerOptionsCtxVar.set(
_TimerOptions(user_metadata=user_metadata, event_group_markers=markers)
)
try:
if self._apply_jobs_first_flag:
# A direct await lets the waiting task arbitrate cancellation
# and readiness without bypassing shielding or using wait_for.
async with asyncio.timeout(timeout):
await fut
return
await asyncio.wait_for(fut, timeout)
except asyncio.TimeoutError:
if cancellation_arrived():
Expand Down Expand Up @@ -2248,6 +2270,11 @@ async def _outbound_start_child_workflow(
def apply_child_cancel_error(
err: asyncio.CancelledError,
) -> None:
if self._apply_jobs_first_flag and handle._result_fut.done():
# Core fails the task on a cancel for a terminated child, and a
# child with a result needs no cancel. Without flag 4, keep the
# old commands.
return
cancel_command = self._add_command()
# Send a cancel request to the child, forwarding the msg passed to
# Task.cancel(msg) (if any) as the cancellation reason.
Expand Down Expand Up @@ -2285,7 +2312,7 @@ async def run_child() -> Any:
await self._await_temporal_operation(
handle._start_fut,
apply_child_cancel_error,
reraise_on_workflow_cancellation=True,
is_start=True,
)
return handle

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

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

apply_cancel(err)

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

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

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

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

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

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

def _check_condition(self, fn: Callable[[], bool], fut: asyncio.Future) -> bool:
if fn():
fut.set_result(True)
Expand Down
Loading
Loading