diff --git a/dapr/actor/runtime/_turn_lock.py b/dapr/actor/runtime/_turn_lock.py new file mode 100644 index 000000000..b8a404422 --- /dev/null +++ b/dapr/actor/runtime/_turn_lock.py @@ -0,0 +1,177 @@ +# -*- coding: utf-8 -*- + +""" +Copyright 2026 The Dapr Authors +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import threading +from collections import deque +from contextlib import asynccontextmanager +from typing import AsyncIterator, Deque, Dict, Optional, Tuple + + +def _resolve(future: 'asyncio.Future[None]') -> None: + if not future.done(): + future.set_result(None) + + +class _Waiter: + __slots__ = ('loop', 'future', 'reentrancy_id', 'granted', 'reentered') + + def __init__(self, reentrancy_id: Optional[str]) -> None: + self.loop = asyncio.get_running_loop() + self.future: 'asyncio.Future[None]' = self.loop.create_future() + self.reentrancy_id = reentrancy_id + self.granted = False + self.reentered = False + + +class _TurnEntry: + __slots__ = ('active_calls', 'reentrancy_id', 'reentrancy_allowed', 'waiters') + + def __init__(self) -> None: + self.active_calls = 0 + self.reentrancy_id: Optional[str] = None + self.reentrancy_allowed = False + self.waiters: Deque[_Waiter] = deque() + + +class ActorTurn: + """A turn held by one call on one actor ID.""" + + def __init__(self, lock: 'ActorTurnLock', entry: _TurnEntry, reentered: bool) -> None: + self._lock = lock + self._entry = entry + self.reentered = reentered + + def allow_reentrancy(self) -> None: + """Lets calls with this turn's reentrancy ID enter; called once activation is done.""" + self._lock._allow_reentrancy(self._entry) + + +class ActorTurnLock: + """Runs one turn at a time per actor ID, in arrival order. + + Waiters may come from different threads and event loops (the Flask extension runs each + callback in its own loop), so a waiter is woken with ``call_soon_threadsafe`` on its own loop. + """ + + def __init__(self) -> None: + self._sync = threading.Lock() + self._entries: Dict[str, _TurnEntry] = {} + + @asynccontextmanager + async def turn( + self, actor_id: str, reentrancy_id: Optional[str] = None + ) -> AsyncIterator[ActorTurn]: + """Holds the actor's turn while the body runs, releasing it on every outcome. + + A call whose reentrancy ID matches the running turn enters it once the turn allows + reentrancy, without queueing behind other callers. + """ + entry, reentered = await self._acquire(actor_id, reentrancy_id or None) + try: + yield ActorTurn(self, entry, reentered) + finally: + with self._sync: + self._release(actor_id, entry) + + def is_in_chain(self, actor_id: str, reentrancy_id: Optional[str]) -> bool: + """Returns whether a turn of this reentrancy chain is running for the actor.""" + if not reentrancy_id: + return False + with self._sync: + entry = self._entries.get(actor_id) + return ( + entry is not None + and entry.active_calls > 0 + and entry.reentrancy_id == reentrancy_id + ) + + async def _acquire( + self, actor_id: str, reentrancy_id: Optional[str] + ) -> Tuple[_TurnEntry, bool]: + with self._sync: + entry = self._entries.setdefault(actor_id, _TurnEntry()) + if entry.active_calls == 0: + self._start_turn(entry, reentrancy_id) + return entry, False + if ( + reentrancy_id is not None + and entry.reentrancy_allowed + and entry.reentrancy_id == reentrancy_id + ): + entry.active_calls += 1 + return entry, True + waiter = _Waiter(reentrancy_id) + entry.waiters.append(waiter) + + try: + await waiter.future + except BaseException: + with self._sync: + if waiter.granted: + self._release(actor_id, entry) + else: + entry.waiters.remove(waiter) + self._remove_if_idle(actor_id, entry) + raise + return entry, waiter.reentered + + def _allow_reentrancy(self, entry: _TurnEntry) -> None: + with self._sync: + if entry.reentrancy_allowed or entry.reentrancy_id is None: + return + entry.reentrancy_allowed = True + chained = [ + queued for queued in entry.waiters if queued.reentrancy_id == entry.reentrancy_id + ] + for waiter in chained: + entry.waiters.remove(waiter) + waiter.reentered = True + if self._grant(waiter): + entry.active_calls += 1 + + def _release(self, actor_id: str, entry: _TurnEntry) -> None: + entry.active_calls -= 1 + if entry.active_calls > 0: + return + while entry.waiters: + waiter = entry.waiters.popleft() + self._start_turn(entry, waiter.reentrancy_id) + if self._grant(waiter): + return + entry.active_calls = 0 + self._remove_if_idle(actor_id, entry) + + def _remove_if_idle(self, actor_id: str, entry: _TurnEntry) -> None: + if entry.active_calls or entry.waiters or self._entries.get(actor_id) is not entry: + return + del self._entries[actor_id] + + @staticmethod + def _start_turn(entry: _TurnEntry, reentrancy_id: Optional[str]) -> None: + entry.active_calls = 1 + entry.reentrancy_id = reentrancy_id + entry.reentrancy_allowed = False + + @staticmethod + def _grant(waiter: _Waiter) -> bool: + waiter.granted = True + try: + waiter.loop.call_soon_threadsafe(_resolve, waiter.future) + except RuntimeError: + # The waiter's event loop is closed, so nobody is left to take the turn. + waiter.granted = False + return False + return True diff --git a/dapr/actor/runtime/actor.py b/dapr/actor/runtime/actor.py index 81ff0909c..9074c7795 100644 --- a/dapr/actor/runtime/actor.py +++ b/dapr/actor/runtime/actor.py @@ -228,6 +228,10 @@ async def _on_activate(self) -> None: This method is called right after the actor is activated and before any method call or reminders are dispatched on it. + + Calls into this actor, including reentrant ones, wait until this method + returns. If it calls another actor that calls back into this one, both + wait until the outbound call times out. """ ... diff --git a/dapr/actor/runtime/manager.py b/dapr/actor/runtime/manager.py index e9ac638e9..49d3b6289 100644 --- a/dapr/actor/runtime/manager.py +++ b/dapr/actor/runtime/manager.py @@ -13,15 +13,17 @@ limitations under the License. """ -import asyncio +import itertools import logging +import threading import uuid from functools import partial -from typing import Any, Callable, Coroutine, Dict, NamedTuple, Optional +from typing import Any, Callable, Coroutine, Dict, List, Optional, Sequence from dapr.actor.id import ActorId from dapr.actor.runtime._method_context import ActorMethodContext from dapr.actor.runtime._reminder_data import ActorReminderData +from dapr.actor.runtime._turn_lock import ActorTurn, ActorTurnLock from dapr.actor.runtime.actor import Actor from dapr.actor.runtime.context import ActorRuntimeContext from dapr.actor.runtime.method_dispatcher import ActorMethodDispatcher @@ -34,13 +36,39 @@ REMINDER_METHOD_NAME = 'receive_reminder' -def _describe_activation(activation_id: Optional[str]) -> str: - return f'activation {activation_id}' if activation_id else 'an activation with no id' +class _ActiveActor: + """An actor object and the daprd activation it belongs to.""" + __slots__ = ( + 'actor', + 'activation_id', + 'replaced', + 'deactivation_requested', + 'deactivation_error', + ) -class _ActiveActor(NamedTuple): - actor: Actor - activation_id: Optional[str] + def __init__(self, actor: Actor, activation_id: Optional[str]) -> None: + self.actor = actor + self.activation_id = activation_id + self.replaced = False + self.deactivation_requested = False + self.deactivation_error: Optional[Exception] = None + + def mark_replaced(self) -> None: + """Marks the object as belonging to an older activation, so it can no longer save.""" + self.replaced = True + self.actor._state_manager._discard() + + +class _Admission: + """The most recent call that arrived with an activation id for one actor ID.""" + + __slots__ = ('ticket', 'activation_id', 'calls') + + def __init__(self) -> None: + self.ticket = 0 + self.activation_id = '' + self.calls = 0 class ActorManager: @@ -50,38 +78,53 @@ def __init__(self, ctx: ActorRuntimeContext): self._runtime_ctx = ctx self._message_serializer = self._runtime_ctx.message_serializer + self._turn_lock = ActorTurnLock() + # A threading lock: calls are admitted before they wait for their turn, and the Flask + # extension dispatches from several threads, each with its own event loop. + self._active_actors_lock = threading.Lock() self._active_actors: Dict[str, _ActiveActor] = {} - self._active_actors_lock = asyncio.Lock() + self._activating: Dict[str, _ActiveActor] = {} + self._detached: Dict[str, List[_ActiveActor]] = {} + self._deactivating: Dict[str, List[_ActiveActor]] = {} + self._admissions: Dict[str, _Admission] = {} + self._tickets = itertools.count(1) self._dispatcher = ActorMethodDispatcher(ctx.actor_type_info) self._timer_method_context = ActorMethodContext.create_for_timer(TIMER_METHOD_NAME) self._reminder_method_context = ActorMethodContext.create_for_reminder(REMINDER_METHOD_NAME) async def activate_actor(self, actor_id: ActorId, activation_id: Optional[str] = None) -> Actor: - """Activates actor.""" - actor = self._runtime_ctx.create_actor(actor_id) - await actor._on_activate_internal(lambda: actor_id.id not in self._active_actors) - - async with self._active_actors_lock: - registered = self._active_actors.get(actor_id.id) - if registered is None: - self._active_actors[actor_id.id] = _ActiveActor(actor, activation_id or None) - return actor - - await self._deactivate_discarded(actor_id, actor) - if activation_id and activation_id != registered.activation_id: - registered_by = _describe_activation(registered.activation_id) - raise DaprInternalError( - f'{actor_id} was activated by {registered_by} during this activation' - ) - return registered.actor - - async def deactivate_actor(self, actor_id: ActorId): - async with self._active_actors_lock: - deactivated = self._active_actors.pop(actor_id.id, None) - if not deactivated: - raise ValueError(f'{actor_id} is not activated') - await deactivated.actor._on_deactivate_internal() + """Activates actor, or returns it if it is already active.""" + ticket = self._admit(actor_id.id, None) + async with self._turn_lock.turn(actor_id.id): + await self._deactivate_detached(actor_id) + active = await self._get_or_activate(actor_id, activation_id, ticket) + return active.actor + + async def deactivate_actor(self, actor_id: ActorId) -> None: + """Deactivates actor once the calls queued ahead of the deactivation finish. + + The actor is unregistered straight away, so the running call can no longer save its state. + A running activation is never registered, and an activation made by a call queued ahead + of the deactivation is deactivated as well. If hooks fail, the latest error is raised: + an earlier turn has already logged the error of the object it deactivated. + """ + with self._active_actors_lock: + requested_on_arrival = self._request_deactivation(actor_id.id) + async with self._turn_lock.turn(actor_id.id): + with self._active_actors_lock: + requested_in_turn = self._request_deactivation(actor_id.id) + requested = requested_on_arrival + requested_in_turn + await self._deactivate_detached(actor_id, requested) + if not requested: + raise ValueError(f'{actor_id} is not activated') + requested_errors = [ + active.deactivation_error + for active in requested + if active.deactivation_error is not None + ] + if requested_errors: + raise requested_errors[-1] async def fire_reminder( self, @@ -139,6 +182,7 @@ async def dispatch( actor_method_name: str, request_body: bytes, activation_id: Optional[str] = None, + reentrancy_id: Optional[str] = None, ) -> bytes: method_context = ActorMethodContext.create_for_actor(actor_method_name) arg_types = self._dispatcher.get_arg_types(actor_method_name) @@ -156,7 +200,7 @@ async def invoke_method(actor): return rtnval rtn_obj = await self._dispatch_internal( - actor_id, method_context, invoke_method, activation_id + actor_id, method_context, invoke_method, activation_id, reentrancy_id ) return self._message_serializer.serialize(rtn_obj) @@ -166,18 +210,26 @@ async def _dispatch_internal( method_context: ActorMethodContext, dispatch_action: Callable[[Actor], Coroutine[Any, Any, Optional[bytes]]], activation_id: Optional[str] = None, + reentrancy_id: Optional[str] = None, ) -> object: - await self._deactivate_if_stale(actor_id, activation_id) - async with self._active_actors_lock: - active = self._active_actors.get(actor_id.id) - if active is not None and activation_id and activation_id != active.activation_id: - registered_by = _describe_activation(active.activation_id) - raise DaprInternalError(f'{actor_id} was activated by {registered_by} during this call') - if active is None: - actor = await self.activate_actor(actor_id, activation_id) - else: - actor = active.actor + in_chain = self._turn_lock.is_in_chain(actor_id.id, reentrancy_id) + admitted_id = None if in_chain else activation_id + ticket = self._admit(actor_id.id, admitted_id) + try: + async with self._turn_lock.turn(actor_id.id, reentrancy_id) as turn: + active = await self._enter_turn(actor_id, activation_id, ticket, turn) + turn.allow_reentrancy() + return await self._invoke(actor_id, active.actor, method_context, dispatch_action) + finally: + self._release_admission(actor_id.id, admitted_id) + async def _invoke( + self, + actor_id: ActorId, + actor: Actor, + method_context: ActorMethodContext, + dispatch_action: Callable[[Actor], Coroutine[Any, Any, Optional[bytes]]], + ) -> object: try: if reentrancy_ctx.get(None) is not None: actor._state_manager.set_state_context(str(uuid.uuid4())) @@ -195,6 +247,183 @@ async def _dispatch_internal( return retval + async def _enter_turn( + self, + actor_id: ActorId, + activation_id: Optional[str], + ticket: int, + turn: ActorTurn, + ) -> _ActiveActor: + if not turn.reentered: + await self._deactivate_detached(actor_id) + return await self._get_or_activate(actor_id, activation_id, ticket) + # A reentrant call runs inside its chain's turn, so it never starts an activation. + with self._active_actors_lock: + active = self._active_actors.get(actor_id.id) + if active is None: + raise DaprInternalError( + f'{actor_id} was deactivated or replaced during this call chain, ' + 'the call was not run' + ) + return active + + async def _get_or_activate( + self, actor_id: ActorId, activation_id: Optional[str], ticket: int + ) -> _ActiveActor: + with self._active_actors_lock: + self._raise_if_superseded(actor_id, activation_id, ticket) + if activation_id: + self._replace_stale(actor_id.id, activation_id) + registered = self._active_actors.get(actor_id.id) + if registered is not None: + return registered + await self._deactivate_detached(actor_id) + return await self._activate_in_turn(actor_id, activation_id, ticket) + + async def _activate_in_turn( + self, actor_id: ActorId, activation_id: Optional[str], ticket: int + ) -> _ActiveActor: + actor = self._runtime_ctx.create_actor(actor_id) + active = _ActiveActor(actor, activation_id or None) + with self._active_actors_lock: + self._raise_if_superseded(actor_id, activation_id, ticket) + self._activating[actor_id.id] = active + try: + await actor._on_activate_internal( + lambda: not (active.replaced or active.deactivation_requested) + ) + finally: + with self._active_actors_lock: + self._activating.pop(actor_id.id, None) + + with self._active_actors_lock: + replaced = active.replaced or self._is_superseded(actor_id.id, activation_id, ticket) + deactivated = active.deactivation_requested and not replaced + if deactivated: + self._detached.setdefault(actor_id.id, []).append(active) + elif not replaced: + self._active_actors[actor_id.id] = active + if replaced: + await self._deactivate_discarded(actor_id, actor) + raise DaprInternalError( + f'{actor_id} was replaced by a newer activation during this activation' + ) + if deactivated: + raise DaprInternalError( + f'{actor_id} was deactivated during this activation, the call was not run' + ) + return active + + def _admit(self, actor_key: str, activation_id: Optional[str]) -> int: + """Numbers the call; a new activation id replaces the stale object before waiting.""" + with self._active_actors_lock: + ticket = next(self._tickets) + if not activation_id: + return ticket + admission = self._admissions.setdefault(actor_key, _Admission()) + admission.ticket = ticket + admission.activation_id = activation_id + admission.calls += 1 + self._replace_stale(actor_key, activation_id) + return ticket + + def _release_admission(self, actor_key: str, activation_id: Optional[str]) -> None: + if not activation_id: + return + with self._active_actors_lock: + admission = self._admissions[actor_key] + admission.calls -= 1 + if admission.calls == 0: + del self._admissions[actor_key] + + def _is_superseded(self, actor_key: str, activation_id: Optional[str], ticket: int) -> bool: + """Activation ids are not ordered, so a different id that arrived later is the newer one.""" + if not activation_id: + return False + admission = self._admissions.get(actor_key) + return ( + admission is not None + and admission.ticket > ticket + and admission.activation_id != activation_id + ) + + def _raise_if_superseded( + self, actor_id: ActorId, activation_id: Optional[str], ticket: int + ) -> None: + if self._is_superseded(actor_id.id, activation_id, ticket): + raise DaprInternalError( + f'{actor_id} was activated by a newer activation while this call waited, ' + 'the call was not run' + ) + + def _replace_stale(self, actor_key: str, activation_id: str) -> None: + """Replaces every object of another activation; the registered one is also detached.""" + pending = self._activating.get(actor_key) + if pending is not None and pending.activation_id != activation_id: + pending.mark_replaced() + unregistered = self._detached.get(actor_key, []) + self._deactivating.get(actor_key, []) + for active in unregistered: + if active.activation_id != activation_id: + active.mark_replaced() + registered = self._active_actors.get(actor_key) + if registered is None or registered.activation_id == activation_id: + return + registered.mark_replaced() + self._detach(actor_key) + + def _request_deactivation(self, actor_key: str) -> List[_ActiveActor]: + """Detaches the registered object and stops a running activation from registering.""" + requested: List[_ActiveActor] = [] + pending = self._activating.get(actor_key) + if pending is not None and not pending.deactivation_requested: + pending.deactivation_requested = True + requested.append(pending) + registered = self._detach(actor_key) + if registered is not None: + requested.append(registered) + return requested + + def _detach(self, actor_key: str) -> Optional[_ActiveActor]: + detached = self._active_actors.pop(actor_key, None) + if detached is not None: + self._detached.setdefault(actor_key, []).append(detached) + return detached + + async def _deactivate_detached( + self, actor_id: ActorId, owned: Sequence[_ActiveActor] = () + ) -> None: + """Deactivates objects detached since the last turn. + + They stay visible to a newer activation until their hooks finish, so it can still refuse + their saves. An error from an object that was not replaced is kept on it for the + deactivation that requested it. Other errors, and those of objects not in ``owned``, are + logged. + """ + with self._active_actors_lock: + detached = self._detached.pop(actor_id.id, []) + if not detached: + return + self._deactivating[actor_id.id] = detached + try: + for active in detached: + await self._deactivate_detached_object(actor_id, active, owned) + finally: + with self._active_actors_lock: + self._deactivating.pop(actor_id.id, None) + + async def _deactivate_detached_object( + self, actor_id: ActorId, active: _ActiveActor, owned: Sequence[_ActiveActor] + ) -> None: + try: + await active.actor._on_deactivate_internal() + except Exception as exception: # noqa: BLE001 + if active.replaced: + logger.exception('Deactivating detached object for %s failed', actor_id) + return + active.deactivation_error = exception + if active not in owned: + logger.exception('Deactivating detached object for %s failed', actor_id) + def _ensure_still_registered(self, actor_id: ActorId, actor: Actor) -> None: active = self._active_actors.get(actor_id.id) if active is None or active.actor is not actor: @@ -202,17 +431,6 @@ def _ensure_still_registered(self, actor_id: ActorId, actor: Actor) -> None: f'{actor_id} was deactivated or replaced during the call, state not saved' ) - async def _deactivate_if_stale(self, actor_id: ActorId, activation_id: Optional[str]) -> None: - """Daprd can re-activate without a DELETE after a SIGKILL or OOM restart.""" - if not activation_id: - return - async with self._active_actors_lock: - stale = self._active_actors.get(actor_id.id) - if stale is None or stale.activation_id == activation_id: - return - del self._active_actors[actor_id.id] - await self._deactivate_discarded(actor_id, stale.actor) - async def _deactivate_discarded(self, actor_id: ActorId, actor: Actor) -> None: """Logs instead of raising so the unrelated call does not fail.""" actor._state_manager._discard() diff --git a/dapr/actor/runtime/runtime.py b/dapr/actor/runtime/runtime.py index 386ed7a5d..9ade1cfd8 100644 --- a/dapr/actor/runtime/runtime.py +++ b/dapr/actor/runtime/runtime.py @@ -140,7 +140,10 @@ async def dispatch( actor_method_name (str): the method name that is dispatched. request_body (bytes): the body of request that is passed to actor method arguments. reentrancy_id (str): reentrancy ID obtained from the dapr_reentrancy_id header - if present. + if present. A call with the running turn's ID enters that turn only when + reentrancy is enabled for the actor type, and only after `_on_activate` + returns. A call back into the actor from `_on_activate` therefore waits + until the outbound call times out. activation_id (str, optional): the Dapr-Actor-Activation-Id header value. Returns: @@ -154,8 +157,13 @@ async def dispatch( if not manager: raise ValueError(f'{actor_type_name} is not registered.') activation_id = await cls._trusted_activation_id(manager, activation_id) + reentrancy_id_for_turn = reentrancy_id if cls._reentrancy_enabled(actor_type_name) else None return await manager.dispatch( - ActorId(actor_id), actor_method_name, request_body, activation_id + ActorId(actor_id), + actor_method_name, + request_body, + activation_id, + reentrancy_id=reentrancy_id_for_turn, ) @classmethod @@ -228,6 +236,23 @@ def get_actor_config(cls) -> ActorRuntimeConfig: """Gets :class:`ActorRuntimeConfig`.""" return cls._actor_config + @classmethod + def _reentrancy_enabled(cls, actor_type_name: str) -> bool: + """Resolves reentrancy as daprd does: a type with its own config uses only that config.""" + type_config = next( + ( + config + for config in cls._actor_config.actor_type_configs + if config.actor_type == actor_type_name + ), + None, + ) + if type_config is None: + reentrancy = cls._actor_config.reentrancy + else: + reentrancy = type_config.reentrancy + return reentrancy is not None and reentrancy.enabled + @classmethod async def _get_actor_manager(cls, actor_type_name: str) -> Optional[ActorManager]: """Gets :class:`ActorManager` object for actor_type_name. diff --git a/tests/actor/test_actor_manager.py b/tests/actor/test_actor_manager.py index 138452bda..745956502 100644 --- a/tests/actor/test_actor_manager.py +++ b/tests/actor/test_actor_manager.py @@ -15,10 +15,11 @@ import asyncio import json +import threading import unittest from datetime import timedelta from functools import partial -from typing import Awaitable, Callable, Dict, List, Optional +from typing import Awaitable, Callable, Dict, List, Optional, Tuple from unittest import mock from dapr.actor.actor_interface import ActorInterface, actormethod @@ -39,6 +40,7 @@ from tests.actor.fake_client import FakeDaprActorClient from tests.actor.utils import ( _async_mock, + _let_pending_tasks_run, _run, ) @@ -501,11 +503,14 @@ async def _run_replaced_during(self, stale_call: Callable[[], Awaitable[None]]) stale_task = asyncio.ensure_future(stale_call()) await asyncio.wait_for(actor_stale.held.wait(), 5) - await self._append('b', 'act-2') + fresh_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + self.assertNotIn(self._actor_id.id, self._manager._active_actors) actor_stale.release.set() with self.assertRaises(DaprInternalError): await asyncio.wait_for(stale_task, 5) + await asyncio.wait_for(fresh_task, 5) self.assertEqual(['x', 'b'], self._stored_items()) def test_replaced_method_call_skips_save(self): @@ -543,9 +548,10 @@ async def scenario() -> None: await asyncio.wait_for(actor_first.held.wait(), 5) actor_first.held = None - await self._append('b', None) + missing_id_task = asyncio.ensure_future(self._append('b', None)) + await _let_pending_tasks_run() actor_first.release.set() - await asyncio.wait_for(first_task, 5) + await asyncio.wait_for(asyncio.gather(first_task, missing_id_task), 5) _run(scenario()) @@ -560,11 +566,14 @@ async def scenario() -> None: first_task = asyncio.ensure_future(self._append('a', 'act-1')) await asyncio.wait_for(actor_first.held.wait(), 5) - await self._manager.deactivate_actor(self._actor_id) + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + await _let_pending_tasks_run() + self.assertNotIn(self._actor_id.id, self._manager._active_actors) actor_first.release.set() with self.assertRaises(DaprInternalError): await asyncio.wait_for(first_task, 5) + await asyncio.wait_for(deactivation, 5) _run(scenario()) @@ -658,6 +667,19 @@ async def _on_deactivate(self) -> None: await self._state_manager.save_state() +class GatedSaveOnDeactivateActor(SaveOnDeactivateActor): + def __init__(self, ctx, actor_id): + super().__init__(ctx, actor_id) + self.deactivate_started: Optional[asyncio.Event] = None + self.deactivate_release: Optional[asyncio.Event] = None + + async def _on_deactivate(self) -> None: + if self.deactivate_started is not None and self.deactivate_release is not None: + self.deactivate_started.set() + await self.deactivate_release.wait() + await super()._on_deactivate() + + class ActorManagerDiscardedSaveTests(unittest.TestCase): def setUp(self): self._serializer = DefaultJSONSerializer() @@ -694,12 +716,74 @@ async def scenario() -> None: _run(scenario()) self.assertEqual(['x', 'y'], self._stored_items()) + def test_new_activation_refuses_the_save_of_a_queued_deactivation(self): + async def scenario() -> None: + await self._append('x', 'act-1') + actor_stale: SaveOnDeactivateActor = self._manager._active_actors[ + self._actor_id.id + ].actor + actor_stale.held = asyncio.Event() + actor_stale.release = asyncio.Event() + held_task = asyncio.ensure_future(self._append('a', 'act-1')) + await asyncio.wait_for(actor_stale.held.wait(), 5) + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + newer_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + + actor_stale.release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(held_task, 5) + await asyncio.wait_for(asyncio.gather(deactivation, newer_task), 5) + + with self.assertLogs('dapr.actor.runtime.manager', level='ERROR'): + _run(scenario()) + + self.assertEqual(['x', 'b'], self._stored_items()) + + def test_new_activation_refuses_the_save_of_a_running_deactivation(self): + type_info = ActorTypeInformation.create(GatedSaveOnDeactivateActor) + ctx = ActorRuntimeContext(type_info, self._serializer, self._serializer, self._client) + self._manager = ActorManager(ctx) + + async def scenario() -> None: + await self._append('x', 'act-1') + actor_stale: GatedSaveOnDeactivateActor = self._manager._active_actors[ + self._actor_id.id + ].actor + actor_stale.deactivate_started = asyncio.Event() + actor_stale.deactivate_release = asyncio.Event() + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + await asyncio.wait_for(actor_stale.deactivate_started.wait(), 5) + newer_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + + actor_stale.deactivate_release.set() + await asyncio.wait_for(asyncio.gather(deactivation, newer_task), 5) + + with self.assertLogs('dapr.actor.runtime.manager', level='ERROR'): + _run(scenario()) + + self.assertEqual(['x', 'b'], self._stored_items()) + self.assertEqual({}, self._manager._deactivating) + class RaisingDeactivateActor(AppendActor): async def _on_deactivate(self) -> None: raise RuntimeError('deactivate failed') +class FailingDeactivateActor(AppendActor): + error_for_new_objects: Optional[Exception] = None + + def __init__(self, ctx, actor_id): + super().__init__(ctx, actor_id) + self.deactivate_error = FailingDeactivateActor.error_for_new_objects + + async def _on_deactivate(self) -> None: + if self.deactivate_error is not None: + raise self.deactivate_error + + class ActorManagerConcurrentActivationTests(unittest.TestCase): def _manager_for(self, actor_class: type) -> ActorManager: serializer = DefaultJSONSerializer() @@ -728,13 +812,13 @@ async def scenario() -> None: late_task = asyncio.ensure_future(self._append(manager, 'a', 'act-A')) await asyncio.wait_for(GatedActivateActor.activation_started.wait(), 5) - await self._append(manager, 'b', 'act-B') - actor_newer = manager._active_actors['race'].actor + newer_task = asyncio.ensure_future(self._append(manager, 'b', 'act-B')) + await _let_pending_tasks_run() release.set() with self.assertRaises(DaprInternalError): await asyncio.wait_for(late_task, 5) - self.assertIs(actor_newer, manager._active_actors['race'].actor) + await asyncio.wait_for(newer_task, 5) self.assertEqual('act-B', manager._active_actors['race'].activation_id) _run(scenario()) @@ -752,18 +836,20 @@ async def scenario() -> None: late_task = asyncio.ensure_future(self._append(manager, 'a', 'act-A')) await asyncio.wait_for(GatedActivateActor.activation_started.wait(), 5) - await self._append(manager, 'b', 'act-B') + newer_task = asyncio.ensure_future(self._append(manager, 'b', 'act-B')) + await _let_pending_tasks_run() release.set() with self.assertRaises(DaprInternalError): await asyncio.wait_for(late_task, 5) + await asyncio.wait_for(newer_task, 5) _run(scenario()) self.assertEqual(['x', 'init', 'b'], json.loads(self._client.store['items'])) - def test_late_activation_with_same_id_reuses_winner(self): - manager = self._manager_for(GatedActivateActor) + def test_deactivation_during_activation_skips_the_activation_save(self): + manager = self._manager_for(GatedActivateWriteActor) self._client.store['items'] = json.dumps(['x']).encode('utf-8') async def scenario() -> None: @@ -773,17 +859,40 @@ async def scenario() -> None: late_task = asyncio.ensure_future(self._append(manager, 'a', 'act-A')) await asyncio.wait_for(GatedActivateActor.activation_started.wait(), 5) - await self._append(manager, 'b', 'act-A') - actor_winner = manager._active_actors['race'].actor + deactivation = asyncio.ensure_future(manager.deactivate_actor(ActorId('race'))) + await _let_pending_tasks_run() release.set() - await asyncio.wait_for(late_task, 5) - self.assertIs(actor_winner, manager._active_actors['race'].actor) + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(late_task, 5) + await asyncio.wait_for(deactivation, 5) + + _run(scenario()) + + self.assertNotIn('race', manager._active_actors) + self.assertEqual(['x'], json.loads(self._client.store['items'])) + + def test_same_id_call_waits_for_the_running_activation(self): + manager = self._manager_for(GatedActivateActor) + self._client.store['items'] = json.dumps(['x']).encode('utf-8') + + async def scenario() -> None: + GatedActivateActor.activation_started = asyncio.Event() + release = asyncio.Event() + GatedActivateActor.activation_release = release + first_task = asyncio.ensure_future(self._append(manager, 'a', 'act-A')) + await asyncio.wait_for(GatedActivateActor.activation_started.wait(), 5) + + same_id_task = asyncio.ensure_future(self._append(manager, 'b', 'act-A')) + await _let_pending_tasks_run() + release.set() + + await asyncio.wait_for(asyncio.gather(first_task, same_id_task), 5) self.assertEqual('act-A', manager._active_actors['race'].activation_id) _run(scenario()) - self.assertEqual(['x', 'b', 'a'], json.loads(self._client.store['items'])) + self.assertEqual(['x', 'a', 'b'], json.loads(self._client.store['items'])) def test_raising_deactivate_on_replace_does_not_fail_new_call(self): manager = self._manager_for(RaisingDeactivateActor) @@ -813,12 +922,14 @@ async def scenario() -> None: new_task = asyncio.ensure_future(self._append(manager, 'b', 'act-B')) await asyncio.wait_for(actor_stale.deactivate_started.wait(), 5) - await self._append(manager, 'a', 'act-A') - actor_late: GatedDeactivateActor = manager._active_actors['race'].actor + late_task = asyncio.ensure_future(self._append(manager, 'a', 'act-A')) + await _let_pending_tasks_run() actor_stale.deactivate_release.set() with self.assertRaises(DaprInternalError): await asyncio.wait_for(new_task, 5) + await asyncio.wait_for(late_task, 5) + actor_late: GatedDeactivateActor = manager._active_actors['race'].actor self.assertEqual(['a'], actor_late.items_appended) self.assertEqual('act-A', manager._active_actors['race'].activation_id) @@ -832,3 +943,438 @@ async def scenario() -> None: _run(scenario()) self.assertEqual(['x', 'a', 'c'], json.loads(self._client.store['items'])) + + +class TurnTrackingActor(AppendActor, Remindable): + log: Optional[List[str]] = None + activation_release: Optional[asyncio.Event] = None + append_pause_seconds = 0.0 + + async def append(self, item: str) -> None: + self._record(f'{item} started') + if TurnTrackingActor.append_pause_seconds: + await asyncio.sleep(TurnTrackingActor.append_pause_seconds) + await super().append(item) + self._record(f'{item} finished') + + async def _on_activate(self) -> None: + self._record('activated') + if TurnTrackingActor.activation_release is not None: + await TurnTrackingActor.activation_release.wait() + + async def _on_deactivate(self) -> None: + self._record('deactivated') + + def _record(self, event: str) -> None: + if TurnTrackingActor.log is not None: + TurnTrackingActor.log.append(event) + + +class ActorManagerTurnTests(unittest.TestCase): + def setUp(self): + self._serializer = DefaultJSONSerializer() + self._client = StoreBackedActorClient() + type_info = ActorTypeInformation.create(TurnTrackingActor) + ctx = ActorRuntimeContext(type_info, self._serializer, self._serializer, self._client) + self._manager = ActorManager(ctx) + self._actor_id = ActorId('turn') + self._log: List[str] = [] + TurnTrackingActor.log = self._log + self.addCleanup(setattr, TurnTrackingActor, 'log', None) + self.addCleanup(setattr, TurnTrackingActor, 'activation_release', None) + self.addCleanup(setattr, TurnTrackingActor, 'append_pause_seconds', 0.0) + + def _stored_items(self) -> object: + return json.loads(self._client.store['items']) + + async def _append( + self, + item: str, + activation_id: Optional[str] = None, + reentrancy_id: Optional[str] = None, + ) -> None: + body = self._serializer.serialize(item) + await self._manager.dispatch( + self._actor_id, 'Append', body, activation_id, reentrancy_id=reentrancy_id + ) + + async def _hold_append( + self, + item: str, + activation_id: Optional[str] = None, + reentrancy_id: Optional[str] = None, + ) -> Tuple['asyncio.Task[None]', TurnTrackingActor]: + """Activates the actor with an 'x' append, then starts one that waits for ``release``.""" + await self._append('x', activation_id) + actor: TurnTrackingActor = self._manager._active_actors[self._actor_id.id].actor + actor.held = asyncio.Event() + actor.release = asyncio.Event() + self._log.clear() + held_task = asyncio.ensure_future(self._append(item, activation_id, reentrancy_id)) + await asyncio.wait_for(actor.held.wait(), 5) + return held_task, actor + + def test_call_waits_for_the_running_call_to_save(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a') + next_task = asyncio.ensure_future(self._append('b')) + await _let_pending_tasks_run() + + self.assertEqual(['a started'], self._log) + + actor.release.set() + await asyncio.wait_for(asyncio.gather(held_task, next_task), 5) + + _run(scenario()) + + self.assertEqual(['a started', 'a finished', 'b started', 'b finished'], self._log) + self.assertEqual(['x', 'a', 'b'], self._stored_items()) + + def test_timer_and_reminder_wait_for_the_running_call(self): + timer_body = self._serializer.serialize({'callback': 'timer_callback', 'data': 't'}) + + async def scenario() -> None: + held_task, actor = await self._hold_append('a') + timer_task = asyncio.ensure_future( + self._manager.fire_timer(self._actor_id, 't1', timer_body) + ) + reminder_task = asyncio.ensure_future( + self._manager.fire_reminder(self._actor_id, 'r', REMINDER_BODY) + ) + await _let_pending_tasks_run() + + self.assertEqual(['a started'], self._log) + + actor.release.set() + await asyncio.wait_for(asyncio.gather(held_task, timer_task, reminder_task), 5) + + _run(scenario()) + + self.assertEqual(['x', 'a', 't', 'r'], self._stored_items()) + + def test_deactivation_runs_after_the_running_call(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a') + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + finished, _ = await asyncio.wait([deactivation], timeout=0.5) + + self.assertEqual(set(), finished) + self.assertEqual(['a started'], self._log) + + actor.release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(held_task, 5) + await asyncio.wait_for(deactivation, 5) + + _run(scenario()) + + self.assertEqual(['a started', 'a finished', 'deactivated'], self._log) + self.assertEqual(['x'], self._stored_items()) + + def test_deactivation_queued_behind_a_call_leaves_nothing_active(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a') + queued_task = asyncio.ensure_future(self._append('b')) + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + await _let_pending_tasks_run() + + actor.release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(held_task, 5) + await asyncio.wait_for(asyncio.gather(queued_task, deactivation), 5) + + _run(scenario()) + + expected_log = [ + 'a started', + 'a finished', + 'deactivated', + 'activated', + 'b started', + 'b finished', + 'deactivated', + ] + self.assertEqual(expected_log, self._log) + self.assertNotIn(self._actor_id.id, self._manager._active_actors) + self.assertEqual(['x', 'b'], self._stored_items()) + + def test_dispatches_from_threads_with_their_own_event_loops_take_turns(self): + TurnTrackingActor.append_pause_seconds = 0.005 + errors: List[BaseException] = [] + + def append_items(prefix: str) -> None: + try: + for index in range(5): + asyncio.run(self._append(f'{prefix}{index}')) + except BaseException as exception: # noqa: BLE001 + errors.append(exception) + + threads = [threading.Thread(target=append_items, args=(prefix,)) for prefix in 'abcd'] + for thread in threads: + thread.start() + for thread in threads: + thread.join(10) + + self.assertEqual([], [thread.name for thread in threads if thread.is_alive()]) + self.assertEqual([], errors) + appends = [event for event in self._log if event.endswith(('started', 'finished'))] + appends_started = appends[::2] + appends_finished = [event.replace('finished', 'started') for event in appends[1::2]] + self.assertEqual(appends_started, appends_finished) + self.assertEqual(20, len(self._stored_items())) + self.assertEqual(1, self._log.count('activated')) + self.assertEqual({}, self._manager._turn_lock._entries) + + def test_concurrent_first_calls_activate_once(self): + async def scenario() -> None: + TurnTrackingActor.activation_release = asyncio.Event() + first_task = asyncio.ensure_future(self._append('a')) + second_task = asyncio.ensure_future(self._append('b')) + await _let_pending_tasks_run() + + TurnTrackingActor.activation_release.set() + await asyncio.wait_for(asyncio.gather(first_task, second_task), 5) + + _run(scenario()) + + self.assertEqual(1, self._log.count('activated')) + self.assertEqual(['a', 'b'], self._stored_items()) + + def test_waiter_superseded_by_a_newer_activation_is_not_run(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a', 'act-1') + superseded_task = asyncio.ensure_future(self._append('w', 'act-1')) + newer_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + + actor.release.set() + for stale_task in (held_task, superseded_task): + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(stale_task, 5) + await asyncio.wait_for(newer_task, 5) + + _run(scenario()) + + self.assertNotIn('w started', self._log) + self.assertEqual(1, self._log.count('activated')) + self.assertEqual(['x', 'b'], self._stored_items()) + self.assertEqual('act-2', self._manager._active_actors[self._actor_id.id].activation_id) + self.assertEqual({}, self._manager._admissions) + + def test_activation_replaced_while_running_is_deactivated(self): + async def scenario() -> None: + TurnTrackingActor.activation_release = asyncio.Event() + late_task = asyncio.ensure_future(self._append('a', 'act-1')) + await _let_pending_tasks_run() + newer_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + + TurnTrackingActor.activation_release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(late_task, 5) + await asyncio.wait_for(newer_task, 5) + + _run(scenario()) + + expected_log = ['activated', 'deactivated', 'activated', 'b started', 'b finished'] + self.assertEqual(expected_log, self._log) + self.assertEqual(['b'], self._stored_items()) + + def test_reentrant_call_enters_the_running_turn(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a', reentrancy_id='chain') + actor.held = None + + await asyncio.wait_for(self._append('b', reentrancy_id='chain'), 5) + + self.assertFalse(held_task.done()) + actor.release.set() + await asyncio.wait_for(held_task, 5) + + _run(scenario()) + + self.assertEqual(['a started', 'b started', 'b finished', 'a finished'], self._log) + + def test_call_from_another_chain_waits(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a', reentrancy_id='chain') + other_task = asyncio.ensure_future(self._append('b', reentrancy_id='other')) + await _let_pending_tasks_run() + + self.assertEqual(['a started'], self._log) + + actor.release.set() + await asyncio.wait_for(asyncio.gather(held_task, other_task), 5) + + _run(scenario()) + + self.assertEqual(['a started', 'a finished', 'b started', 'b finished'], self._log) + + def test_reentrant_call_during_activation_waits_for_it(self): + async def scenario() -> None: + TurnTrackingActor.activation_release = asyncio.Event() + first_task = asyncio.ensure_future(self._append('a', reentrancy_id='chain')) + await _let_pending_tasks_run() + reentrant_task = asyncio.ensure_future(self._append('b', reentrancy_id='chain')) + await _let_pending_tasks_run() + + self.assertEqual(['activated'], self._log) + + TurnTrackingActor.activation_release.set() + await asyncio.wait_for(asyncio.gather(first_task, reentrant_task), 5) + + _run(scenario()) + + self.assertEqual(1, self._log.count('activated')) + self.assertIn('b finished', self._log) + + def test_reentrant_call_after_deactivation_is_not_run(self): + async def scenario() -> None: + held_task, actor = await self._hold_append('a', reentrancy_id='chain') + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + await _let_pending_tasks_run() + + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(self._append('b', reentrancy_id='chain'), 5) + + actor.release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(held_task, 5) + await asyncio.wait_for(deactivation, 5) + + _run(scenario()) + + self.assertNotIn('b started', self._log) + + def test_deactivation_error_still_reaches_its_caller(self): + type_info = ActorTypeInformation.create(RaisingDeactivateActor) + ctx = ActorRuntimeContext(type_info, self._serializer, self._serializer, self._client) + manager = ActorManager(ctx) + _run(manager.activate_actor(self._actor_id)) + + with self.assertRaises(RuntimeError): + _run(manager.deactivate_actor(self._actor_id)) + + self.assertNotIn(self._actor_id.id, manager._active_actors) + + def _deactivate_behind_a_queued_call( + self, error_first: Exception, error_second: Optional[Exception] + ) -> Tuple[BaseException, List[Optional[BaseException]]]: + """Fails the first object's hook in the queued call's turn, then DELETE's own turn. + + Returns the error DELETE raised and the errors the manager logged. + """ + self.addCleanup(setattr, FailingDeactivateActor, 'error_for_new_objects', None) + type_info = ActorTypeInformation.create(FailingDeactivateActor) + ctx = ActorRuntimeContext(type_info, self._serializer, self._serializer, self._client) + manager = ActorManager(ctx) + + async def append(item: str) -> None: + body = self._serializer.serialize(item) + await manager.dispatch(self._actor_id, 'Append', body) + + async def scenario() -> BaseException: + await append('x') + actor_first: FailingDeactivateActor = manager._active_actors[self._actor_id.id].actor + actor_first.deactivate_error = error_first + FailingDeactivateActor.error_for_new_objects = error_second + actor_first.held = asyncio.Event() + actor_first.release = asyncio.Event() + held_task = asyncio.ensure_future(append('a')) + await asyncio.wait_for(actor_first.held.wait(), 5) + queued_task = asyncio.ensure_future(append('b')) + deactivation = asyncio.ensure_future(manager.deactivate_actor(self._actor_id)) + await _let_pending_tasks_run() + + actor_first.release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(held_task, 5) + await asyncio.wait_for(queued_task, 5) + with self.assertRaises(RuntimeError) as raised: + await asyncio.wait_for(deactivation, 5) + return raised.exception + + with self.assertLogs('dapr.actor.runtime.manager', level='ERROR') as logs: + error_raised = _run(scenario()) + + self.assertNotIn(self._actor_id.id, manager._active_actors) + self.assertEqual(['x', 'b'], self._stored_items()) + errors_logged = [record.exc_info[1] if record.exc_info else None for record in logs.records] + return error_raised, errors_logged + + def test_deactivation_error_reaches_its_caller_when_an_earlier_turn_deactivates(self): + error_first = RuntimeError('first object failed') + + error_raised, errors_logged = self._deactivate_behind_a_queued_call(error_first, None) + + self.assertIs(error_first, error_raised) + self.assertEqual([error_first], errors_logged) + + def test_deactivation_raises_its_own_hook_error_after_an_earlier_one_was_logged(self): + error_first = RuntimeError('first object failed') + error_second = RuntimeError('second object failed') + + error_raised, errors_logged = self._deactivate_behind_a_queued_call( + error_first, error_second + ) + + self.assertIs(error_second, error_raised) + self.assertEqual([error_first], errors_logged) + + def test_activation_hit_by_deactivation_and_newer_id_is_deactivated_once(self): + async def scenario() -> None: + TurnTrackingActor.activation_release = asyncio.Event() + late_task = asyncio.ensure_future(self._append('a', 'act-1')) + await _let_pending_tasks_run() + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + newer_task = asyncio.ensure_future(self._append('b', 'act-2')) + await _let_pending_tasks_run() + + TurnTrackingActor.activation_release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(late_task, 5) + await asyncio.wait_for(asyncio.gather(deactivation, newer_task), 5) + + _run(scenario()) + + expected_log = ['activated', 'deactivated', 'activated', 'b started', 'b finished'] + self.assertEqual(expected_log, self._log) + self.assertEqual(['b'], self._stored_items()) + self.assertEqual({}, self._manager._detached) + + def test_deactivation_during_activation_stops_the_call(self): + async def scenario() -> None: + TurnTrackingActor.activation_release = asyncio.Event() + first_task = asyncio.ensure_future(self._append('a')) + await _let_pending_tasks_run() + deactivation = asyncio.ensure_future(self._manager.deactivate_actor(self._actor_id)) + await _let_pending_tasks_run() + + TurnTrackingActor.activation_release.set() + with self.assertRaises(DaprInternalError): + await asyncio.wait_for(first_task, 5) + await asyncio.wait_for(deactivation, 5) + + _run(scenario()) + + self.assertEqual(['activated', 'deactivated'], self._log) + self.assertNotIn(self._actor_id.id, self._manager._active_actors) + self.assertNotIn('items', self._client.store) + + def test_reentrant_call_with_another_activation_id_does_not_reset(self): + async def scenario() -> TurnTrackingActor: + held_task, actor = await self._hold_append('a', 'act-1', reentrancy_id='chain') + actor.held = None + + await asyncio.wait_for(self._append('b', 'act-2', reentrancy_id='chain'), 5) + + actor.release.set() + await asyncio.wait_for(held_task, 5) + return actor + + actor = _run(scenario()) + + registered = self._manager._active_actors[self._actor_id.id] + self.assertIs(actor, registered.actor) + self.assertEqual('act-1', registered.activation_id) + self.assertNotIn('deactivated', self._log) diff --git a/tests/actor/test_actor_reentrancy.py b/tests/actor/test_actor_reentrancy.py index cbfa6b925..1f77d80e3 100644 --- a/tests/actor/test_actor_reentrancy.py +++ b/tests/actor/test_actor_reentrancy.py @@ -15,9 +15,14 @@ import asyncio import unittest +from typing import Optional from unittest import mock -from dapr.actor.runtime.config import ActorReentrancyConfig, ActorRuntimeConfig +from dapr.actor.runtime.config import ( + ActorReentrancyConfig, + ActorRuntimeConfig, + ActorTypeConfig, +) from dapr.actor.runtime.runtime import ActorRuntime from dapr.serializers import DefaultJSONSerializer from tests.actor.fake_actor_classes import ( @@ -280,3 +285,47 @@ def test_parse_incoming_reentrancy_header_fastapi(self): reentrancy_id, activation_id=None, ) + + def _reentrancy_id_for_turn(self, config: ActorRuntimeConfig) -> Optional[str]: + ActorRuntime.set_actor_config(config) + manager = ActorRuntime._actor_managers[FakeReentrantActor.__name__] + manager_dispatch = mock.AsyncMock(return_value=b'') + + with mock.patch.object(manager, 'dispatch', manager_dispatch): + _run( + ActorRuntime.dispatch( + FakeReentrantActor.__name__, + 'test-id', + 'ReentrantMethod', + b'', + reentrancy_id='chain', + ) + ) + + return manager_dispatch.await_args.kwargs['reentrancy_id'] + + def test_turn_reentrancy_follows_the_global_config(self): + enabled = ActorRuntimeConfig(reentrancy=ActorReentrancyConfig(enabled=True)) + disabled = ActorRuntimeConfig(reentrancy=None) + + self.assertEqual('chain', self._reentrancy_id_for_turn(enabled)) + self.assertIsNone(self._reentrancy_id_for_turn(disabled)) + + def test_turn_reentrancy_uses_only_the_actor_type_config_when_present(self): + actor_type = FakeReentrantActor.__name__ + type_enabled = ActorTypeConfig(actor_type, reentrancy=ActorReentrancyConfig(enabled=True)) + type_disabled = ActorTypeConfig(actor_type, reentrancy=ActorReentrancyConfig(enabled=False)) + type_unset = ActorTypeConfig(actor_type) + global_reentrancy = ActorReentrancyConfig(enabled=True) + + enabled_for_type = ActorRuntimeConfig(actor_type_configs=[type_enabled]) + disabled_for_type = ActorRuntimeConfig( + reentrancy=global_reentrancy, actor_type_configs=[type_disabled] + ) + unset_for_type = ActorRuntimeConfig( + reentrancy=global_reentrancy, actor_type_configs=[type_unset] + ) + + self.assertEqual('chain', self._reentrancy_id_for_turn(enabled_for_type)) + self.assertIsNone(self._reentrancy_id_for_turn(disabled_for_type)) + self.assertIsNone(self._reentrancy_id_for_turn(unset_for_type)) diff --git a/tests/actor/test_actor_turn_lock.py b/tests/actor/test_actor_turn_lock.py new file mode 100644 index 000000000..b4cdfe4e6 --- /dev/null +++ b/tests/actor/test_actor_turn_lock.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- + +""" +Copyright 2026 The Dapr Authors +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import asyncio +import threading +import unittest +from typing import List, Optional, Tuple + +from dapr.actor.runtime._turn_lock import ActorTurnLock, _Waiter +from tests.actor.utils import _let_pending_tasks_run + +WAIT_SECONDS = 5 + + +class ActorTurnLockTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self._lock = ActorTurnLock() + + async def _hold( + self, + entered: asyncio.Event, + release: asyncio.Event, + actor_id: str, + reentrancy_id: Optional[str], + allow_reentrancy: bool, + ) -> None: + async with self._lock.turn(actor_id, reentrancy_id) as turn: + if allow_reentrancy: + turn.allow_reentrancy() + entered.set() + await release.wait() + + async def _start_holding( + self, + actor_id: str = 'a', + reentrancy_id: Optional[str] = None, + allow_reentrancy: bool = False, + ) -> Tuple['asyncio.Task[None]', asyncio.Event]: + entered = asyncio.Event() + release = asyncio.Event() + holder = asyncio.ensure_future( + self._hold(entered, release, actor_id, reentrancy_id, allow_reentrancy) + ) + await asyncio.wait_for(entered.wait(), WAIT_SECONDS) + return holder, release + + async def _record( + self, + order: List[str], + name: str, + actor_id: str = 'a', + reentrancy_id: Optional[str] = None, + ) -> bool: + async with self._lock.turn(actor_id, reentrancy_id) as turn: + order.append(name) + return turn.reentered + + async def test_turns_for_one_actor_run_one_at_a_time(self): + holder, release = await self._start_holding() + order: List[str] = [] + waiter = asyncio.ensure_future(self._record(order, 'second')) + await _let_pending_tasks_run() + + self.assertEqual([], order) + + release.set() + await asyncio.wait_for(asyncio.gather(holder, waiter), WAIT_SECONDS) + self.assertEqual(['second'], order) + self.assertEqual({}, self._lock._entries) + + async def test_turns_for_different_actors_run_in_parallel(self): + holder, release = await self._start_holding('a') + order: List[str] = [] + + await asyncio.wait_for(self._record(order, 'b', actor_id='b'), WAIT_SECONDS) + + self.assertEqual(['b'], order) + release.set() + await asyncio.wait_for(holder, WAIT_SECONDS) + + async def test_waiters_enter_in_arrival_order(self): + holder, release = await self._start_holding() + order: List[str] = [] + names = ['first', 'second', 'third'] + waiters = [asyncio.ensure_future(self._record(order, name)) for name in names] + await _let_pending_tasks_run() + + release.set() + await asyncio.wait_for(asyncio.gather(holder, *waiters), WAIT_SECONDS) + + self.assertEqual(names, order) + + async def test_waiter_cancelled_while_queued_leaves_the_queue(self): + holder, release = await self._start_holding() + order: List[str] = [] + cancelled = asyncio.ensure_future(self._record(order, 'cancelled')) + waiter = asyncio.ensure_future(self._record(order, 'next')) + await _let_pending_tasks_run() + + cancelled.cancel() + await _let_pending_tasks_run() + release.set() + await asyncio.wait_for(asyncio.gather(holder, waiter), WAIT_SECONDS) + + self.assertTrue(cancelled.cancelled()) + self.assertEqual(['next'], order) + self.assertEqual({}, self._lock._entries) + + async def test_waiter_cancelled_after_its_grant_passes_the_turn_on(self): + entered = asyncio.Event() + release = asyncio.Event() + order: List[str] = [] + waiters: List['asyncio.Task[bool]'] = [] + + async def release_then_cancel_next() -> None: + async with self._lock.turn('a'): + entered.set() + await release.wait() + # Same step as the hand-off, so the granted waiter has not resumed yet. + waiters[0].cancel() + + holder = asyncio.ensure_future(release_then_cancel_next()) + await asyncio.wait_for(entered.wait(), WAIT_SECONDS) + waiters.append(asyncio.ensure_future(self._record(order, 'granted'))) + waiters.append(asyncio.ensure_future(self._record(order, 'next'))) + await _let_pending_tasks_run() + + release.set() + await asyncio.wait_for(asyncio.gather(holder, waiters[1]), WAIT_SECONDS) + + self.assertTrue(waiters[0].cancelled()) + self.assertEqual(['next'], order) + self.assertEqual({}, self._lock._entries) + + async def test_exception_inside_a_turn_releases_it(self): + order: List[str] = [] + + with self.assertRaises(RuntimeError): + async with self._lock.turn('a'): + raise RuntimeError('actor method failed') + + await asyncio.wait_for(self._record(order, 'next'), WAIT_SECONDS) + self.assertEqual(['next'], order) + + async def test_cancelled_turn_releases_it(self): + holder, _ = await self._start_holding() + order: List[str] = [] + waiter = asyncio.ensure_future(self._record(order, 'next')) + await _let_pending_tasks_run() + + holder.cancel() + + await asyncio.wait_for(waiter, WAIT_SECONDS) + self.assertTrue(holder.cancelled()) + self.assertEqual(['next'], order) + + async def test_reentrant_call_enters_once_reentrancy_is_allowed(self): + entered = asyncio.Event() + activated = asyncio.Event() + release = asyncio.Event() + + async def root() -> None: + async with self._lock.turn('a', 'chain') as turn: + entered.set() + await activated.wait() + turn.allow_reentrancy() + await release.wait() + + root_task = asyncio.ensure_future(root()) + await asyncio.wait_for(entered.wait(), WAIT_SECONDS) + order: List[str] = [] + reentrant = asyncio.ensure_future(self._record(order, 'reentrant', reentrancy_id='chain')) + await _let_pending_tasks_run() + + self.assertEqual([], order) + + activated.set() + reentered = await asyncio.wait_for(reentrant, WAIT_SECONDS) + self.assertTrue(reentered) + self.assertEqual(['reentrant'], order) + self.assertFalse(root_task.done()) + release.set() + await asyncio.wait_for(root_task, WAIT_SECONDS) + self.assertEqual({}, self._lock._entries) + + async def test_reentrant_call_skips_queued_callers(self): + holder, release = await self._start_holding(reentrancy_id='chain', allow_reentrancy=True) + order: List[str] = [] + queued = asyncio.ensure_future(self._record(order, 'queued')) + await _let_pending_tasks_run() + + reentered = await asyncio.wait_for( + self._record(order, 'reentrant', reentrancy_id='chain'), WAIT_SECONDS + ) + + self.assertTrue(reentered) + release.set() + await asyncio.wait_for(asyncio.gather(holder, queued), WAIT_SECONDS) + self.assertEqual(['reentrant', 'queued'], order) + + async def test_other_or_missing_reentrancy_ids_wait(self): + for reentrancy_id in (None, '', 'other'): + with self.subTest(reentrancy_id=reentrancy_id): + holder, release = await self._start_holding( + reentrancy_id='chain', allow_reentrancy=True + ) + order: List[str] = [] + waiter = asyncio.ensure_future( + self._record(order, 'waiter', reentrancy_id=reentrancy_id) + ) + await _let_pending_tasks_run() + + self.assertEqual([], order) + + release.set() + _, reentered = await asyncio.wait_for(asyncio.gather(holder, waiter), WAIT_SECONDS) + self.assertFalse(reentered) + self.assertEqual(['waiter'], order) + + async def test_is_in_chain(self): + holder, release = await self._start_holding(reentrancy_id='chain') + + self.assertTrue(self._lock.is_in_chain('a', 'chain')) + self.assertFalse(self._lock.is_in_chain('a', 'other')) + self.assertFalse(self._lock.is_in_chain('a', None)) + self.assertFalse(self._lock.is_in_chain('b', 'chain')) + + release.set() + await asyncio.wait_for(holder, WAIT_SECONDS) + self.assertFalse(self._lock.is_in_chain('a', 'chain')) + + +class ActorTurnLockEventLoopTests(unittest.TestCase): + """Manages its own event loops: IsolatedAsyncioTestCase runs in debug mode, which is too slow + for 10,000 tasks.""" + + def test_long_queue_runs_in_order(self): + lock = ActorTurnLock() + names = [str(index) for index in range(10_000)] + order: List[str] = [] + + async def scenario() -> None: + entered = asyncio.Event() + release = asyncio.Event() + + async def hold() -> None: + async with lock.turn('a'): + entered.set() + await release.wait() + + async def record(name: str) -> None: + async with lock.turn('a'): + order.append(name) + + holder = asyncio.ensure_future(hold()) + await asyncio.wait_for(entered.wait(), WAIT_SECONDS) + waiters = [asyncio.ensure_future(record(name)) for name in names] + await _let_pending_tasks_run() + + release.set() + await asyncio.wait_for(asyncio.gather(holder, *waiters), WAIT_SECONDS) + + asyncio.run(scenario()) + + self.assertEqual(names, order) + self.assertEqual({}, lock._entries) + + def test_waiter_whose_event_loop_closed_is_skipped(self): + async def create_waiter() -> _Waiter: + return _Waiter(None) + + closed_loop = asyncio.new_event_loop() + orphan = closed_loop.run_until_complete(create_waiter()) + closed_loop.close() + lock = ActorTurnLock() + order: List[str] = [] + + async def scenario() -> None: + entered = asyncio.Event() + release = asyncio.Event() + + async def hold() -> None: + async with lock.turn('a'): + entered.set() + await release.wait() + + async def record(name: str) -> None: + async with lock.turn('a'): + order.append(name) + + holder = asyncio.ensure_future(hold()) + await asyncio.wait_for(entered.wait(), WAIT_SECONDS) + lock._entries['a'].waiters.append(orphan) + waiter = asyncio.ensure_future(record('next')) + await _let_pending_tasks_run() + + release.set() + await asyncio.wait_for(asyncio.gather(holder, waiter), WAIT_SECONDS) + + asyncio.run(scenario()) + + self.assertFalse(orphan.granted) + self.assertEqual(['next'], order) + self.assertEqual({}, lock._entries) + + def test_turns_from_threads_with_their_own_event_loops(self): + lock = ActorTurnLock() + counters_lock = threading.Lock() + counters = {'inside': 0, 'max_inside': 0, 'completed': 0} + errors: List[BaseException] = [] + + async def take_turn() -> None: + async with lock.turn('a'): + with counters_lock: + counters['inside'] += 1 + counters['max_inside'] = max(counters['max_inside'], counters['inside']) + await asyncio.sleep(0.005) + with counters_lock: + counters['inside'] -= 1 + counters['completed'] += 1 + + def take_turns() -> None: + try: + for _ in range(5): + asyncio.run(take_turn()) + except BaseException as exception: # noqa: BLE001 + errors.append(exception) + + threads = [threading.Thread(target=take_turns) for _ in range(4)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(WAIT_SECONDS * 2) + + self.assertEqual([], [thread.name for thread in threads if thread.is_alive()]) + self.assertEqual([], errors) + self.assertEqual(1, counters['max_inside']) + self.assertEqual(20, counters['completed']) + self.assertEqual({}, lock._entries) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/actor/test_grpc_host.py b/tests/actor/test_grpc_host.py index 2400ace2b..73a6f7754 100644 --- a/tests/actor/test_grpc_host.py +++ b/tests/actor/test_grpc_host.py @@ -516,8 +516,9 @@ async def test_call_from_dropped_stream_does_not_save_over_new_activation(self): await asyncio.wait_for(HostTestActor.append_held.wait(), 5) stale_tasks = list(self.host._dispatch_tasks) new_stream_gate.set() - replies = await self._await_replies(1) + await self._wait_until(lambda: self._held_activation_id() is None) HostTestActor.append_release.set() + replies = await self._await_replies(1) await asyncio.wait_for(asyncio.gather(*stale_tasks, return_exceptions=True), 5) self.assertEqual('req-fresh', replies[0].invoke_response.id) diff --git a/tests/actor/utils.py b/tests/actor/utils.py index 3918109c8..28ba3e643 100644 --- a/tests/actor/utils.py +++ b/tests/actor/utils.py @@ -12,6 +12,11 @@ async def mock_coro(*args, **kwargs): return mock_coro +async def _let_pending_tasks_run() -> None: + for _ in range(5): + await asyncio.sleep(0) + + def _run(coro): try: loop = asyncio.get_running_loop() diff --git a/tests/integration/apps/actor_grpc_host.py b/tests/integration/apps/actor_grpc_host.py index 32e033fa0..c397db260 100644 --- a/tests/integration/apps/actor_grpc_host.py +++ b/tests/integration/apps/actor_grpc_host.py @@ -22,12 +22,17 @@ import asyncio from datetime import timedelta -from typing import Optional +from typing import Dict, Optional from dapr.actor import Actor, ActorGrpcHost, ActorInterface, Remindable, actormethod -from dapr.actor.runtime.config import ActorRuntimeConfig +from dapr.actor.runtime.config import ActorRuntimeConfig, ActorTypeConfig from dapr.actor.runtime.runtime import ActorRuntime +HOLD_TURN_SECONDS = 1.0 + +# Per actor ID, outside the actor so a reactivation cannot reset them. +_turns: Dict[str, Dict[str, int]] = {} + class GrpcIntegrationActorInterface(ActorInterface): @actormethod(name='GetActivationCount') @@ -120,12 +125,52 @@ async def timer_callback(self, state) -> None: await self._state_manager.save_state() +class TurnHoldingActorInterface(ActorInterface): + @actormethod(name='HoldTurn') + async def hold_turn(self) -> None: ... + + @actormethod(name='GetTurns') + async def get_turns(self) -> object: ... + + +class TurnHoldingActor(Actor, TurnHoldingActorInterface): + """Counts how many HoldTurn calls run at once on each actor ID.""" + + async def hold_turn(self) -> None: + turns = self._turns() + turns['started'] += 1 + turns['running'] += 1 + turns['max_running'] = max(turns['max_running'], turns['running']) + try: + await asyncio.sleep(HOLD_TURN_SECONDS) + finally: + turns['running'] -= 1 + turns['completed'] += 1 + + async def get_turns(self) -> object: + return dict(self._turns()) + + def _turns(self) -> Dict[str, int]: + initial = {'started': 0, 'running': 0, 'max_running': 0, 'completed': 0} + return _turns.setdefault(self.id.id, initial) + + async def main() -> None: - # Short idle timeout so the idle-deactivation test completes quickly. - ActorRuntime.set_actor_config(ActorRuntimeConfig(actor_idle_timeout=timedelta(seconds=3))) + # Short idle timeout so the idle-deactivation test completes quickly. TurnHoldingActor keeps + # a longer one: calls abandoned by their callers leave it idle in daprd's eyes, and an idle + # deactivation would cancel the call that reads the counters. + turn_holding_config = ActorTypeConfig( + TurnHoldingActor.__name__, actor_idle_timeout=timedelta(minutes=5) + ) + ActorRuntime.set_actor_config( + ActorRuntimeConfig( + actor_idle_timeout=timedelta(seconds=3), actor_type_configs=[turn_holding_config] + ) + ) host = ActorGrpcHost() await host.register_actor(GrpcIntegrationActor) + await host.register_actor(TurnHoldingActor) print('GrpcIntegrationActor host started', flush=True) await host.run_forever() diff --git a/tests/integration/test_actor_grpc.py b/tests/integration/test_actor_grpc.py index ac3d86a09..c663a2e8e 100644 --- a/tests/integration/test_actor_grpc.py +++ b/tests/integration/test_actor_grpc.py @@ -25,13 +25,17 @@ """ import asyncio +import contextlib import json import time +import uuid +import httpx import pytest from dapr.actor import ActorId, ActorProxy from tests.actor_grpc_utils import actor_stream_supported +from tests.wait_utils import wait_until GRPC_PORT = 13531 HTTP_PORT = 3531 @@ -40,6 +44,10 @@ ACTOR_TYPE = 'GrpcIntegrationActor' ACTOR_ID = 'integration-1' +TURN_ACTOR_TYPE = 'TurnHoldingActor' +CANCELLED_CALLS = 5 +CANCEL_AFTER_SECONDS = 0.3 + def _invoke(method: str, data: bytes = None): async def _run(): @@ -110,6 +118,25 @@ def test_timer_fires_over_stream(actor_host): assert evidence == {'n': 7} +def test_call_cancelled_by_its_caller_keeps_the_turn(actor_host): + """daprd hands the actor to the next call as soon as a caller gives up, while the + abandoned call is still running in the app; the app must not start the next one.""" + actor_id = uuid.uuid4().hex + actor_url = f'http://127.0.0.1:{HTTP_PORT}/v1.0/actors/{TURN_ACTOR_TYPE}/{actor_id}/method' + + for _ in range(CANCELLED_CALLS): + with contextlib.suppress(httpx.TimeoutException): + httpx.post(f'{actor_url}/HoldTurn', timeout=CANCEL_AFTER_SECONDS) + + def settled_turns(): + turns = httpx.post(f'{actor_url}/GetTurns', timeout=30).json() + settled = turns['started'] > 0 and turns['completed'] == turns['started'] + return turns if settled and turns['running'] == 0 else None + + turns = wait_until(settled_turns, timeout=30, interval=0.5) + assert turns['max_running'] == 1 + + def test_idle_actor_is_deactivated_and_reactivates(actor_host): """The host's idle timeout is 3s; daprd's deactivation scan eventually deactivates the instance and the next invocation activates a fresh one,