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
14 changes: 10 additions & 4 deletions temporalio/worker/_workflow_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
Expand Down
142 changes: 121 additions & 21 deletions tests/worker/test_workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
WorkflowExecutionStatus,
WorkflowFailureError,
WorkflowHandle,
WorkflowHistory,
WorkflowQueryFailedError,
WorkflowUpdateFailedError,
WorkflowUpdateHandle,
Expand Down Expand Up @@ -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]
)
Expand Down Expand Up @@ -1807,25 +1817,17 @@ def state(self) -> tuple[bool, bool]:


@pytest.mark.parametrize("timeout", [False, True])
@pytest.mark.parametrize(
("original_single_batch", "cleanup_completes"),
[
pytest.param(False, True, id="task-cancellation"),
pytest.param(True, False, id="original-behavior-preserved"),
],
)
@pytest.mark.parametrize("task_cancellation", [False, True])
async def test_workflow_shielded_wait_condition_after_cancel(
client: Client,
timeout: bool,
original_single_batch: bool,
cleanup_completes: bool,
client: Client, timeout: bool, task_cancellation: bool
) -> None:
worker = new_worker(client, ShieldedWaitConditionWorkflow)
# A new run uses the newer flag when the worker enables both.
worker._set_default_workflow_logic_flag(
_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=original_single_batch
_SINGLE_BATCH_WORKFLOW_LOGIC_FLAG, enabled=True
)
worker._set_default_workflow_logic_flag(
_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=True
_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG, enabled=task_cancellation
)
async with worker:
handle = await client.start_workflow(
Expand All @@ -1852,17 +1854,115 @@ async def state() -> tuple[bool, bool]:
event.event_type == EventType.EVENT_TYPE_TIMER_FIRED
for event in history.events
)
is cleanup_completes
is task_cancellation
)
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
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)


@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 self._handler

@workflow.signal
async def start_handler(self) -> None:
self._handler = "waiting"
try:
await workflow.wait_condition(lambda: self._release)
self._handler = "returned"
except asyncio.CancelledError:
self._handler = "cancelled"

@workflow.signal
def release(self) -> None:
self._release = True

@workflow.query
def state(self) -> tuple[str, bool]:
return self._handler, self._caught_cancel


@pytest.mark.parametrize(
("first_flag", "expected"),
[
pytest.param(
_APPLY_JOBS_FIRST_WORKFLOW_LOGIC_FLAG,
"returned",
id="batching-with-task-cancellation",
),
pytest.param(
_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, expected: str
) -> None:
task_queue = str(uuid.uuid4())
handle = await client.start_workflow(
HandlerWaitConditionAfterCancelWorkflow.run,
id=f"workflow-{uuid.uuid4()}",
task_queue=task_queue,
)

async def state() -> tuple[str, bool]:
return await handle.query(HandlerWaitConditionAfterCancelWorkflow.state)

def flag_worker(*flags: _WorkflowLogicFlag) -> Worker:
worker = new_worker(
client,
HandlerWaitConditionAfterCancelWorkflow,
task_queue=task_queue,
# The Java test server does not reliably reschedule an abandoned
# sticky task after its timeout, so keep events sent after this
# worker stops on the normal queue.
max_cached_workflows=0,
)
is cleanup_completes
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_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
):
await handle.signal(HandlerWaitConditionAfterCancelWorkflow.start_handler)
await assert_eq_eventually(("waiting", False), state)
await handle.cancel()
await assert_eq_eventually(("waiting", True), state)
await handle.signal(HandlerWaitConditionAfterCancelWorkflow.release)
assert await handle.result() == expected

history = await handle.fetch_history()
assert _recorded_workflow_logic_flags(history) == {first_flag}
await Replayer(workflows=[HandlerWaitConditionAfterCancelWorkflow]).replay_workflow(
history
)
await Replayer(workflows=[ShieldedWaitConditionWorkflow]).replay_workflow(history)


@workflow.defn
Expand Down
Loading