Skip to content

Commit 4609e8b

Browse files
committed
PYTHON-5406 - AsyncPeriodicExecutor must reset CSOT contextvars before executing
1 parent 6d33d4f commit 4609e8b

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

pymongo/_asyncio_task.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def cancelling(self) -> int:
4343
return self._cancel_requests
4444

4545

46+
# We can directly pass an empty Context() object to create_task in Python >= 3.11
4647
def create_task(coro: Coroutine[Any, Any, Any], *, name: Optional[str] = None) -> asyncio.Task:
4748
if sys.version_info >= (3, 11):
4849
return asyncio.create_task(coro, name=name)

pymongo/_csot.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@
3232
DEADLINE: ContextVar[float] = ContextVar("DEADLINE", default=float("inf"))
3333

3434

35+
def reset_all() -> None:
36+
TIMEOUT.set(None)
37+
RTT.set(0.0)
38+
DEADLINE.set(float("inf"))
39+
40+
3541
def get_timeout() -> Optional[float]:
3642
return TIMEOUT.get(None)
3743

pymongo/periodic_executor.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import weakref
2424
from typing import Any, Optional
2525

26+
from pymongo import _csot
2627
from pymongo._asyncio_task import create_task
2728
from pymongo.lock import _create_lock
2829

@@ -93,6 +94,8 @@ def skip_sleep(self) -> None:
9394
self._skip_sleep = True
9495

9596
async def _run(self) -> None:
97+
# The CSOT contextvars must be cleared inside the executor task before execution begins
98+
_csot.reset_all()
9699
while not self._stopped:
97100
if self._task and self._task.cancelling(): # type: ignore[unused-ignore, attr-defined]
98101
raise asyncio.CancelledError

0 commit comments

Comments
 (0)