Skip to content

fix(actor): hold an actor's turn until a cancelled call finishes - #1359

Open
AdepuSriCharan wants to merge 3 commits into
dapr:mainfrom
AdepuSriCharan:fix/actor-turn-lock
Open

AdepuSriCharan wants to merge 3 commits into
dapr:mainfrom
AdepuSriCharan:fix/actor-turn-lock

Conversation

@AdepuSriCharan

@AdepuSriCharan AdepuSriCharan commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • What takes a turn: Method calls, timers, reminders, activation and deactivation. Calls for one actor run one at a time, in arrival order, and each holds its turn until the post-method state save finishes.
  • Threads and event loops: The lock works across both, so it also covers the Flask extension, which runs each callback in its own asyncio.run().
  • Reentrancy: A reentrant call joins the running turn only when reentrancy is enabled for that actor type. The SDK resolves this from the config the same way daprd does.
  • Activation IDs (Reset stale actor objects using the daprd activation id #1347): Following the still-open dotnet-sdk#1958, a new activation ID or DELETE detaches the stale actor immediately. A call still running on that actor skips its save, and the stale actor is deactivated during the next turn. A DELETE that arrives during _on_activate stops that activation from being registered, and a stale actor still in _on_deactivate can't save once a new activation ID arrives.

Behaviour changes

  • Calls for one actor ID no longer overlap in the app. Different actor IDs still run in parallel.
  • A DELETE waits for the calls queued before it, then deactivates the actor.
  • Concurrent first calls create a single actor instance.
  • A reentrant call into an actor still in _on_activate waits until activation finishes. So if _on_activate calls another actor that calls back into this one, both wait until the outbound call times out; on main, the callback ran on a second instance of the actor. The _on_activate and ActorRuntime.dispatch docstrings say so.
  • A queued call whose activation ID was superseded fails with DaprInternalError without running.
  • A call whose activation is still running when a DELETE arrives fails with DaprInternalError without 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.
  • 21 new manager tests and 2 runtime tests.
  • 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_save
    • test_replaced_by_missing_id_call_still_saves
    • test_deactivated_during_call_skips_save
    • test_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_activation
    • test_old_id_registered_during_reset_fails_new_id_call
    • test_late_activation_with_same_id_reuses_winner renamed to test_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_activation

The expected stored state remains unchanged.

Validation

  • Reproduced against daprd 1.19.0, with reentrancy enabled and disabled: Five cancelled calls previously ran four at once on FastAPI, Flask and the gRPC host. With this fix, at most one runs at a time.
  • Unit tests: Python 3.10 (2,286 passed, 2 skipped), and CI runs 3.10–3.14. Ruff, formatting and mypy are clean.
  • Integration and examples: test_actor_grpc.py passes against daprd 1.19.0, and CI runs both suites against 1.18.0. The new integration test fails on main, confirming the regression coverage.

Known limitations

  • Calls abandoned by daprd while waiting in the SDK can still run because the Python hosts don't expose caller cancellation.
  • A running call cancelled during gRPC host shutdown may be interrupted rather than finishing its turn.

Issue reference

Closes #1346

Checklist

  • Code compiles correctly
  • Created/updated tests

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>
@AdepuSriCharan
AdepuSriCharan requested review from a team as code owners November 7, 2026 06:14
@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 88.91%. Comparing base (3358174) to head (d35ea80).
⚠️ Report is 2 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@CasperGN CasperGN self-assigned this Nov 7, 2026
@acroca
acroca requested a balanced review from Copilot November 9, 2026 21:15

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread dapr/actor/runtime/manager.py Outdated
Comment on lines +101 to +102
with self._active_actors_lock:
detached_on_arrival = self._detach(actor_id.id)
Comment thread dapr/actor/runtime/manager.py Outdated
Comment on lines +358 to +370
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
Comment thread dapr/actor/runtime/manager.py Outdated
Comment on lines +365 to +368
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 CasperGN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@AdepuSriCharan

Copy link
Copy Markdown
Contributor Author

Thanks for the review @CasperGN I kept the wait to match .NET's turn-lock behaviour, since parallel calls with the same reentrancy ID must also wait. Verified this against daprd 1.19.0. I've documented the behaviour and added a regression test in d35ea80.

@CasperGN CasperGN left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3 of 3: follow-up on the changes since ab2c3a3.

Every earlier blocker is resolved and the new changes add none.

Resolved since the last round: 1.

Drafted with AI assistance and reviewed by me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants