Skip to content

Workflow eviction never completes when an already-cancelled activity handle is cancelled again during eviction (regression in 1.33.0) #1938

Closed

Description

@jtwillis92

What happens

If a workflow cancels an activity and the run is then evicted before the cancel resolves, eviction never finishes. The worker logs RuntimeError: Eviction processed, but 1 tasks remain (the remaining task is the _ActivityHandle), retries the eviction every 2s forever, _could_not_evict_count goes to 1, and the run stays pinned to that worker with its workflow tasks timing out. Worker.shutdown() never drains.

The easiest trigger is any workflow task failure in the same activation as the cancel. On 1.32.0 a transient failure there is retried and the workflow completes. On 1.33.0+ the run is stuck RUNNING.

  • Bad: 1.33.0, 1.34.0, main at 78b3fe0a
  • Good: 1.32.0 (and 1.31.0)
  • Python 3.11, Linux, dev server from WorkflowEnvironment.start_local() (CLI 1.9.1, Server 1.32.0)

Cause

Introduced by #1814 (ee2a4da).

It also reproduces with no failure at all: ActivityCancellationType.WAIT_CANCELLATION_COMPLETED, cancel, then a cache eviction (max_cached_workflows=1 plus a second workflow). Clean on 1.31.0, hangs on 1.34.0.

Repro

import asyncio
import uuid
from datetime import timedelta

from temporalio import activity, workflow
from temporalio.client import Client
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import UnsandboxedWorkflowRunner, Worker

_failed_once: set[str] = set()


@activity.defn
async def slow() -> None:
    await asyncio.sleep(60)


@workflow.defn
class CancelThenFailOnce:
    @workflow.run
    async def run(self) -> str:
        handle = workflow.start_activity(slow, start_to_close_timeout=timedelta(minutes=2))
        await workflow.sleep(1)
        handle.cancel()
        await asyncio.sleep(0)  # let the handle task emit its cancel command
        if workflow.info().run_id not in _failed_once:
            _failed_once.add(workflow.info().run_id)
            # Any transient workflow task failure after the cancel triggers eviction
            raise RuntimeError("transient workflow task failure")
        try:
            await handle
        except Exception:
            pass
        return "done"


async def main() -> None:
    async with await WorkflowEnvironment.start_local() as env:
        client: Client = env.client
        tq = f"tq-{uuid.uuid4()}"
        async with Worker(
            client,
            task_queue=tq,
            workflows=[CancelThenFailOnce],
            activities=[slow],
            workflow_runner=UnsandboxedWorkflowRunner(),  # module-level "fail once" state
            graceful_shutdown_timeout=timedelta(seconds=1),
        ) as worker:
            handle = await client.start_workflow(
                CancelThenFailOnce.run,
                id=f"wf-{uuid.uuid4()}",
                task_queue=tq,
                task_timeout=timedelta(seconds=5),
            )
            try:
                print("result:", await asyncio.wait_for(handle.result(), 20), flush=True)
            except asyncio.TimeoutError:
                desc = await handle.describe()
                print("result: TIMED OUT after 20s, status", desc.status.name, flush=True)
                await handle.terminate()
            wfw = worker._workflow_worker
            print("could_not_evict_count:", wfw._could_not_evict_count, flush=True)
            try:
                await asyncio.wait_for(worker.shutdown(), 20)
                print("worker shutdown: drained", flush=True)
            except asyncio.TimeoutError:
                print("worker shutdown: HUNG (>20s)", flush=True)
                import os

                os._exit(1)


if __name__ == "__main__":
    asyncio.run(main())

1.32.0 (2.4s):

result: done
could_not_evict_count: 0
worker shutdown: drained

1.34.0 (40.3s):

Failed running eviction job for run ID 01a11266-f0e5-7500-8156-c1590079373c, continually retrying eviction. ...
RuntimeError: Eviction processed, but 1 tasks remain. Stack traces below:
Stack for <_ActivityHandle pending name='activity: slow (workflow: CancelThenFailOnce, ...)' ...
result: TIMED OUT after 20s, status RUNNING
could_not_evict_count: 1
Shutting down workflow worker, but 1 workflow(s) could not be evicted previously, so the shutdown may hang
worker shutdown: HUNG (>20s)

Suggested fix

Skip the dedup while deleting, so _add_command() raises _WorkflowBeingEvictedError the way it did before #1814:

def _request_cancel(self) -> None:
    if self._cancel_command_seq == self._seq and not self._instance._deleting:
        return
    self._cancel_command_seq = self._seq
    self._apply_cancel_command(self._instance._add_command())

The non-evicting path is unchanged, so #1813 stays fixed, and nothing is emitted during eviction since _add_command() raises first. With this patched into 1.34.0 the repro above prints result: done, could_not_evict_count: 0 and worker shutdown: drained (2.4s). Happy to send a PR with this and a regression test.

Activity

  1. tconley1428 commented on Oct 6, 2026

    @tconley1428
    Contributor

    Sounds good. Thanks for catching the issue.

  2. donegold commented on Oct 8, 2026

    @donegold

    We hit this independently on 1.33.0 and traced it to the same early return in _ActivityHandle._request_cancel. Two details from our side, in case they help the fix or a regression test:

    • Our trigger: a workflow cancels an activity started with cancellation_type=ActivityCancellationType.WAIT_CANCELLATION_COMPLETED, then awaits the handle. Any eviction landing after the cancel request and before the activity reports its cancellation leaks the handle's task. The window is up to the activity's heartbeat throttle (about 8 s with a 10 s heartbeat timeout) or its start-to-close.
    • A reliable reproduction: a worker with max_cached_workflows=0 evicts after every activation, so it hits the window on every run. With the default cache, a graceful shutdown before any cancel was requested evicts cleanly.
    • The visible effect beyond the stuck eviction: the next graceful Worker.shutdown() hangs ("1 workflow(s) could not be evicted previously, so the shutdown may hang"), because _handle_cache_eviction's retry loop swallows cancellation. We restart the worker; the run completes on another worker.
  3. jtwillis92 commented on Oct 8, 2026

    @jtwillis92
    ContributorAuthor

    Sounds good. Thanks for catching the issue.

    @tconley1428 do you accept outside contributions to this project? I believe I could put together a fix PR if so.

  4. tconley1428 commented on Oct 8, 2026

    @tconley1428
    Contributor

    We are happy to accept good outside contributions. Just make sure to add some test coverage, but yes, by all means do.

  5. added 2 commits that reference this issue on Oct 8, 2026
    c470ec6
    a496674
  6. added a commit that references this issue on Oct 10, 2026
    ee25ade
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions