Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Fix DB session reuse across asyncio tasks (#6312)
Shuchang Zheng01f245159a6c
diff --git a/skyvern/forge/sdk/db/base_alchemy_db.py b/skyvern/forge/sdk/db/base_alchemy_db.pyindex 91cbb6179..e16305899 100644--- a/skyvern/forge/sdk/db/base_alchemy_db.py+++ b/skyvern/forge/sdk/db/base_alchemy_db.py@@ -1,6 +1,7 @@import asyncioimport contextvarsfrom contextlib import asynccontextmanager+from dataclasses import dataclassfrom functools import wrapsfrom typing import Any, AsyncContextManager, AsyncIterator, Callable@@ -68,11 +69,17 @@ class BaseAlchemyDB:return False+@dataclass(frozen=True)+class _SessionEntry:+ session: AsyncSession+ task: asyncio.Task[Any] | None++class _SessionFactory:def __init__(self, db: BaseAlchemyDB, sessionmaker: async_sessionmaker[AsyncSession]) -> None:self._db = dbself._sessionmaker = sessionmaker- self._session_ctx: contextvars.ContextVar[AsyncSession | None] = contextvars.ContextVar(+ self._session_ctx: contextvars.ContextVar[_SessionEntry | None] = contextvars.ContextVar("skyvern_db_session",default=None,)@@ -85,13 +92,14 @@ class _SessionFactory:@asynccontextmanagerasync def _session(self) -> AsyncIterator[AsyncSession]:- existing_session = self._session_ctx.get()- if existing_session is not None:- yield existing_session+ existing = self._session_ctx.get()+ current_task = asyncio.current_task()+ if existing is not None and current_task is not None and existing.task is current_task:+ yield existing.sessionreturnsession = self._sessionmaker()- token = self._session_ctx.set(session)+ token = self._session_ctx.set(_SessionEntry(session=session, task=current_task))try:yield sessionfinally:diff --git a/tests/unit/forge/sdk/db/test_session_factory_dedup.py b/tests/unit/forge/sdk/db/test_session_factory_dedup.pynew file mode 100644index 000000000..4fae0d507--- /dev/null+++ b/tests/unit/forge/sdk/db/test_session_factory_dedup.py@@ -0,0 +1,41 @@+import asyncio++import pytest+from sqlalchemy import text+from sqlalchemy.ext.asyncio import create_async_engine++from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB+++async def test_create_task_child_does_not_reuse_session_inherited_before_parent_exit() -> None:+ db = BaseAlchemyDB(create_async_engine("sqlite+aiosqlite:///:memory:"))+ start_child_db_work = asyncio.Event()+ captured = {}++ async def child() -> None:+ await start_child_db_work.wait()+ async with db.Session() as session:+ await session.execute(text("SELECT 1"))+ captured["child"] = session++ async with db.Session() as outer:+ child_task = asyncio.create_task(child())++ start_child_db_work.set()+ await child_task+ await db.engine.dispose()++ assert captured["child"] is not outer+++async def test_none_current_task_does_not_reuse_existing_session(monkeypatch: pytest.MonkeyPatch) -> None:+ db = BaseAlchemyDB(create_async_engine("sqlite+aiosqlite:///:memory:"))+ monkeypatch.setattr(asyncio, "current_task", lambda: None)++ async with db.Session() as outer:+ async with db.Session() as inner:+ assert inner is not outer++ await db.engine.dispose()