Repository navigation
fix(actor): hold an actor's turn until a cancelled call finishes - #1359
AdepuSriCharan wants to merge 3 commits into
Conversation
daprd releases an actor's turn as soon as a caller cancels a call, but the SDK kept running the cancelled method, so the next call ran on the same actor at the same time. Add a per-actor turn lock held from activation through the post-method state save for method calls, timers, reminders and deactivation. It is thread-safe, so it also works with the Flask extension's per-request event loops. A reentrant call enters the running turn only when reentrancy is enabled for the actor type, resolved the same way daprd resolves it. To keep the activation-id guarantees, a new activation id or a DELETE detaches the stale object before waiting for the turn, so a call still running on it skips its save, and a call superseded while waiting is not run. Signed-off-by: Adepu Sri Charan <sricharan.adepu36@gmail.com>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1359 +/- ##
==========================================
+ Coverage 88.72% 88.91% +0.18%
==========================================
Files 166 167 +1
Lines 13632 13878 +246
==========================================
+ Hits 12095 12339 +244
- Misses 1537 1539 +2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved lifecycle races let stale actors overwrite newer state and pending activations survive DELETE, while cleanup failures can be hidden from the DELETE caller.
3 open issues
What changed in this PR
This PR addresses #1346 by adding SDK-side per-actor turn locking so calls abandoned by daprd cannot overlap with subsequent calls. It also integrates turn ordering with the activation-ID handling introduced in #1347.
Changes:
- Adds ordered turn locking across threads and event loops, with support for reentrant calls.
- Applies turns to actor methods, lifecycle hooks, timers, reminders, and post-method state saves.
- Adds concurrency regression coverage and updates activation-replacement tests for serialized execution.
| File | Description |
|---|---|
dapr/actor/runtime/_turn_lock.py |
Implements per-actor turn locking and reentrant admission. |
dapr/actor/runtime/manager.py |
Coordinates turns, activation replacement, and deferred deactivation. |
dapr/actor/runtime/runtime.py |
Resolves actor-type reentrancy settings for turn admission. |
tests/actor/test_actor_turn_lock.py |
Covers ordering, cancellation, reentrancy, and cross-thread locking. |
tests/actor/test_actor_manager.py |
Tests serialized dispatch and activation lifecycle interactions. |
tests/actor/test_actor_reentrancy.py |
Tests global and actor-type reentrancy configuration. |
tests/actor/test_grpc_host.py |
Adapts stream-replacement coverage to serialized calls. |
tests/actor/utils.py |
Adds a helper for yielding to pending tasks. |
tests/integration/apps/actor_grpc_host.py |
Adds an actor that tracks overlapping calls. |
tests/integration/test_actor_grpc.py |
Verifies caller cancellation does not allow overlapping turns. |
Review effort: Balanced
| with self._active_actors_lock: | ||
| detached_on_arrival = self._detach(actor_id.id) |
| with self._active_actors_lock: | ||
| detached = self._detached.pop(actor_id.id, []) | ||
| owned_error: Optional[Exception] = None | ||
| for active in detached: | ||
| try: | ||
| await active.actor._on_deactivate_internal() | ||
| except Exception as exception: # noqa: BLE001 | ||
| if active in owned and not active.replaced: | ||
| owned_error = exception | ||
| continue | ||
| logger.exception('Deactivating detached object for %s failed', actor_id) | ||
| if owned_error is not None: | ||
| raise owned_error |
| if active in owned and not active.replaced: | ||
| owned_error = exception | ||
| continue | ||
| logger.exception('Deactivating detached object for %s failed', actor_id) |
A DELETE that arrived while _on_activate was running let that activation register, save and run its call. The DELETE now stops the activation from registering, and the call fails without running. An object whose _on_deactivate was still running was invisible to a newer activation id, so a save it started afterwards went through. It now stays visible until its hook finishes. When a call queued ahead of a DELETE ran the cleanup and the hook failed, the error was only logged. The DELETE that requested the deactivation now raises it. Signed-off-by: Adepu Sri Charan <sricharan.adepu36@gmail.com>
CasperGN
left a comment
There was a problem hiding this comment.
Thanks a lot @AdepuSriCharan for your interest in Dapr and for taking on #1346, this is a tricky one 🙌 The turn lock is careful work: the hand-off on cancellation, both before and after a waiter is granted, and the cross-loop wake-up with call_soon_threadsafe both hold up. The PR description that lists every behaviour change and every test you touched made it much easier to review. I left one question inline about reentrant calls made from _on_activate, please take a look 👀
Drafted with AI assistance and reviewed by me.
| 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() |
There was a problem hiding this comment.
Reentrancy only opens here, after _enter_turn returns, so a call with the same reentrancy ID waits while _on_activate is still running. If an actor's _on_activate calls another actor that calls back into this one, reentrancy_ctx is already set by ActorRuntime.dispatch, so the callback carries the running turn's ID. It then waits in _acquire (_turn_lock.py L109-118) for an activation that is itself waiting on the callback, so both hang until the HTTP timeout.
While activation runs, only a call started by _on_activate can carry this turn's reentrancy ID. What do you think about failing that call straight away with a DaprInternalError ("called back during activation") instead of queueing it? The caller would get a clear error instead of a timeout. If you'd rather keep the wait, could the docs or the dispatch docstring mention that calling back during _on_activate deadlocks?
A call with the running turn's reentrancy ID enters the turn only after _on_activate returns, as in the .NET SDK. So if _on_activate calls another actor that calls back into this one, both wait until the outbound call times out. Failing the callback instead would also reject a parallel call from the same call chain, which daprd delivers with the same ID. Add a test that pins the wait. Signed-off-by: Adepu Sri Charan <sricharan.adepu36@gmail.com>


Description
When a caller cancels an actor call, daprd releases the actor and sends the next call while the SDK is still running the cancelled one. Two calls then run on the same actor at once (#1346).
This adds a per-actor turn lock to the SDK, like dotnet-sdk#1937 and java-sdk#1877:
asyncio.run()._on_activatestops that activation from being registered, and a stale actor still in_on_deactivatecan't save once a new activation ID arrives.Behaviour changes
_on_activatewaits until activation finishes. So if_on_activatecalls another actor that calls back into this one, both wait until the outbound call times out; onmain, the callback ran on a second instance of the actor. The_on_activateandActorRuntime.dispatchdocstrings say so.DaprInternalErrorwithout running.DaprInternalErrorwithout running, and the activation's state isn't saved.Tests
tests/actor/test_actor_turn_lock.py: 14 tests covering ordering, cancellation, reentrancy and threads running their own event loops.tests/integration/test_actor_grpc.py: Cancels five calls through daprd and verifies that at most one runs at a time.Existing tests changed
Ten #1347 tests previously started a second call or DELETE while the first was paused. With the turn lock, the second call waits, so these tests now start it as a task and await it after the first call finishes.
test_actor_manager.py:test_replaced_method_call_skips_save,test_replaced_timer_skips_save,test_replaced_reminder_skips_savetest_replaced_by_missing_id_call_still_savestest_deactivated_during_call_skips_savetest_late_activation_does_not_overwrite_newer_activation: Now checks the registered activation ID rather than the actor object.test_late_activation_save_does_not_overwrite_newer_activationtest_old_id_registered_during_reset_fails_new_id_calltest_late_activation_with_same_id_reuses_winnerrenamed totest_same_id_call_waits_for_the_running_activation, expecting arrival order['x', 'a', 'b'].test_grpc_host.py:test_call_from_dropped_stream_does_not_save_over_new_activationThe expected stored state remains unchanged.
Validation
test_actor_grpc.pypasses against daprd 1.19.0, and CI runs both suites against 1.18.0. The new integration test fails onmain, confirming the regression coverage.Known limitations
Issue reference
Closes #1346
Checklist