Repository navigation
Description
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,
mainat78b3fe0a - 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).
- On eviction,
_apply_remove_from_cachesets_deleting = Trueand cancels every task. - The activity handle task is parked in
_await_temporal_operation. OnCancelledErrorwith the result future still pending it callsapply_cancel,uncancel()s and loops. - Up to 1.32.0 that call was
apply_cancel(err, self._add_command())._add_command()ran unconditionally, and while deleting_assert_not_read_onlyraises_WorkflowBeingEvictedError, which is what ended the handle task. - Since Fix duplicate activity cancellation commands #1814 it calls
handle._request_cancel(), which returns early when_cancel_command_seq == _seq. If the handle was already cancelled before the eviction, nothing raises, the task uncancels and loops on a future that will never resolve, and thetasks remaincheck fails on every retry.
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
tconley1428 commentedon Oct 6, 2026
Sounds good. Thanks for catching the issue.
donegold commentedon Oct 8, 2026
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: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.max_cached_workflows=0evicts 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.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.jtwillis92 commentedon Oct 8, 2026
@tconley1428 do you accept outside contributions to this project? I believe I could put together a fix PR if so.
tconley1428 commentedon Oct 8, 2026
We are happy to accept good outside contributions. Just make sure to add some test coverage, but yes, by all means do.
Fix eviction hang when an already-cancelled activity is cancelled again
Fix eviction hang when an already-cancelled activity is cancelled again
Fix eviction hang when an already-cancelled activity is cancelled aga…